BenRongey / BenApprenticeship

0 stars 0 forks source link

You Don't Know JS - Scopes & Closures #22

Open BenRongey opened 5 years ago

BenRongey commented 5 years ago

Read: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/README.md#you-dont-know-js-scope--closures

Questions:

function foo(a) {
    var b = a;
    return a + b;
}

var c = foo( 2 );
  1. Identify all the left hand side look-ups (there are 3!).

  2. Identify all the right hand side look-ups (there are 4!).

    • Describe how scopes nest in JavaScript. What rules does JavaScript follow when looking for something in a nested scope? Is it possible for an inner scope to be nested within two different outer scopes that don't "overlap"?
    • Why is eval evil?
    • What is the difference between a scope made with function and one made with if?
    • What is "hiding" variables in JS and why might you do it?
    • Give example code showing declarations being "hidden" from the global scope.
    • Give some reasons to avoid declaring things in the global scope.
    • What is an anonymous function? When might you use one? When is it better to use a named function?
    • What's an IIFE?
    • What is "block scope"? How is it different from "function scope"?
    • We prefer let and const over var in our JS code. Why do you think that is?
    • True or false: "hoisting" treats "var x = 3;" as a single statement.
    • What are some ways you can write and organize your code to avoid hoisting-related bugs?
    • On our platform, setTimeout only takes two arguments: arg1 is the function to be called, arg2 is the delay in milliseconds. Write code that will call console.log with the argument "Delayed log" after one second.
    • Describe closures. How do you make one? Closures have an important property with regard to scope. What is it?
    • This code has a bug:
var countdown = [];
for(var i = 5; i >= 0; i--) {
    countdown.push(function() { console.log(i); });
}

for(var j = 0; j < 5; j++) {
    countdown[j]()
}

How would you fix it?