Skip to content

Instantly share code, notes, and snippets.

@brittanydionigi
Created August 22, 2018 14:00
Show Gist options
  • Save brittanydionigi/8376c9eb659604dc6f2b8eee5672efdc to your computer and use it in GitHub Desktop.
Save brittanydionigi/8376c9eb659604dc6f2b8eee5672efdc to your computer and use it in GitHub Desktop.

Scope Practice

For each exercise, tell me in what order each of the logs are executed, and what each of them will actually log.

In order to complete these exercises, you must understand the following concepts:

  • hoisting
  • variable assignment/reassignment vs. variable declaration
  • the three scoping levels: global, functional and block
  • the scoping levels that var/let/const adhere to
  • the order in which JavaScript is read and executed

let num = 10;

function foo() {
    if (num > 5) {
       num = 7;
    }
    console.log('A:', num);
}

foo();

console.log('B: ', num);

Bonus Challenges:

  • What would happen if we changed let to const?
  • What would happen if we added var in front of num = 7?

let grade = 100;

function losePoints() {
  grade = 90;

  function addPoints() {
    const grade = 95;

    if (grade === 95) {
      let grade = 97;
    }

    console.log('A: ', grade);
  }

  addPoints();

  console.log('B: ', grade);
}

losePoints();

console.log('C: ', grade);

var num = 5;

function first() {
  console.log('A: ', num);
  num = 6;
  console.log('B: ', num);
}

function second() {
  console.log('C: ', num);
  let num = 7;
}

first();
second();

console.log('D: ', num);

var instructor = 'Pam';

function changeInstructor() {

  console.log('A: ', instructor);

  if (instructor === 'Brittany') {
    const instructor = 'Nathaniel';
  } else {
    let instructor = 'Brittany';
  }

  console.log('B: ', instructor);

  function rename() {
    instructor = 'Louisa';
    console.log('C: ', instructor);
  }

  rename();

  console.log('D: ', instructor);

}

console.log('E: ', instructor);

changeInstructor();

console.log('F: ', instructor);

var shoe = 'flipflop';

function putOnShoe() {
  console.log('A: ', shoe);
  var shoe = 'boot';
}

console.log('B: ', shoe);
putOnShoe();
console.log('C: ', shoe);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment