[JS] global vs const vs var vs let

Here’s an example of how to use each one of the above keywords.

function getProgramName() {
    programName = "ABC";
}

getProgramName();
console.log("Program name: " + programName);

As the programName variable is not prefixed with var, let or const it is a global variable with a global scope. Meaning that it is visible anywhere in the script regardless it is being accessed inside any function.

On the other hand, the const keyword has a local scope and is used to define variables that won’t be modified EVER.

function getPI() {
    const PI = 3.14;
    return PI;
}

getPI();
console.log("PI: " + PI);

So, if you try to assign another value to the const variable an error will be thrown.

function getPI() {
    const PI = 3.14;

    if (true) {
      PI = 3.15;
    }

    return PI;
}

getPI();
console.log("PI: " + getPI());

>> error: Uncaught TypeError: Assignment to constant variable.

Regarding the var statement, the scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.

function foo() 
  var x = 1;  
  function bar() {
    var y = 2;
    console.log(x); // 1 (function `bar` closes over `x`)
    console.log(y); // 2 (`y` is in scope)
  }
  bar();
  console.log(x); // 1 (`x` is in scope)
  console.log(y); // ReferenceError in strict mode, `y` is scoped to `bar`
}

foo();

Finally, the let statement declares a block-scoped local variable, optionally initializing it to a value.

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 1

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Leave a comment

Your email address will not be published. Required fields are marked *