I am new to javascipt as I have started learning js now, I am pretty confused with var
that is said to be function scoped and block scoped;
If so then how do we access them outside of that function!? lets say i want to use it from another class (I don't know maybe by creating some object or whatever) (I guess we can't create objects here! because as it is a functional programming based language I guess!:( )
var y = "global";
if (y === "global") {
var y = "block-scoped";
console.log(y); // expected output: block-scoped
}
console.log(y); // expected output: block-scoped
var
is not said to be function scoped.
Variables declared with var
can either be function or Global scoped.
If a variable is declared with let
or const
, then it has block level scope. A block is delimited by {}
or if those symbols are not present, the enclosing function or, if not in a block or a function, then Global.
I've written another post that discusses scope and the scope chain in much greater detail and should help in answering your coding scenario.