javascript function with parameter code example

Example 1: javascript function variable arguments

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

foo(1,2,3);
//1
//2
//3

Example 2: javascript pass function as parameter

//passing a function as param and calling that function
function goToWork(myCallBackFunction) {
    //do some work here
    myCallBackFunction();
}

function refreshPage() {
    alert("I should be refreshing the page");
}

goToWork(refreshPage);

Example 3: javascript function multiple parameters

function sum(...values) {
    console.log(values);
}
sum(1);
sum(1, 2);
sum(1, 2, 3);
sum(1, 2, 3, 4);


function sum(...values) {
    let sum = 0;
    for (let i = 0; i < values.length; i++) {
        sum += values[i];
    }
  
    return sum;
}
console.log(sum(1)); //1
console.log(sum(1, 2)); //3
console.log(sum(1, 2, 3)); // 5
console.log(sum(1, 2, 3, 4)); //10

Example 4: parameters in javascript

function myFunction(x, y) {
  if (y === undefined) {
    y = 2;
  }
}

Example 5: how to create a function with parameters in JavaScript

function name(param, param2, param3) {

}

Example 6: js running function as parameter

function FuncOne(param1) //example function
{
  //Do whatever
}

function FuncTwo(FuncOne, param1) //Function to call FuncOne w/ param
{
  FuncOne(param1); //Write it like you would any normal function call
}