Goutham Sai Goutham Sai - 5 months ago 29
Javascript Question

Logic behind the two javascript function behaviour

Please explain what is the logic behind this two types of behaviour to understand easily.

var a = 10;
function foo(){
a = 20;
}
foo();
console.log(a);


Prints---> a = 20;

var a = 10;
function foo(a){
a = 20;
}
foo();
console.log(a);


Prints---> a = 10;

Answer Source

In the first example a in the function is replacing the first declaration of a outside the function because you're not scoping it locally with var (or let or const).

In the second example the function accepts a as an argument so it becomes scoped locally to the function. Note that this occurs even if a isn't actually passed into the function (and is therefore undefined).

A good article on scope and context that might be of some use to you.