1.18 you don’t know JS

2h Tonight I got into reading you don’t know js on scope and closures. After 2 hours my eyes glazed over, but it was really great while it lasted. I’m going to dig in tomorrow for more. I learned a bunch of things about hoisting, and a bit more about closures. I’m not sure if I don’t understand it, or if I just misunderstand why people think it is hard to understand. hmmm…

here are my short notes.

scope and closure

“ReferenceError is Scope resolution-failure related, whereas TypeError implies
that Scope resolution was successful, but that there was an illegal/impossible
action attempted against the result.”

ReferenceError : the var is not found in this Scope
TypeError: you’re doing something dumb with the variable.

scope shadowing is when you redefine (using var let or const) a global scope var inside a inner level Scope.
The program will not ‘see’ the global scope so it will overwrite it while in the inner Scope.

What is the module pattern? how is it defensive and prevent namespace collisions?

IIFE! immediately invoked function expression.
immediately invoked – run when declared. this is the () part, and it may be optional.
function expression – the name does not exist in the global namespace, Only in the parens.

//instead of
function foo() {
console.log(“not an IIFE”)

//you can do
(function foo() {
console.log(“this IS an IIFE!”)

//you can also make it anonymous
(function() {
console.log(“this IS an IIFE!”)
// anonymous is harder to read in stack traces, harder to add / remove handlers or timeouts on
// and it is hard or impossible to make it recursively call itself.

IIFEs can end in )() OR ()) They both work the same way.

function scoping
vars defined in a function are not accessible outside of that errorFunction

block scoping
vars defined in a block (like a for statement, or an if statement) SHOULD be inaccessible outside that block
use let in order to make sure that is true.

using an iife is a way to hide scope within functions pre es6. is it useful nowadays?

VAR declarations hoist to the top of the scope when compiling
let DOES NOT! so move your lets to the top or get ready for errors.
const is block scoped as well, but it is a constant.

when var assignments are hoisted, only the assignment is hoisted

var x = 4;
gets turned into
var x; //hoisted to top of scope
x = 4; //stays put where it was.

functions are hoisted first, and then variables

Tell me what you think.

This site uses Akismet to reduce spam. Learn how your comment data is processed.