Skip to content

Instantly share code, notes, and snippets.

@Micspr
Forked from Shurlow/scope.md
Created September 20, 2018 18:14
Show Gist options
  • Save Micspr/07e4f5905c32b62856d699ba9b0de24e to your computer and use it in GitHub Desktop.
Save Micspr/07e4f5905c32b62856d699ba9b0de24e to your computer and use it in GitHub Desktop.
Scope Lesson Notes

Scope

Objectives

  • Describe what global scope is
  • Describe what local (or lexical) scope is
  • Explain why global scope should be avoided
  • Describe what variable shadowing is
  • Explain how variables are hoisted
  • Explain how an IIFE can help with scope

Guiding Questions

Watch this video about scope: https://www.youtube.com/watch?v=SBwoFkRjZvE

  • Turn to your neighbor and explain what scope refers to in javascript. How are global and local variables different?

    Your answer...

  • What is a global variable? When are they useful? How can they be problematic?

    Your answer...

  • Looking at the following code, identify all the local and global variables:

    var a = 4
    
    function foo(x) {
      var b = x
    }
    
    if(true) {
      var c = false
    }
    
    var d = 123
  • What does it mean when a variable is shadowed?

    What will we see logged to the console?

    var foo = 5;
    
    function logFoo(foo) {
      console.log(foo);
    }
    
    logFoo(2);

    What are the values of a and b when this snippet is run?

    var a = 'red'
    var b = 'blue'
    function go() {
      a = 'yellow'
      var b = 'green'
    }
    go()
  • What things get hoisted in javascript?

    What would we see printed out?

    function hoist() {
      a = 20;
      var b = 100;
    }
    
    hoist();
    
    console.log(a); 
    console.log(b); 
  • How can IIFEs be used to avoid global scope issues?

    Your answer...

For the following questions, refer to this snippet of code:

var people = [
  { name: 'Rufus Harvey' },
  { name: 'Hector Ferguson' },
  { name: 'Pamela Simon' }
]

function sayHello () {
  for (var i = 0; i < people.length; i++) {
    const person = people[i]
    console.log(`Hello, ${person.name}!`)
  }

  console.log(`I said hello to ${i} people.`)
}

sayHello()
  • Which variables are global?

    Your answer...

  • Which variables are scoped to the overall function?

    Your answer...

  • Which variables are scoped to a specific block?

    Your answer...

  • Can they sayHello() function invocation be moved to above the function's definition? Why or why not?

    Your answer...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment