I understood it's a matter of when you have a Global variable like a primitive inside a function (local variable). The Global variable will not be overwritten by the local variable. Like:
let a = 10;
function increase1(a){
a++; }
increase1(a);
console.log('a = ',a);
So that doesn't work. It gives us a = 10 The code bellow works, it gives us a = 11:
let a = 10;
function increase2(){
a++;}
increase2(a);
console.log('a = ',a);
Because it's the same as:
let a = 10;
a++;
console.log('a = ',a);
But why this behaves the same way as the increase1?
let a = 10;
function increase3(x){
x++; }
increase3(a);
console.log('a = ',a);
And why when I try this, I get "undefined"?
console.log('a = ',increase3(a));
Thank you.
Firstly, you need to understand that you have 2 scopes here one is global and other is functional. Imagine scope as a object to which each variable defined within it, is attached as a property. Here function scope is nested within global.
Now variable lookup starts from running scope(context). If variable is not present over there it will keep on looking into outer scopes (not inner) until it finds variable or reach global scope
Now case 1:
let a = 10; //[[globalScope]] = {a: 10}
function increase1(a){ //[[increase1Scope]] = {a : 10} as parameters are local variable to function
a++; } //[[increase1Scope]] = {a: 11}
increase1(a); //here u have passed 10 as a **value** to increase1 param a(you havent passed global variable **"a"** but its value)
console.log('a = ',a); //takes value from its running scope i.e [[globalScope]] which is 10
case 2:
let a = 10; //[[globalScope]] = {a: 10}
function increase2(){ //no parameters so [[increase2Scope]] = {}
a++;} //[[increase2Scope]] don't have a, so look into next outerscope i.e. [[globalScope]] and alter its value to [[globalScope]] = {a: 11}
increase2(a); //as increase2() has no defined parameter so this argument of 10 wont do anything
console.log('a = ',a); //same from [[globalScope]] = {a: 11}
case 3:
let a = 10; //[[globalScope]] = {a: 10}
function increase3(x){ //[[increase1Scope]] = {x: 10}
x++; } //[[increase1Scope]] = {x: 11}
increase3(a); //value 10 get passed to increase3 -> x
console.log('a = ',a); //this time [[globalScope]] = {a: 10}, so 10
Now, As increase3() function is not returning anything, so you are getting undefined
console.log('a = ',increase3(a)); //undefined
To get the desired result, include a return statement in function definition:
function increase3(x){
x++;
return x;
}
Hope it will help. I tried to put something into perspective. I highly recommend you to go through below online JS book. It will certainly help.