4) JS Var. Scope & Hoisting Flashcards
Explain Scope.
Give a clear example of scope in action.
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”};
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?
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.
Is a variable declared inside a for loop considered a global scoped variable or a locally scoped variable?
It’s considered a globally scoped variable.
Explain Hoisting.
Easy. Hoisting occurs everytime you declare a variable inside a function. The variables declaration goes to the top of the function.