- 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
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
andb
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...
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...