Variables (let, const, var) Flashcards

1
Q

let vs var vs const scope

A
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
var i = 10;
let animals = ['gbear', 'lbear'];
for(var i = 0; i < anilams.length; i++){
   do smth;
}

console.log(i);

A

2

if we used let instead of var in the for loop - the answer would be 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

nested functions

A
  1. we call outer(), we can’t call inner() directly
  2. inner() is only called if it is not only declared but also invoked insided outer()
  3. the variables of outer() are visible in inner()
  4. if we declare a variable with the same name in inner as in outer - the one in inner will be taken
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

hoisting and var/let/const

A
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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly