Question about 'Scope'

Check out my Training_Days JS project app and offer your advice, tips, compliments, and critiques:

Training_Days.js

My question about scope is: When a variable is defined outside a function it is global, when it is defined in a function it is local. what is the difference between being defined at the top of the function block and in the if / else block ?

Hello @paulgureghian, as far as I know, scope only refers to the variables’ location in terms of functions. If a variable is defined in a function, it is local. If not, it is global:

function a(){
let a = " ";//local scope
if (a) {
let b = " ";//local scope
}
}

let c = " ";//global scope
if (c) {
let d = " ";//local scope
}

The let keyword follows scope rules. The var keyword, however does not:

if (true) {
var a = "the" //global because of var
}

I hope this helps!

In actuality, var does affect scope, but only inside a function body, not any of the other block constructs.

1 Like