javascript arguments function 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: js unspecified parameters

function my_log(...args) {
     // args is an Array
     console.log(args);
     // You can pass this array as parameters to another function
     console.log(...args);
}

Example 3: parameters types in javascript

/**
 * My function description
 * @param {String} a
 * @param {String} b
 * @param {Number} amount
 * @example
 * // returns "fooBar fooBar"
 * myFunction('foo', 'Bar', 2)
 * @returns {String}
 */
function myFunction(a, b, amount){
  //do stuff
}
//Note that javascript is not a statically typed language and therefore you
//will not recieve any syntax errors for passing in the wrong types.
//The above code works in Visual Studio Code and intellisense.

Example 4: 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 5: parameters in javascript

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

Tags:

Java Example