Variables (let, const, var) Flashcards
let vs var vs const scope
if(true){ var animal = 'eel'; console.log(animal); }
console.log(animal);
this will print animal twice, no errors
but const and let are scoped, so if we use them here instead of var, they will be only printed once and then there will be undefined error
var i = 10; let animals = ['gbear', 'lbear']; for(var i = 0; i < anilams.length; i++){ do smth; }
console.log(i);
2
if we used let instead of var in the for loop - the answer would be 10
nested functions
- we call outer(), we can’t call inner() directly
- inner() is only called if it is not only declared but also invoked insided outer()
- the variables of outer() are visible in inner()
- if we declare a variable with the same name in inner as in outer - the one in inner will be taken
hoisting and var/let/const
console.log(animal); var animal = "Bear";
will print undefined in the console. And there will be no exception thrown.
The interpreter rearranges the code to this:
var animal; //variable is undefined
console.log(animal);
animal = “Bear”;
this is called hoisting.
And it doesn’t work for let and const. If we use them in place of var - there will be exception thrown instead (UncaughtReferenceError)