javascript arguments code example

Example 1: javascript x number of parameters

function display_numbers(...numbers) {
	colors.forEach(function(x) {
  		console.log(x);
	});
}

// call it like:
display_numbers(1)
display_numbers(1, 2, 3, 4)
display_numbers(1, -1, 9, 0, 2)

Example 2: 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 3: 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 4: arguments object in javascript

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

addAll(1, 2, 3, 4, 5, 6, 7, 8, 9,10); //we can provide inifite numbers as argument

Example 5: how to access any argument in javascript

function example() {
	console.log(arguments);
  	console.log(arguments[0]);
} // Console outputs an array of each argument with its value

example('hi', 'hello'); 
// Outputs: 
// ['hi', 'hello']
// 'hi'

Example 6: parameters in javascript

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

Tags:

Java Example