Check out my 'Training_Days JS project app and offer your advice, tips, critiques …
Training_Days.js
My question about scope is: If a variable is outside of a function it is globally scoped, if it is inside a function it is locally scoped / block scope. what is the classification of a locally scoped variable at the top of the function code block and a variable in the if/else statements ?
There is more than just scope for a function and for a variable. For let
and const
, any set of {}
creates a scope. For these variables, the scope is local to the containing {}
.
function sumThese(lower, upper) {
// upper, lower, and sum are local to the function
let sum = 0;
for (let i = lower; i <= upper; i++) {
// i is local to this loop
sum += i;
}
}
// These guys have global scope
let num1 = 5;
let num2 = 10;
console.log(sumThese(num1, num2));
1: what is the classification of a locally scoped variable at the top of the function code block
If it’s before the function it’s globally if it’s inside the function it’s locally
a variable in the if/else statements ?
If else is ussually in the function so localy
Also the local variable will overide the global one
Lexical scope is pretty simple: a variable has the scope of whatever pair of curly braces it’s in. That’s it. Variables declared deeper in will shadow those further out.
1 Like