Scopes Flashcards
What will the below code print out? "use strict"; var name = 'igloo'; var code = "var name = 'asim';" eval(code) console.log(name)
igloo
// What will this code print? (function(){ var a = 3; })(); console.log("a defined? " + (typeof a !== 'undefined'));
a defined false
// What will this code print? console.log(moo); var moo = function() { console.log("loo"); };
undefined
for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function(){ console.log(i); }); document.body.appendChild(btn); } // What gets logged to the console when the user clicks on “Button 4”?
5
console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(4));
This is an IIFE that actually performs a factorial, so 4! which is 24
// Consider the code snippet below. What will the console output be? (function(x) { return (function(y) { console.log(x); })(2) })(1);
Javascript searches the functions outer scope and in there it will find x and the value of x is 1 since that is what was passed in through the IIFE.
// Consider the code snippet below. What will the console output? function loo() { var goo = 1; moo(); } function moo() { console.log(goo); } loo();
The goo variable isn’t visible on the moo function due to scope lookup rules.
uncaught REferenceError: goo not defined
// What will be the output of first console.log in the code below?
var salary = “1000$”;
(function () {
console.log(“Original salary was “ + salary);
var salary = “5000$”;
console.log(“My New Salary “ + salary);
})();
The var salary in the IIFE is hoisted to the top of the function scope, so that means that salary is set to undefined by the time the first console.log is run
Original Salary was undeffined
// What happens when you execute the code below a = 1;
It creates a global variable called “a”
// What does this print out? console.log(typeof(null));
Object
Can closures refer to variables inside functions (outer scopes)
yes
Can closures refer to variables even after the function has been returned?
Yes (only current value of variables)
10
10
10
Why? Because the closure points to the actual value of i in the outer scope (after the for loop has finished)
var foo = []; for(var i =0; i < 10; i++){ // use a intimidate invoked function // (function(){ var y = i; foo[i] = function() {return y}; })(); } console.log(foo[0]()); console.log(foo[1]()); console.log(foo[2]());
// improve // var foo = []; for(var i =0; i < 10; i++){ // use a intimidate invoked function // (function(){ var y = i; foo[i] = function() {return y}; })(); }
var foo = []; for(var i =0; i < 10; i++){ (function(y){ foo[y] = function() {return y}; })(i); }