🚀 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: call(), apply(), 𝗮𝗻𝗱 bind() 𝘄𝗶𝘁𝗵 this! Ready to take your JavaScript skills to the next level? 🦸♂️ Understanding this is one of the biggest hurdles for devs, but when you learn how to control it using call(), apply(), and bind(), you'll unlock new superpowers in your code! 🧑💻💥 Let’s break it down with examples that put this in the spotlight: ✨ 1. call() — 𝗧𝗵𝗲 𝗖𝗼𝗻𝘁𝗲𝘅𝘁 𝗖𝗵𝗮𝗻𝗴𝗲𝗿 ⚡ The call() method is like a magic wand that changes the this value to something you specify—𝘢𝘯𝘥 you pass arguments one by one. const person = { name: 'Alice', greet: function(age) { console.log(`Hi, I'm ${this.name} and I'm ${age} years old.`); } }; // Using `call()` to set `this` to `person` and pass arguments individually person.greet.call({ name: 'Bob' }, 25); // Output: "Hi, I'm Bob and I'm 25 years old." 🔑 𝗛𝗼𝘄 𝗜𝘁 𝗪𝗼𝗿𝗸𝘀: Here, this inside greet() is set to { name: 'Bob' }, not the original person object. ✨ 2. apply() — 𝗧𝗵𝗲 𝗔𝗿𝗿𝗮𝘆 𝗟𝗼𝘃𝗲𝗿 🧳 apply() works similarly to call(), but instead of passing arguments one by one, you send them as an 𝗮𝗿𝗿𝗮𝘆. It’s perfect for when you need to handle multiple arguments dynamically! const person = { name: 'Alice', greet: function(city, country) { console.log(`Hi, I'm ${this.name} from ${city}, ${country}.`); } }; // Using `apply()` to pass arguments as an array and change `this` person.greet.apply({ name: 'Charlie' }, ['New York', 'USA']); // Output: "Hi, I'm Charlie from New York, USA." 🔑 𝗛𝗼𝘄 𝗜𝘁 𝗪𝗼𝗿𝗸𝘀: Again, the this context is set to { name: 'Charlie' }, and the arguments ['New York', 'USA'] are passed as an array. ✨ 3. bind() — 𝗧𝗵𝗲 𝗧𝗶𝗺𝗲 𝗧𝗿𝗮𝘃𝗲𝗹𝗲𝗿 ⏳ What if you need to "freeze" a function with a specific this context, but don’t want to call it immediately? That’s what bind() is for. It creates a new function that you can invoke later with a fixed this and pre-set arguments. const person = { name: 'Alice', greet: function(age) { console.log(`Hi, I'm ${this.name} and I'm ${age} years old.`); } }; // Using `bind()` to create a function that is "pre-bound" to `Alice` const greetAlice = person.greet.bind({ name: 'Alice' }); // Later, call the pre-bound function greetAlice(30); // Output: "Hi, I'm Alice and I'm 30 years old." 🔑 𝗛𝗼𝘄 𝗜𝘁 𝗪𝗼𝗿𝗸𝘀: With bind(), this is always set to { name: 'Alice' }, no matter when you call the function! 💡 𝗪𝗵𝘆 𝗬𝗼𝘂 𝗦𝗵𝗼𝘂𝗹𝗱 𝗖𝗮𝗿𝗲: • call() and apply() are perfect for when you want to invoke a function with a specific context immediately, and pass dynamic arguments. • bind() is your go-to for creating "pre-bound" functions that remember their this context when invoked later! #JavaScript #WebDev #CodingTips #JS #TechTalk #WebDevelopment #LearnToCode #DevLife #call #apply #bind
Mastering call(), apply(), and bind() in JavaScript
More Relevant Posts
-
Today I learned about two very important concepts in JavaScript --string and arrays. 1. STRINGS A strong is a sequence of characters used to represent text. eg: let str = "Vineet Nagar"; we can store text, numbers, or any characters inside it. (I) str.length: gives the total number of characters. (II) We can access any character using its index (like str[1] or str charAt(1).) => Common String Methods: (I) /n: moves text to a new line (II)\t: adds extra space or tab. (III)toUpperCase()/toLowerCase(): converts text to upper or lower case. (IV)trim(): removes extra spaces from the start and end. (V)slice(start, end): extracts a part of the string. (VI)concat(): joins two strings. (VII)replace(old, new): replaces a specific part of string . (VIII)charAt(index): returns the character at a given position. NOTE: Strings are immutable, meaning we can't directly change a specific character in them. 2. ARRAYS An array is a collection of items(numbers, strings, etc). eg: let arr = [96, 75, 48, 83, 66]; Each item has an index starting from 0. Unlike strings, arrays are mutable, so we can add, remove, or modify elements. => Common Array Methods: (I)push(): adds an element at the end. (II)pop(): removes the last element. (III)toString(): converts the array into a string. (IV)concat(): joins two arrays. (V)unshift(): adds an element at the beginning. (VI)shift(): removes the first element. (VII)slice(): returns a portion of the array. (VIII)splice(start, deletecount, newitem): removes and/or adds elements in between. NOTE: Arrays are mutable.
To view or add a comment, sign in
-
-
In JavaScript, let arr = [] is not an array! This looks like an array, but it's not. At least, not in the way a C++ or Rust developer would define one. This distinction is crucial for understanding JS performance. 🖥️ The "Real" Array (Low-Level) In low-level languages, an array is a fixed-size, contiguous block of memory. If you declare [i32; 4] in Rust, you allocate exactly 128 bits (4 * 32-bit integers). - Pro: Extremely fast and memory-predictable. - Con: It's rigid. You can't just .append(). There's no guarantee the memory slot "next door" is free. 🧙♂️ The JavaScript "Array" (High-Level) A JS Array is actually a highly optimized, dynamic Object in disguise. The engine (like V8) is smart. It runs "optimizations" based on how you use the array. It generally picks between two internal structures: 1. The "Fast" Mode (Dynamic Array) - When: You use it sequentially (e.t., .push(), .pop()). - How: The engine allocates a contiguous block of memory with extra capacity (just like a Rust Vec or C++ std::vector). - The Catch: When that capacity runs out, the engine must allocate a new, larger block and copy all the old elements over. - This is why push() is usually O(1) (amortized), but sometimes O(n). 2. The "Slow" Mode (Hash Map) - When: You create a sparse array (e.g., arr[0] = 1; arr[1000] = 2;). - How: The engine sees this and gives up on the contiguous block. It's a waste of memory. - It switches the array's internal structure to a hash map (or dictionary). It only stores the key-value pairs that actually exist ('0': 1, '1000': 2). The Takeaway JavaScript trades the raw memory predictability of a C/Rust array for incredible developer flexibility. It's not a simple memory block; it's a sophisticated data structure managed by the engine, constantly adapting to your code. Knowing when it might be a fast array vs. a slow hash map is key to writing high-performance JS. #JavaScript #V8 #NodeJs #SoftwareArchitecture #Performance #DataStructures #JSEngine #TypeScript
To view or add a comment, sign in
-
💥 𝗠𝗮𝘀𝘁𝗲𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗔𝗿𝗿𝗮𝘆 𝗠𝗲𝘁𝗵𝗼𝗱𝘀: 𝗧𝗵𝗲 𝗨𝗹𝘁𝗶𝗺𝗮𝘁𝗲 𝗚𝘂𝗶𝗱𝗲 𝗳𝗼𝗿 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 💻 If you work with JavaScript, you work with arrays. But are you truly using their full potential? Here’s a quick-hit guide to the most powerful and frequently used array methods every JS developer should know: 🔁 𝗖𝗼𝗻𝘃𝗲𝗿𝘁 & 𝗖𝗼𝗺𝗯𝗶𝗻𝗲 𝘁𝗼𝗦𝘁𝗿𝗶𝗻𝗴() → Converts array to string 𝗷𝗼𝗶𝗻() → Join elements with a custom separator 𝗰𝗼𝗻𝗰𝗮𝘁() → Merge arrays 𝗔𝗿𝗿𝗮𝘆.𝗳𝗿𝗼𝗺() → Convert iterable/array-like objects ➕➖ 𝗔𝗱𝗱 / 𝗥𝗲𝗺𝗼𝘃𝗲 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 𝗽𝘂𝘀𝗵() / 𝗽𝗼𝗽() → Add/remove at the end 𝘂𝗻𝘀𝗵𝗶𝗳𝘁() / 𝘀𝗵𝗶𝗳𝘁() → Add/remove at the start 𝘀𝗽𝗹𝗶𝗰𝗲() → Insert/remove anywhere 𝘀𝗹𝗶𝗰𝗲() → Copy a portion 𝗱𝗲𝗹𝗲𝘁𝗲 → Remove item (⚠️ leaves hole!) 🔍 𝗦𝗲𝗮𝗿𝗰𝗵 & 𝗖𝗵𝗲𝗰𝗸 𝗶𝗻𝗱𝗲𝘅𝗢𝗳() / 𝗹𝗮𝘀𝘁𝗜𝗻𝗱𝗲𝘅𝗢𝗳() → Find element positions 𝗶𝗻𝗰𝗹𝘂𝗱𝗲𝘀() → Check existence 𝗳𝗶𝗻𝗱() / 𝗳𝗶𝗻𝗱𝗜𝗻𝗱𝗲𝘅() → First match / index 𝗔𝗿𝗿𝗮𝘆.𝗶𝘀𝗔𝗿𝗿𝗮𝘆() → Verify if array 🔄 𝗧𝗿𝗮𝗻𝘀𝗳𝗼𝗿𝗺 & 𝗟𝗼𝗼𝗽 𝗳𝗼𝗿𝗘𝗮𝗰𝗵() → Loop (no return) 𝗺𝗮𝗽() → Create new array from existing 𝗳𝗶𝗹𝘁𝗲𝗿() → Keep items that match the condition 𝗲𝘃𝗲𝗿𝘆() / 𝘀𝗼𝗺𝗲() → Test all or any items 🧮 𝗥𝗲𝗱𝘂𝗰𝗲 & 𝗔𝗰𝗰𝘂𝗺𝘂𝗹𝗮𝘁𝗲 𝗿𝗲𝗱𝘂𝗰𝗲() / 𝗿𝗲𝗱𝘂𝗰𝗲𝗥𝗶𝗴𝗵𝘁() → Combine elements into single value (sum, flatten, etc.) 🛠 𝗙𝗶𝗹𝗹 & 𝗖𝗼𝗽𝘆 𝗳𝗶𝗹𝗹() → Fill with a static value 𝗰𝗼𝗽𝘆𝗪𝗶𝘁𝗵𝗶𝗻() → Copy a portion within the array 📊 𝗦𝗼𝗿𝘁 & 𝗥𝗲𝗼𝗿𝗱𝗲𝗿 𝘀𝗼𝗿𝘁() → Sort elements (default: strings) 𝗿𝗲𝘃𝗲𝗿𝘀𝗲() → Reverse order 🔗 𝗕𝗼𝗻𝘂𝘀 𝗨𝘁𝗶𝗹𝗶𝘁𝗶𝗲𝘀: 𝗲𝗻𝘁𝗿𝗶𝗲𝘀() → [index, value] iterator 𝘃𝗮𝗹𝘂𝗲𝗢𝗳() → Returns the original array 💡 𝗣𝗿𝗼 𝗧𝗶𝗽: 𝑀𝑎𝑠𝑡𝑒𝑟𝑖𝑛𝑔 𝑡ℎ𝑒𝑠𝑒 𝑎𝑟𝑟𝑎𝑦 𝑚𝑒𝑡ℎ𝑜𝑑𝑠 𝑚𝑎𝑘𝑒𝑠 𝑦𝑜𝑢𝑟 𝐽𝑎𝑣𝑎𝑆𝑐𝑟𝑖𝑝𝑡 𝑐𝑜𝑑𝑒 𝑐𝑙𝑒𝑎𝑛𝑒𝑟, 𝑓𝑎𝑠𝑡𝑒𝑟, 𝑎𝑛𝑑 𝑚𝑜𝑟𝑒 𝑒𝑓𝑓𝑖𝑐𝑖𝑒𝑛𝑡, 𝑒𝑠𝑝𝑒𝑐𝑖𝑎𝑙𝑙𝑦 𝑓𝑜𝑟 𝑀𝐸𝑅𝑁 𝑠𝑡𝑎𝑐𝑘 𝑑𝑒𝑣𝑒𝑙𝑜𝑝𝑚𝑒𝑛𝑡 𝑜𝑟 𝑐𝑜𝑑𝑖𝑛𝑔 𝑖𝑛𝑡𝑒𝑟𝑣𝑖𝑒𝑤𝑠. 📌 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲𝘀 𝘁𝗼 𝗔𝗰𝗰𝗲𝗹𝗲𝗿𝗮𝘁𝗲 𝗬𝗼𝘂𝗿 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝘁 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 📘 𝗖𝗮𝗿𝗲𝗲𝗿 𝗚𝘂𝗶𝗱𝗮𝗻𝗰𝗲 – 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝘁 : https://lnkd.in/guhaEEQP 🎯 𝗕𝗼𝗼𝘀𝘁 𝗬𝗼𝘂𝗿 𝗟𝗶𝗻𝗸𝗲𝗱𝗜𝗻 𝗮𝗻𝗱 𝗡𝗮𝘂𝗸𝗿𝗶 𝗣𝗿𝗼𝗳𝗶𝗹𝗲: https://lnkd.in/gz4Uu8Ug 📕 𝗥𝗲𝘀𝘂𝗺𝗲 𝗥𝗲𝘃𝗶𝗲𝘄 𝗮𝗻𝗱 𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗮𝘁𝗶𝗼𝗻 https://lnkd.in/g3hkDm-J credit - Sushant Desai #JavaScript #MERN #ReactJS #NodeJS #TypeScript #MongoDB #WebDevelopment #CodingTips #SoftwareEngineering #TechInterview #FrontendDevelopment #BackendDevelopment #LearnToCode
To view or add a comment, sign in
-
✅ 𝗠𝗮𝘀𝘁𝗲𝗿 𝘁𝗵𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 – 𝗔 𝗠𝘂𝘀𝘁-𝗞𝗻𝗼𝘄 𝗳𝗼𝗿 𝗘𝘃𝗲𝗿𝘆 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 Want to stand out in JavaScript interviews? Start by truly understanding the Event Loop. It’s the key to mastering how JavaScript handles sync and async tasks—here’s the simplest way to break it down. 🔹 𝟭. 𝗖𝗮𝗹𝗹 𝗦𝘁𝗮𝗰𝗸 What is it? The Call Stack is the place where JavaScript keeps track of function execution. It follows a simple LIFO (Last-In-First-Out) structure. How it works: 1️⃣ When a function is called, it gets pushed onto the stack. 2️⃣ When it finishes, it gets popped off. 3️⃣ Errors thrown inside a function bubble up through the stack. This is why synchronous code always runs first. 🔹 𝟮. 𝗘𝘃𝗲𝗻𝘁𝘀 𝗤𝘂𝗲𝘂𝗲 (𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸 𝗤𝘂𝗲𝘂𝗲) What is it? The Event Queue stores callback functions from asynchronous APIs like setTimeout, DOM events, etc. How it works: ✅ When the Call Stack is empty, the Event Loop takes the next task from the Event Queue and moves it to the stack. This is where tasks like setTimeout() get executed — but only after the current script and microtasks are done. 🔹 𝟯. 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲 What is it? This queue handles microtasks such as Promise callbacks and MutationObserver tasks. How it works: Once the Call Stack is empty, the Event Loop first checks the Microtask Queue. ✅ All microtasks are executed before moving to the Event Queue. This is why: Promise.resolve().then(...) runs before a setTimeout() even with 0ms delay. 🔹 𝟰. 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 The brain of the process. The Event Loop continuously monitors the Call Stack and the two queues. Flow: Is the Call Stack empty? → If yes, process all pending microtasks After that, move to the Event Queue and execute queued callbacks Key takeaway: 🔥 Microtasks always take priority over macrotasks (setTimeout, setInterval, etc.). 🔹 𝟱. 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 & 𝘀𝗲𝘁𝗜𝗻𝘁𝗲𝗿𝘃𝗮𝗹 Even when you set: setTimeout(() => console.log("Timeout!"), 0) It doesn’t mean the callback executes immediately. Why? Because it goes to the Event Queue, and the Event Loop processes it after: Synchronous code Microtasks ✅ 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴("𝗦𝘁𝗮𝗿𝘁!"); 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁(() => { 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴("𝗧𝗶𝗺𝗲𝗼𝘂𝘁!"); }, 𝟬); 𝗣𝗿𝗼𝗺𝗶𝘀𝗲.𝗿𝗲𝘀𝗼𝗹𝘃𝗲("𝗣𝗿𝗼𝗺𝗶𝘀𝗲!") .𝘁𝗵𝗲𝗻(𝗿𝗲𝘀 => 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴(𝗿𝗲𝘀)); 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴("𝗘𝗻𝗱!"); 𝗢𝘂𝘁𝗽𝘂𝘁: 𝗦𝘁𝗮𝗿𝘁! 𝗘𝗻𝗱! 𝗣𝗿𝗼𝗺𝗶𝘀𝗲! 𝗧𝗶𝗺𝗲𝗼𝘂𝘁! 👉 𝗣𝗿𝗼𝗺𝗶𝘀𝗲 (𝗺𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸) 𝗿𝘂𝗻𝘀 𝗯𝗲𝗳𝗼𝗿𝗲 𝗧𝗶𝗺𝗲𝗼𝘂𝘁 (𝗺𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸). #javascript #eventloop
To view or add a comment, sign in
-
-
Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code 1. Shorthand for if with multiple OR(||) conditions if (car === 'audi' || car === 'BMW' || car === 'Tesla') { //code } In a traditional way, we used to write code in the above pattern. but instead of using multiple OR conditions we can simply use an array and includes. Check out the below example. if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) { //code } if(obj && obj.tele && obj.tele.stdcode) { console.log(obj.tele .stdcode) } Use optional chaining (?.) to replace this snippet. console.log(obj?.tele?.stdcode); if (name !== null || name !== undefined || name !== '') { let second = name; } The simple way to do it is... const second = name || ''; switch (number) { case 1: return 'Case one'; case 2: return 'Case two'; default: return; } Use a map/ object const data = { 1: 'Case one', 2: 'Case two' }; //Access it using data[num] function example(value) { return 2 * value; } Use the arrow function const example = (value) => 2 * https://lnkd.in/gjf7ViX5
To view or add a comment, sign in
-
Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code 1. Shorthand for if with multiple OR(||) conditions if (car === 'audi' || car === 'BMW' || car === 'Tesla') { //code } In a traditional way, we used to write code in the above pattern. but instead of using multiple OR conditions we can simply use an array and includes. Check out the below example. if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) { //code } if(obj && obj.tele && obj.tele.stdcode) { console.log(obj.tele .stdcode) } Use optional chaining (?.) to replace this snippet. console.log(obj?.tele?.stdcode); if (name !== null || name !== undefined || name !== '') { let second = name; } The simple way to do it is... const second = name || ''; switch (number) { case 1: return 'Case one'; case 2: return 'Case two'; default: return; } Use a map/ object const data = { 1: 'Case one', 2: 'Case two' }; //Access it using data[num] function example(value) { return 2 * value; } Use the arrow function const example = (value) => 2 * https://lnkd.in/gjf7ViX5
To view or add a comment, sign in
-
Let’s talk about something that’s quietly changing how we write and debug JavaScript: The Power of Optional Chaining and Nullish Coalescing If you’ve ever battled nested objects in JavaScript and spent precious minutes guarding against null or undefined errors, optional chaining and nullish coalescing might just become your new best friends. Here’s the scenario: You’re working with data from APIs, user inputs, or third-party services. Sometimes, part of the data might be missing or undefined, and directly accessing deep properties can throw nasty runtime errors like “Cannot read property 'x' of undefined.” Enter optional chaining: a syntax that lets you safely access deeply nested properties without writing bulky checks. How does it look in code? Imagine you have user data that might or might not have an address object: ```javascript const user = { name: 'Jane', address: { city: 'Seattle', } }; // Traditional way const city = user && user.address && user.address.city; console.log(city); // Seattle // With optional chaining const cityOpt = user?.address?.city; console.log(cityOpt); // Seattle ``` Notice how much cleaner that is? If address is missing, cityOpt will gracefully be undefined instead of throwing an error. Now, what about default values when something is null or undefined? That’s where nullish coalescing (??) comes in. Unlike the OR operator (||), which treats many falsy values like 0 or '' as false, nullish coalescing only triggers when the value is null or undefined. Example: ```javascript const config = { timeout: 0, }; const timeout = config.timeout || 3000; // results in 3000 — not ideal if 0 is valid const timeoutFixed = config.timeout ?? 3000; // results in 0 — correct handling console.log(timeout, timeoutFixed); ``` Optional chaining + nullish coalescing together reduce boilerplate, make your code easier to read, and prevent subtle bugs. If you haven’t adopted these yet, I advise giving them a try in your next project. They’re supported in all modern browsers and Node.js versions, and once you get the hang of them, your JavaScript will feel smoother and safer. Ready to write cleaner, more robust JS? Start chaining safely today. #JavaScript #WebDevelopment #CodingTips #CleanCode #SoftwareEngineering #TechTrends #DevCommunity #Programming
To view or add a comment, sign in
-
💛 #JSMadeEasy with Virashree 🧠 Understanding Execution Context & Call Stack in JavaScript When I started learning JavaScript, I used to wonder — 💭 “How does JS actually run my code line by line?” The answer lies in two magical words: ✨ Execution Context and 🧱 Call Stack Let’s make them super simple 👇 ⚙️ What is an Execution Context? Think of it as a container where your JS code runs. It decides: 🧩 Which variables and functions exist 📍 Where they live (scope) 🚀 How and in what order your code executes 🌍 1. Global Execution Context (GEC) This is created by default when your JS file starts running. It does 3 main things: 1️⃣ Creates a global object (window in browsers) 2️⃣ Sets up the this keyword 3️⃣ Allocates memory for variables & functions (this is where hoisting happens!) var name = "Virashree"; function greet() { console.log("Hello " + name); } greet(); ✅ First, JS creates memory for name and greet. ✅ Then, it executes line by line — calling greet(). 2. Function Execution Context (FEC) Every time you call a function, a new mini-world(Execution Context) is created just for that function! function greet() { var message = "Hello from function!"; console.log(message); } greet(); JS creates: - A new memory space for that function - Its own scope & variables - When done, it removes it from memory 🧱 The Call Stack — The Manager of All! - Imagine a stack of plates 🍽️ - The last plate you place on top is the first one you remove. - That’s exactly how the Call Stack works (LIFO rule — Last In, First Out) function one() { two(); } function two() { console.log("Inside two"); } one(); 🧩 JS Flow: 1️⃣ Global context created 2️⃣ one() pushed to stack 3️⃣ Inside it, two() pushed 4️⃣ two() finishes → removed 5️⃣ one() finishes → removed 6️⃣ Stack empty ✅ 💡 In short: - Every JS file starts with a Global Execution Context - Each function call creates a new context - The Call Stack manages them all in order 💬 Question for you: Have you ever seen that “Call Stack” section in browser DevTools? It’s this exact thing happening behind the scenes! ⚡ #javascript #frontenddevelopment #reactjs #webdevelopment #learninginpublic #womenintech #JSMadeEasy
To view or add a comment, sign in
-
💛 #JSMadeEasy with Virashree When I first heard about “Hoisting” in JavaScript, I thought it had something to do with lifting variables up 🏋️♀️😂 Turns out… I wasn’t entirely wrong! - Here’s a simple way to understand what Hoisting really means 👇 🧠 What is Hoisting? - When JavaScript runs your code, it does it in two phases: 1️⃣ 𝗠𝗲𝗺𝗼𝗿𝘆 𝗖𝗿𝗲𝗮𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 — where it scans and “remembers” all variables and functions 2️⃣ 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 — where it actually runs the code line by line - In the first phase, JS “hoists” (lifts) all variable and function declarations to the top of their scope. 💻 Example 1: Using var console.log(name); // undefined var name = "Virashree"; JS internally does this 👇 var name; // declaration hoisted console.log(name); // undefined name = "Virashree"; - So, name exists in memory but has no value yet — hence undefined. 🌿 Example 2: Using let and const console.log(age); // ❌ ReferenceError let age = 24; - Unlike var, let and const are hoisted too — but they stay in a special zone called the 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭) until they’re declared. - That’s why accessing them before declaration throws an error instead of showing undefined. ⚙️ Function Hoisting — Two Types In JavaScript, there are two main ways to create functions: 1️⃣ Function Declaration 2️⃣ Function Expression - And they behave very differently when it comes to hoisting 👇 🌿 1. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 — Fully Hoisted ✅ The whole function is hoisted to the top of its scope. So you can call it before it’s defined. greet(); // ✅ Works fine function greet() { console.log("Hello, Virashree!"); } ➡️ Output: Hello, Virashree! Because JS hoists both the name and the body of the function. 🌸 2. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 — NOT Fully Hoisted When you assign a function to a variable (using var, let, or const), only the variable name is hoisted — not the function itself. sayHi(); // ❌ TypeError var sayHi = function() { console.log("Hi there!"); }; - If you used var, you’ll get: ❌ TypeError: sayHi is not a function - If you used let or const, you’ll get: ❌ ReferenceError: Cannot access 'sayHi' before initialization - So basically: 🚫 The variable gets hoisted, but the actual function definition does not. 🧩 Quick Recap var → Hoisted ✅ | Value: undefined let → Hoisted ✅ | Value: ❌ ReferenceError (TDZ) const → Hoisted ✅ | Value: ❌ ReferenceError (TDZ) function decl → ✅ Fully hoisted function expr → ⚠️ Partially hoisted (variable only) 🧠 Takeaway - So next time your code throws “is not a function,” - check how you declared it — not where! 😉 💬 Question for you: Which one confused you more — function declarations or function expressions? Comment below and I’ll break it down in my next #javascript #frontenddevelopment #webdevelopment #reactjs #learninginpublic #womenintech
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development