Mastering Fundamentals: JavaScript & Browser Internals
Whether you're building real-time dashboards or debugging a UI bug, JavaScript is where everything begins. Let's look at the JavaScript fundamentals useful in daily development and even in technical interviews.
๐ Table of Contents:
- Hoisting, Scoping & Closures
- Promises, Async/Await & The Event Loop
- Understanding this, call, apply, and bind
- Browser & Memory management
- Performance Tuning
๐ Hoisting, Scoping & Closures
๐ Intro: Why Did That Variable Show as undefined?
You write a function, declare a variable halfway down, but it somehow exists at the top - even if it’s undefined. Or maybe you accidentally created a global variable without realising it. Sound familiar?
These weird behaviours come down to hoisting, scoping, and closures - three foundational JavaScript concepts that control how and when variables are available. Knowing how they interact helps you write safer, clearer code.
๐ง What Is a Closure?
A closure is a function that remembers the variables from its lexical (surrounding) scope - even after that outer function has finished running.
๐งช How Does Closure Preserve State?
A closure retains access to variables in its original scope. This allows private variables and functions - like in counters, debounce utilities, or React hooks.
❓Interview:
Q: Write a function that returns a counter. Each call to the function should return the next number.
๐ป Example:
๐ฌ Gotcha to Watch For:
- Closures can sometimes cause memory leaks if you accidentally retain large DOM elements or objects in the closed-over scope.
๐ง What Is Hoisting?
Hoisting means that JavaScript moves declarations (not assignments) to the top of their scope during the compile phase, before any code is executed.
The declaration is hoisted and assignment happens later, so a variable can be used before it has been declared with undefined.
The declaration is hoisted. In case of Let, it’s not initialised until the engine reaches that line. So accessing it before that is illegal → Reference Error (not undefined!) Same for const, with the added rule: it must be initialised at the time of declaration otherwise the code will not run.
❓Interview:
Q: Why does calling a function expression before its definition cause an error?
๐ป Example: Hoisting
>>> Var, Let, Const & function Hoisting
๐ง What is Scope?
- Always use
let
orconst
unless you need function-level scoping. - var does not respect { } blocks like if, for, or while — unless they're inside a function.
- Use
const
by default and only uselet
when you know the value will change.
⏳Coming up next: Async programming in JavaScript >>>
How’s the pace so far? If anything feels too fast or too basic, drop a comment and I’ll adjust accordingly. Thanks :)
ReplyDelete