javascript arguments object 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: 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 4: js array as parameter

function myFunction(a, b, c) {//number of parameters should match number of items in your array
  	//simple use example
  	console.log("a: " + a);
  	console.log("b: " + b);
  	console.log("c: " + c);
}

var myArray = [1, -3, "Hello"];//define your array
myFunction.apply(this, myArray);//call function

Example 5: arguments object in javascript

function test(a, b, c){
    // console.log(arguments);
    // console.log(JSON.stringify(arguments));
    // console.log(typeof a);

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

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

test(10, 20, 30);

Tags:

C Example