JavaScript’s Tricky Trio: call, apply, and bind — Demystified! If you’ve ever been puzzled by these three, you’re not alone. They all revolve around the mysterious this keyword — which sometimes points to the global object, and sometimes to the object that owns the method. Wouldn’t it be great if we could control what this points to? That’s exactly what these methods let us do 👇 🧠 The Big Three 1️⃣ .call() → Invokes the function immediately and lets you pass arguments one by one. 2️⃣ .apply() → Works like .call(), but accepts arguments as an array. 3️⃣ .bind() → Doesn’t execute right away; instead, it creates a new function with a fixed this and preset parameters. 🧩 Example const person = { firstName: "John", lastName: "Doe", getFullName() { return this.firstName + " " + this.lastName; } }; function greet(lang1, lang2) { console.log(`Hello, I am ${this.getFullName()} and I speak ${lang1}, ${lang2}`); } // call → run immediately greet.call(person, "English", "Spanish"); // apply → same, but arguments in an array greet.apply(person, ["French", "German"]); // bind → create a reusable version const greetPerson = greet.bind(person, "Hindi"); greetPerson("Punjabi"); ✅ Output: Hello, I am John Doe and I speak English, Spanish Hello, I am John Doe and I speak French, German Hello, I am John Doe and I speak Hindi, Punjabi ⚙️ Real-world Uses 🔹 Function Borrowing → Use methods from one object on another. 🔹 Function Currying → Create specialized versions of functions with preset parameters. Example: function multiply(a, b) { return a * b; } const multiplyByTwo = multiply.bind(this, 2); console.log(multiplyByTwo(4)); // 8 const multiplyByThree = multiply.bind(this, 3); console.log(multiplyByThree(4)); // 12 🎯 Key takeaway: 👉 .call() & .apply() → Execute now. 👉 .bind() → Save for later (with context pre-set). Once you understand how they work, they stop being scary — and become some of your most powerful tools for mastering function execution in JavaScript. #JavaScript #WebDevelopment #FrontendDevelopment #JS #CodingTips #TechLearning #WebDevCommunity
Understanding JavaScript's call, apply, and bind methods
More Relevant Posts
-
Let’s talk about a surprisingly underused but powerful tool in JavaScript: the Nullish Coalescing Operator (??). If you haven’t been using this gem yet, it might just simplify your code and help you avoid some common bugs related to default values. Here’s the problem it solves: often, you want to provide a fallback or default value when a variable is undefined or null. Previously, many of us leaned heavily on the logical OR (||) operator, like this: ```javascript const userInput = ''; const displayName = userInput || 'Guest'; // displayName will be 'Guest' ``` Looks fine, right? But wait—what if the user deliberately entered an empty string, which is a valid input here? The || operator treats empty strings, 0, NaN, and false as falsy and will override those with the fallback value. That can lead to unexpected behavior. Enter the Nullish Coalescing Operator (??): ```javascript const userInput = ''; const displayName = userInput ?? 'Guest'; // displayName will be '' ``` With ??, only null or undefined triggers the fallback. Empty strings, zeros, and false remain untouched. This is a cleaner, more precise way of handling defaults. This operator is especially useful in real-world cases such as: - Config settings, where 0 or false can be valid options. - API responses, where some fields can be omitted (undefined) but others deliberately falsey. - Form inputs, where user data might legitimately be falsey but not null. Here’s a quick snippet comparing the two approaches: ```javascript function getTimeout(config) { // Using OR operator const timeoutOld = config.timeout || 3000; // Using Nullish Coalescing const timeoutNew = config.timeout ?? 3000; console.log('Old:', timeoutOld, 'New:', timeoutNew); } getTimeout({ timeout: 0 }); // Output: // Old: 3000 New: 0 ``` See how ?? correctly respects 0 as a valid value, while || doesn’t? Pro tip: avoid mixing ?? with || in the same expression, as it can cause syntax errors or produce confusing results. Use parentheses if you must combine them. So if you want to write clearer, less bug-prone JavaScript, start using the Nullish Coalescing Operator. It might be a tiny change for your code but a giant leap in clarity and correctness. Have you used ?? in your projects yet? What scenarios made you appreciate it? Let’s swap tips in the comments! #JavaScript #WebDevelopment #CodingTips #TechTrends #Frontend #Programming #DeveloperExperience
To view or add a comment, sign in
-
Day 19/100 Day 10 of JavaScript Mastering String Methods in JavaScript In JavaScript, strings are sequences of characters used to represent text. But what makes them truly powerful are the built-in string methods that help us manipulate and analyze text efficiently. Let’s explore some of the most useful ones 1. length — Find String Length Returns the number of characters in a string. let name = "JavaScript"; console.log(name.length); // Output: 10 Useful when you need to validate input length, like passwords or usernames 2. toUpperCase() & toLowerCase() — Change Case Converts all characters to upper or lower case. let lang = "javascript"; console.log(lang.toUpperCase()); // JAVASCRIPT console.log(lang.toLowerCase()); // javascript Handy for case-insensitive comparisons. 3. includes() — Check if a Word Exists Checks if a string contains a specific substring. let sentence = "Learning JavaScript is fun!"; console.log(sentence.includes("JavaScript")); // true Perfect for search or filter functions. 4. indexOf() & lastIndexOf() — Find Positions Finds the index of the first or last occurrence of a substring. let text = "Hello JavaScript world!"; console.log(text.indexOf("JavaScript")); // 6 console.log(text.lastIndexOf("o")); // 19 Useful for locating specific patterns in strings. 5. slice() — Extract a Portion Extracts part of a string based on index range. let str = "JavaScript"; console.log(str.slice(0, 4)); // "Java" Often used to trim text or extract keywords. 6. replace() — Replace Text Replaces a substring with another. let msg = "I love JavaScript!"; console.log(msg.replace("JavaScript", "Python")); // "I love Python!" Useful for content formatting or dynamic text updates. 7. trim() — Remove Extra Spaces Removes whitespace from both ends of a string. let input = " Hello World! "; console.log(input.trim()); // "Hello World!" Essential for cleaning user input. 8. split() — Convert String to Array Splits a string into an array based on a delimiter. let fruits = "apple,banana,grape"; console.log(fruits.split(",")); // ["apple", "banana", "grape"] Commonly used when processing CSV data. 9. charAt() — Get Character by Index Returns the character at a specific index. let word = "Hello"; console.log(word.charAt(1)); // "e" 10. concat() — Join Multiple Strings Combines two or more strings. let first = "Hello"; let second = "World"; console.log(first.concat(" ", second)); // "Hello World" Alternative to using + for string concatenation. Quick Tip: All string methods return new strings — they don’t modify the original one since strings in JavaScript are immutable. Final Thought: Mastering string methods helps you handle text data like a pro — from formatting user inputs to processing dynamic content. #10000coders #JavaScript #WebDevelopment #CodingTips #LearnJavaScript #Developers #LinkedInLearning
To view or add a comment, sign in
-
Today I revised some of the most essential JavaScript concepts that appear in real-world development. 1️⃣ Higher-Order Function (HOF) ✅ Question: Create a function that runs another function twice 📝 Code: function runTwice(fn) { fn(); fn(); } runTwice(() => console.log("hello")); 🔍 Short Explanation: A HOF is a function that takes another function as input or returns a function. Helps in reusable logic. 2️⃣ Pure Function 📝 Code: function pure(a, b) { console.log(a + b); } pure(2, 3); pure(2, 3); 🔍 Short Explanation: Always gives the same output for the same input. No side effects. 3️⃣ Impure Function 📝 Code: let global = 0; function imPure(a) { global++; console.log(a + global); } imPure(2); imPure(2); 🔍 Short Explanation: Depends on external data → output changes unexpectedly. 4️⃣ Destructuring in Function Parameters 📝 Code: const obj = { name: "Pratik", age: 21 }; function destructuring({ name, age }) { console.log(name, age); } destructuring(obj); 🔍 Short Explanation: Pulls values directly from objects → cleaner code. 5️⃣ Normal Function vs Arrow Function (this difference) 📝 Code: let objTwo = { name: "Pratik", fnc: function () { console.log(this); }, arrowFnc: () => { console.log(this); } }; objTwo.fnc(); objTwo.arrowFnc(); 🔍 Short Explanation: Normal function → owns its own this Arrow function → uses parent this (lexical) 6️⃣ map(): Square each number 📝 Code: let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(e => e * e); console.log(newArr); 🔍 Short Explanation: Transforms each element → returns a new array. 7️⃣ filter(): Get even numbers 📝 Code: let filtered = arr.filter(e => e % 2 === 0); console.log(filtered); 🔍 Short Explanation: Keeps only the elements that match a condition. 8️⃣ reduce(): Total salary 📝 Code: let salary = [10000, 20000, 30000]; let total = salary.reduce((acc, v) => acc + v, 0); console.log(total); 🔍 Short Explanation: Reduces an array into one final value. 9️⃣ some() & every() 📝 Code: let names = ["pratik", "sun", "om", "krish", "vijay"]; let some = names.some(e => e.length > 3); let every = names.every(e => e.length > 3); console.log(some, every); 🔍 Short Explanation: some() → at least ONE matches every() → ALL must match 🔟 Object.freeze() 📝 Code: const users = { name: "Sunny", age: 21 }; Object.freeze(users); users.age = 22; users.city = "Surat"; delete users.name; console.log(users); 🔍 Short Explanation: No add, no delete, no modify → completely locked. 1️⃣1️⃣ Object.seal() 📝 Code: const test = { subject: "Maths", score: 50 }; Object.seal(test); test.score = 60; test.grade = "A"; delete test.subject; console.log(test); 🔍 Short Explanation: You can modify, but cannot add or delete keys. 1️⃣2️⃣ Optional Chaining (?.) 📝 Code: const user = { name: "Pratik", address: { city: "Surat" } }; console.log(user?.address?.city); 🔍 Short Explanation: Avoids errors when accessing nested properties.
To view or add a comment, sign in
-
Today, I explored one of the core topics in JavaScript — Operators. Understanding different types of operators like Arithmetic, Comparison, Logical, and Assignment helps in writing efficient and logical code. Every symbol in JavaScript has a purpose, and learning how they work gives more control over program logic and decision-making. Operators in JavaScript: Definition: Operators in JavaScript are special symbols or keywords that are used to perform operations on operands (values or variables). They help in performing various tasks like arithmetic calculations, comparisons, logical decisions, and assignments. Example: let x = 10 + 5; Here, + is an operator, and 10 and 5 are operands. ⚙️ Types of JavaScript Operators 1. Arithmetic Operators Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, and division. List of Arithmetic Operators: + (Addition): Adds two operands. - (Subtraction): Subtracts one operand from another. * (Multiplication): Multiplies two operands. / (Division): Divides one operand by another. % (Modulus): Returns the remainder after division. ** (Exponentiation): Raises a number to a power. ++ (Increment): Increases the value of a variable by 1. -- (Decrement): Decreases the value of a variable by 1. 2. Assignment Operators Assignment operators are used to assign values to variables. They can also perform operations and assign the result to the same variable. Examples: = → Assigns a value. += → Adds and assigns. -= → Subtracts and assigns. *= → Multiplies and assigns. /= → Divides and assigns. %= → Finds remainder and assigns. 3. Comparison Operators Comparison operators are used to compare two values. The result of a comparison operation is either true or false. Examples: == → Equal to (compares value only). === → Strict equal to (compares value and type). != → Not equal to. !== → Strict not equal to (value and type). > → Greater than. < → Less than. >= → Greater than or equal to. <= → Less than or equal to. let a = 10; let b = 5; console.log(a + b); // 15 (Addition) console.log(a - b); // 5 (Subtraction) console.log(a * b); // 50 (Multiplication) console.log(a / b); // 2 (Division) console.log(a % b); // 0 (Remainder) console.log(a ** 2); // 100 (Exponentiation) a++; // Increment console.log(a); // 11 b--; // Decrement console.log(b); // 4 let x = 10; x += 5; // x = x + 5 console.log(x); // 15 x -= 3; // x = x - 3 console.log(x); // 12 x *= 2; // x = x * 2 console.log(x); // 24 let a = 10; let b = "10"; console.log(a == b); // true (equal value) console.log(a === b); // false (equal value but different type) console.log(a != b); // false (same value) console.log(a !== b); // true (different type) console.log(a > 5); // true #javascript #webdevelopment #codingjourney #learning
To view or add a comment, sign in
-
🧠 JavaScript typeof Explained: Understanding Data Types Made Simple When coding in JavaScript, one of the most common tasks is checking what type of data you’re working with. That’s where the typeof operator comes in! --- 💡 What is typeof? typeof is a built-in JavaScript operator that tells you the type of a variable or value. It’s like asking JavaScript: > “Hey, what exactly is this thing I’m working with?” --- 🧩 Syntax: typeof variableName; or typeof(value); --- 🔍 Examples: typeof "Hello"; // "string" typeof 42; // "number" typeof true; // "boolean" typeof {}; // "object" typeof []; // "object" (arrays are technically objects) typeof undefined; // "undefined" typeof null; // "object" (a known JavaScript quirk!) typeof function(){}; // "function" --- 🪄 Why It Matters The typeof operator is super useful when: Debugging your code 🐞 Validating user input 🧍♂️ Writing clean, bug-free programs 💻 --- ⚙️ Pro Tip: If you want to check if something is an array, don’t use typeof. Instead, use: Array.isArray(value); --- 🚀 Final Thoughts: Understanding the typeof operator helps you master JavaScript’s dynamic typing system. It’s a simple but powerful tool for keeping your code organized and error-free. Start experimenting with typeof today—you’ll quickly see how handy it is! #codecraftbyaderemi #webdeveloper #html #javascript #frontend
To view or add a comment, sign in
-
-
“Why does this behave so weird in JavaScript? 🤯 Let’s finally make sense of it!” If you’ve ever shouted at your screen because this suddenly became undefined — you’re not alone 😅 Let’s break down how this works across different scenarios with simple examples 👇 🧩 1️⃣ Arrow Function Defined Directly in Object const person = { name: "Suverk", greet: () => console.log(`Hi ${this.name}`) }; person.greet(); // ❌ undefined 🧠 Why? Arrow functions don’t have their own this. They lexically inherit this from their surrounding scope — which here is the global (not person). ✅ Fix: Use a regular function: greet() { console.log(`Hi ${this.name}`); } 🧩 2️⃣ Arrow Function Inside a Regular Method const person = { name: "Suverk", greet: function() { const arrow = () => console.log(this.name); arrow(); } }; person.greet(); // ✅ "Suverk" 🧠 Why? The arrow function inherits this from where it was created — inside greet, and this inside greet = person. ✅ Works perfectly because of lexical scoping. 🧩 3️⃣ Regular Function Inside Another Regular Function const person = { name: "Suverk", greet: function() { function inner() { console.log(this.name); } inner(); } }; person.greet(); // ❌ undefined 🧠 Why? When you call inner() as a plain function, it’s not attached to any object. So this defaults to global (or undefined in strict mode). ✅ Fixes: // Option 1 const self = this; function inner() { console.log(self.name); } // Option 2 function inner() { console.log(this.name); } inner.bind(this)(); // Option 3 const inner = () => console.log(this.name); 🧩 4️⃣ Detached Method Reference const person = { name: "Suverk", greet() { console.log(this.name); } }; const use = person.greet; use(); // ❌ undefined 🧠 Why? this depends on how a function is called. You’ve just taken the function reference — the link to person is gone. ✅ Fix: const use = person.greet.bind(person); use(); // ✅ "Suverk" In JavaScript, this depends on how a function is called — except for arrow functions, which depend on where they’re defined. 💬 Have you ever been tricked by this before? Drop your comment below 👇 — let’s make others learn faster than we did 😅 #JavaScript #Frontend #WebDevelopment #Angular
To view or add a comment, sign in
-
🚀 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 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
To view or add a comment, sign in
-
Working with objects in JavaScript is easy, actually 🤔. So allow me to simplify it as much as I can: 😊 There are two data types in JavaScript. we have primitive and non-primitive. primitive data types are easy and well known. They are your average Let name = "John"; Const age = 30; Primitive data types holds 7 different things: Strings, Numbers, Boolean, Symbol, Null, Undefined, and BigInt. just declare them with their values and you're all set. just remember, they are immutable. you can reassign them (unless you're using const) and they will change in value, but the original will still be in memory. so using something like name.toUpperCase() won't effect the variable name unless you reassign it like name = name.toUpperCase(). Objects, however, are completely different beast. they a non-primitive type. like Arrays or functions. The properties inside the objects are mutable. as Objects just point to the value in memory. so if you use for example: let obj = {name: "John", age: 30}; you're not making a variable named name and John as its value, but you're making a property with the value of John in memory. so when you call |obj.name| it will return "John". but if you mutated the property like: obj.name = "Doe"; then its in memory changed to Doe. John is no longer in there. So even if we made a copy of primitive data type, it will reference its assigned value, even if the original was changed, but the original is still in memory. in objects, the copy will reference the value in memory. so if a property's value change in the original, it will also change in the copy. 😀
To view or add a comment, sign in
-
-
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
-
-
💛 #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
More from this author
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