4) JS Var. Scope & Hoisting Flashcards

1
Q

Explain Scope.

Give a clear example of scope in action.

A

Global and local Scope.

The scope determines whether you have access to a variable or not, as all variables have either a local or global scope.

JS has function-level scope. So variables can either be defined inside or outside a function.

A clear exampel would be that if you created a variable name = john, and console.logged( name ) you’d always get “john”, UNLESS you modified john in the scope in which you created it. How coudl you modify the variable name? You could use an if statement, if(name){name=”louis”};

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

Which of the two has priority inside a function, variables that are defined in the global scope or variables defined inside the function itself?

What is the one ridiculously interesting thing about variables that you should know as it relates to global declaration or not?

A

Obviously the variables declared inside the function/local scope.

Variables that are initialized in the local scope without being declared with a var keyword are considered global scope variables!

So see below:

function runMarathon( ){

  • runner1* = “matt”
  • runner2* = “john”

}

Because both runners were never declared with a var keyword we must assume they are and that is easy because they are in fact automatically created outside the function when yu do this.

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

Is a variable declared inside a for loop considered a global scoped variable or a locally scoped variable?

A

It’s considered a globally scoped variable.

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

Explain Hoisting.

A

Easy. Hoisting occurs everytime you declare a variable inside a function. The variables declaration goes to the top of the function.

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