Friday, December 18, 2020

[JavaScript][example] arguments object

 "arguments" is an object which is Array-liked. By using "arguments" object you can access the values you passed to the function.


example 1:

<script>

function testFunc(num1, num2, num3, num4) {

  console.log(arguments[0]+","+arguments[1]+","+arguments[2]+","+arguments[3]);

}

testFunc(9, 8, 7, 6);

</script>

result : "9,8,7,6"


example 2:

From this example you would found there is no visable paramter at function defination at line 1:

<script>

function average(){

    var sum = 0;

    for (let index in arguments){

        sum += arguments[index];

    }

    return sum / arguments.length;

}

console.log(average(1,2,3,4,5,6,7))

</script>

If you use sort() function which is Array built-in function, it causes "Uncaught TypeError: arguments.sort is not a function"

<script>

function average(){

    arguments.sort(); // causes error

}

console.log(average(1,2,3,4,5,6,7))

</script>

this is a local variable with all non-arrow function, 

let test that in arrow format:

<script>

var test = ()=>{

  console.log(arguments); //causes error: "Uncaught ReferenceError: arguments is not defined"

}

test(5,4,3,2,1)

</script>




Remarks

Beware that the "arguments" is not a real array, (if you use typeof to check would found it's an object)

that mean you cannot use Js Array's built-in method such as forEach(), otherwise you would get a function not found error.


1 comment :