Web/JavaScript

(JavaScript) Scope Chain

haramang 2021. 10. 31. 11:13

 

'use strict';

 

function calcAge(birthYear) {

  const age = 2037 - birthYear;

  console.log(firstName); // Global variable

 

  function printAge() {

    let output = `You are ${age}, born in ${birthYear}`;

    console.log(output);

 

    if (birthYear >= 1981 && birthYear <= 1996) {

      var millenial = true;

 

      // Create a new variable with same name as outer scope's variable

      const firstName = 'Steve'; // It first loop up in this scope and if it is not there it is looking up

      // In this case, we have first name Steve - so firstname is steve

 

      // Reassigning outer scope's variable

      output = 'NEW OUTPUT';

 

      const str = `Oh, and you're a millenial, ${firstName}`;

      console.log(str);

 

      function add(a, b) {

        return a + b;

      }

    }

    // console.log(str);       // block scope

    console.log(millenial); // var is a function scope - ignore block scope

    // console.log(add(2, 3)); // add function is in the block scope - cannot be accessed

    // but, without a 'use strict' it is a function scope - can be accessed

    console.log(output);

  }

 

  printAge();

 

  return age;

}

 

// console.log(millenial); // it is in the function scope, cannot be accessed.

 

const firstName = 'Hongsik';

calcAge(1988);

// console.log(age);    // cannot be accessed because age is in inner scope

// printAge();          // cannot be accessed because it is in function calcAge