I've just read the answers for this question about 'setting global variables inside a function' but I still have a doubt.
This maybe is very basic but can someone tell me why an error does not occur when I do this? I understand that what is passed to the function is a copy of the value of the variable i, but... why
var i = 5;
function exp(i) {
i = 7;
console.log(i);
}
exp(i);
//logs 7
or
function exp(i) {
return i = 7;
console.log(i);
}
exp(5)
//logs 7
and:
function exp() {
return 5 = 7; //or console.log(5 = 7);
}
exp()//Uncaught ReferenceError: Invalid left-hand side in assignment
In the first example am I not making 5 = 7? Why the function logs '7'?
This all came up after I've seen this example in the wonderful JavaScript Garden about local variables:
// global scope
var foo = 1;
var bar = 2;
var i = 2;
function test(i) {
// local scope of the function test
i = 5;
var foo = 3;
bar = 4;
}
test(10);
Why test(10) which sets 10 = 5 inside the function does not make an error?