Global/Local Variable Scope Question


#1

Simple question: Why does this code print out North Star? I thought the star variable should only be accessible from within the if block of code - - and not available to the console.log(star) - - so this code should produce an undefined error?

if(true){
  var star = 'North Star';
}
console.log(star);

#2

var gives a functional scope, what you are talking about is block scope.


#3

Here is what the course text states:

Because of the challenges with global scope, it is preferable to define variables in block scope.

A block refers to the {} braces of a function, a loop, or an if statement, and serves as an important structural marker for our code. Block scope means that a variable defined in the block is only accessible within the curly braces.

Does this not hold for variables defined as var?


#4

functional scope can also be useful, if used with care

There are a couple of terms here:
block scope
functional scope
local variable
global variable

block scope can be created with let and const in Javascript.

functional scope can be created with var.

Global variable can be created with var, let and const

lets do an example:

var a = "aa";  // global variable
let b = "bb";   // global variable
const c = "cc";// global variable

function example(){
  if (true){
     var d = "dd";  // local variable with functional scope
     let e = "ee";   // global variable with block scope
     const f = "ff";// global variable with block scope
    console.log("block", a, b, c, d, e, f); // this goes fine
  }
  console.log("function", a, b, c, d);
  // d exist within the function, so we can log it
  // attempting to log e or f will give error
  // given they only exist in if clause
  // console.log(e, f);
  // feel free to try
}
example(); // execute function
console.log("global", a, b, c);
// attempting to log d, e or f will give error
// given its outside the scope. 
// console.log(d, e, f);

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.