singularity

Scope

Lexical scope

  var todoList = ["grocery", "exercise", "meeting"];

  function emptyTodoList() {
    todoList = [];
  }

  console.log(window.hasOwnProperty("todoList")); 
  // true
  console.log(window.hasOwnProperty("emptyTodoList")); 
  // true
  const todoList = ["grocery", "exercise", "meeting"];

  let emptyTodoList = function () {
    todoList = [];
  };

  console.log(window.hasOwnProperty("todoList")); 
  // false
  console.log(window.hasOwnProperty("emptyTodoList")); 
  // false

Avoid polluting the global scope

Implicit globals

function printSquare(num) {
  result = num * num;
  console.log(result);
}

printSquare(9);

console.log("implicit global "+ result)

HTML attributes

<h1 id="mainHeading">Hello World!</h1>

Shadowing declarations

Function (parameter) scope

function paramScope(arr=["initial array"], buff=()=>arr) {
var arr = [1, 2, 3];
console.log(arr); // [1, 2, 3]
console.log(buff()); // ["initial array"]
}

paramScope();

function paramScope(arr=["initial array"], buff=()=> arr) {
  arr = [1, 2, 3];
  console.log(arr); // [1, 2, 3]
  console.log(buff()); // [1, 2, 3]
}

paramScope();

Function expression name scope

let fn = function namedFn() {
  // code ...
};
let fn = function namedFn() {
  let namedFn = 123;
  console.log(namedFn); // 123
};

Block Scope

Module Scope

Scope Chain