viery365
viery365

Reputation: 965

Function parameter as a number for a local variable name

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?

Upvotes: 1

Views: 81

Answers (2)

Jorawar Singh
Jorawar Singh

Reputation: 7621

your first method

var i = 5;

function exp(i) {
    i = 7;
    console.log(i);//of course it prints 7, i belong to exp scope
}
console.log(i)//it will print five
exp(i);

you are not giving new value to i variable but just to parameter you got

function exp() {
  return 5 = 7; //or console.log(5 = 7);
}

your trying to returnn 5 = 7; what's 5? In Javascript if you are not using "strict mode" then you can declare variable without var keyword, but variable name cannot start with number.

function exp() {
      return 5 + 7; //or console.log(5 + 7);//this will work
 }
 function exp(i) {
      i = 5
     return i = 7; //or console.log(5 + 7);//this will work
 }

Upvotes: 1

user5116395
user5116395

Reputation:

You can't do 5 = 7. 5 will always be 5.

i = 7 equals to set var i as 7

Upvotes: 2

Related Questions