Controlling `this` in JavaScript: Call vs. Apply vs. Bind. 🎮 One of the most common interview questions for mid-level developers is: "𝑊ℎ𝑎𝑡 𝑖𝑠 𝑡ℎ𝑒 𝑑𝑖𝑓𝑓𝑒𝑟𝑒𝑛𝑐𝑒 𝑏𝑒𝑡𝑤𝑒𝑒𝑛 𝐶𝑎𝑙𝑙, 𝐵𝑖𝑛𝑑, 𝑎𝑛𝑑 𝐴𝑝𝑝𝑙𝑦?" They all do the same core job: They allow you to manually set what `this` refers to inside a function. But they do it in slightly different ways. 𝐇𝐞𝐫𝐞 𝐢𝐬 𝐭𝐡𝐞 𝟏𝟎-𝐬𝐞𝐜𝐨𝐧𝐝 𝐛𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧: 1️⃣ 𝐂𝐚𝐥𝐥 & 𝐀𝐩𝐩𝐥𝐲 (𝐓𝐡𝐞 𝐈𝐦𝐦𝐞𝐝𝐢𝐚𝐭𝐞 𝐈𝐧𝐯𝐨𝐤𝐞𝐫𝐬) Both of these execute the function 𝑖𝑚𝑚𝑒𝑑𝑖𝑎𝑡𝑒𝑙𝑦. The only difference is how they handle arguments. • 𝐂𝐚𝐥𝐥: Passes arguments individually (comma-separated). • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐂all = 𝐂ommas. • 𝐀𝐩𝐩𝐥𝐲: Passes arguments as a single Array. • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐀pply = 𝐀rray. 2️⃣ 𝐁𝐢𝐧𝐝 (𝐓𝐡𝐞 𝐏𝐥𝐚𝐧𝐧𝐞𝐫) • 𝐁𝐢𝐧𝐝: Does NOT execute the function immediately. • Instead, it returns a 𝐧𝐞𝐰 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐜𝐨𝐩𝐲 with the `this` context permanently locked (bound) to the object you specified. You can then call this new function whenever you want later. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐮𝐬𝐞𝐟𝐮𝐥? It allows "Method Borrowing." You can use a method from one object (like a helper function) and use it on a completely different object, just by changing the `this` context! Check out the syntax comparison below! 👇 Which one do you use most often? I find `bind` essential for passing methods into React components or event listeners! #JavaScript #WebDevelopment #CodingInterviews #SoftwareEngineering #Frontend #JSConcepts
Nidhi Jagga’s Post
More Relevant Posts
-
🚀 Top 150 React Interview Questions — 15/150 ⚛️ 🧠 What is JSX? JSX stands for JavaScript XML. It is a syntax extension that lets you write HTML-like code directly inside JavaScript. Instead of complex DOM methods, you can simply write UI in a clean, readable way. ✨ Why we use JSX: ✍️ Easier to write – Much faster than React.createElement() 👀 Visual clarity – Looks like HTML, so UI structure is easy to understand 🧠 Power of JavaScript – Use variables, conditions, loops, and logic inside UI ⚙️ How JSX works behind the scenes: 🌐 Browsers cannot read JSX 🔧 A compiler called Babel converts JSX into plain JavaScript Example: const element = <h1>Hi</h1>; ➡️ Babel converts it to: React.createElement('h1', null, 'Hi'); 📏 Important JSX rules: 1️⃣ Single root element – Wrap everything in one parent (div or <>...</>) 2️⃣ CamelCase attributes – className, onClick, etc. 3️⃣ Closing tags required – <img />, <br /> 4️⃣ JS expressions – Use { } to inject JavaScript 📌 Easy way to remember: JSX is syntactic sugar 🍬 It doesn’t add new power to JavaScript — it just makes UI code cleaner, readable, and declarative. 👇 Comment “React” if this series helps you. #ReactJS #JSX #JavaScript #FrontendDevelopment #ReactInterview #WebDevelopment #LearningInPublic #ReactFundamentals
To view or add a comment, sign in
-
-
Type Conversion in JavaScript ---------------------------------------- JavaScript supports three main types of type conversion: > String Conversion > Number Conversion > Boolean Conversion > String Conversion Use the String(value) method to convert a value into a string. Examples: String(10) // "10" String(true) // "true" String(false) // "false" String(null) // "null" > Number Conversion Use the Number(value) method to convert a value into a number. If conversion fails, it returns NaN. Examples: Number("10") // 10 Number("sdfsd") // NaN Number(false) // 0 Number(true) // 1 Number("") // 0 > Boolean Conversion Use the Boolean(value) method to convert a value into a boolean. Examples: Boolean(1) // true Boolean(0) // false Boolean("true") // true Boolean("") // false Boolean(null) // false Boolean(undefined) // false #JavaScript #JavaScriptBasics #TypeConversion #WebDevelopment #FrontendDevelopment #Programming #Coding #SoftwareDevelopment #WebDevelopers #LearnJavaScript #DeveloperCommunity #TechLearning #CodingTips #ITCareers
To view or add a comment, sign in
-
Day 15/50 – JavaScript Interview Question? Question: What is the Event Loop in JavaScript? Simple Answer: The Event Loop is the mechanism that handles asynchronous operations in JavaScript's single-threaded environment. It continuously checks the Call Stack and Task Queues, executing code in a specific order: synchronous code first, then microtasks (promises), then macrotasks (setTimeout, events). 🧠 Why it matters in real projects: Understanding the Event Loop is crucial for debugging asynchronous behavior, preventing UI blocking, and optimizing performance. It explains why promises execute before setTimeout even with 0ms delay. 💡 One common mistake: Not understanding the priority of microtasks vs macrotasks, leading to unexpected execution order in complex async code. 📌 Bonus: console.log('1: Start'); setTimeout(() => console.log('2: Timeout'), 0); Promise.resolve() .then(() => console.log('3: Promise 1')) .then(() => console.log('4: Promise 2')); console.log('5: End'); // Output order: // 1: Start // 5: End // 3: Promise 1 // 4: Promise 2 // 2: Timeout // Why? Sync code → Microtasks (Promises) → Macrotasks (setTimeout) #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🤔 Ever wondered why JavaScript sometimes silently fails… and sometimes loudly breaks? That’s where Strict Mode comes in. 🧠 JavaScript interview question What is strict mode in JavaScript? ✅ Short answer Strict mode is an optional JavaScript mode that makes code run in a safer and more predictable way by turning silent errors into real ones and disallowing risky behavior. You enable it with: "use strict"; (or automatically when using ES modules) 🔍 What strict mode actually changes • Prevents accidental global variables • Throws errors instead of failing silently • Makes this safer and more predictable • Disallows duplicate parameters • Disables outdated syntax (like octal literals) • Protects read-only properties 💻 Examples Accidental globals ❌ "use strict"; x = 10; // ReferenceError: x is not defined Function-level strict mode function demo() { "use strict"; y = 5; // ReferenceError } this behavior function show() { console.log(this); } show(); // non-strict → global object // strict → undefined ⚠️ Common misconceptions • Strict mode is not about performance • It doesn’t break code randomly — it exposes real bugs • Modules are already strict by default 🎯 Why it matters Strict mode helps you catch mistakes early, write cleaner code, and avoid hidden bugs that are painful to debug later. 📌 Interview tip If your code suddenly “breaks” in strict mode — that code was already broken. #JavaScript #Frontend #WebDevelopment #JSInterview #CleanCode #LearnInPublic
To view or add a comment, sign in
-
🧩 JavaScript Output-Based Question (call / bind) ❓ What will be logged? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : A 🧠 Why this output comes? (Step-by-Step) 1️⃣ bind() creates a NEW function const bound = greet.bind(a); bind() permanently sets this to object a and returns a new bound function. 2️⃣ call() cannot change a bound this bound.call(b); Once a function is bound: • call() • apply() • bind() again ❌ cannot override the original binding So even though call(b) is used, this still points to a. That’s why : A is printed. 🔑 Key Takeaways ✔️ bind() sets this permanently ✔️ call() and apply() set this only temporarily ✔️ call() cannot override bind() ✔️ This is a very common interview trap If you remember one thing: bind beats call and apply #JavaScript #CallBindApply #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS
To view or add a comment, sign in
-
-
🤔 Ever confused by the three dots (...) in JavaScript? They look the same, but default parameters, rest, and spread solve very different problems. 🧠 JavaScript interview question What’s the difference between default parameters, rest parameters, and the spread operator? ✅ Short answer • Default parameters give fallback values • Rest collects multiple values into one • Spread expands one value into many Same syntax, different intent. 🔍 Default parameters — “Give me a fallback” Used when a function argument is missing or undefined. Instead of manual checks, JavaScript handles it for you. function greet(name = "there") { return "Hi " + name; } greet(); // "Hi there" greet("Sam"); // "Hi Sam" 🔍 Rest parameters — “Collect the leftovers” Used in function definitions to gather extra arguments into a real array. function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3, 4); // 10 🔍 Spread operator — “Unpack things” Used in function calls, arrays, and objects to expand values. const a = [1, 2]; const b = [3, 4]; const combined = [...a, ...b]; // [1,2,3,4] With objects (shallow copy): const user = { name: "A", meta: { v: 1 } }; const copy = { ...user, role: "admin" }; ⚠️ Common misconceptions • Rest ≠ arguments (rest is a real array) • Spread does not deep clone objects • Default params apply only when value is undefined 🧩 Easy way to remember Rest gathers. Spread scatters. #javascript #frontend #webdevelopment #interviewprep #react #codingtips
To view or add a comment, sign in
-
Day 13/365 – Top #JavaScript Interview Questions 🔥Part2 Q19). What are higher-order functions? Q20). What is currying in JavaScript? Q21). What is an IIFE and why is it used? Q22). What is prototypal inheritance? Q23). What is debouncing and throttling? Q24). What is the difference between the spread operator and rest operator? Q25). What is the difference between Object.freeze() and Object.seal()? Q26). What is the difference between a Promise and an Observable? Q27). What is the difference between slice() and splice()? Q28). How do you optimize performance in JavaScript applications? Q29). What is the difference between synchronous and asynchronous code? Q30). What is the difference between null ,undefined and NaN? Q31). What are object methods like Object.keys(), Object.values(), and Object.entries()? Q32). What is the difference between DOM and BOM? Q33). What is destructuring in JavaScript and how is it useful? Q34). What is the difference between filter() and find()? Q35) How do you handle errors in JavaScript? Q36). What is Object.assign() and how does it work? #javascript #interview #webdevlopment #js #365daysofjs #jsinterview #interviewprepration
To view or add a comment, sign in
-
JavaScript Array Methods — Explained Visually If JavaScript array methods ever felt confusing, this visual will make them click instantly Instead of memorizing definitions, focus on how data actually transforms step by step. 🔹 map() → transforms every element 🔹 filter() → selects matching elements 🔹 find() → returns the first match 🔹 findIndex() → gives the position 🔹 fill() → fills with a static value 🔹 some() → checks if any element matches 🔹 every() → checks if all elements match Why this matters: Understanding array methods is essential for: ✅ Writing clean JavaScript ✅ Cracking frontend interviews ✅ Working with React & modern JS Save this post for quick revision before coding 📌 #JavaScript #ArrayMethods #WebDevelopment #Frontend #Coding #DSA #LearnJavaScript #ProgrammingBasics
To view or add a comment, sign in
-
-
🤔 Ever wondered why some JavaScript functions can be called before they’re defined? JavaScript treats function declarations and function expressions differently. 🧠 JavaScript interview question What’s the difference between function declarations and function expressions? ✅ Short answer • Both define functions • Only declarations are fully hoisted • Expressions are evaluated at runtime • Timing of availability is the key difference 🔍 A bit more detail Function declarations are hoisted, meaning the entire function is available before the code runs. Function expressions create a function as part of an expression and are only usable after that expression executes. Function expressions can also be named, which helps with debugging and recursion without polluting the outer scope. 💻 Example // function declaration greet(); function greet() { console.log("Hi"); } // function expression const sayHi = function () { console.log("Hello"); }; sayHi(); // named function expression const factorial = function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); }; console.log(factorial(5)); // 120 ⚠️ Small but important • Only function declarations are hoisted as callable functions • Function expressions are not available before assignment • Named function expressions keep their name scoped to the function body 👍 Follow for daily JavaScript interview questions #javascript #webdevelopment #frontend #frontenddeveloper #coding #programming #js #interviewprep #learnjavascript
To view or add a comment, sign in
-
Javascript Interview Question ❓ 🧠 JavaScript Call Stack Explained (With Nested Functions) Ever wondered which function runs first when functions are nested in JavaScript? Let’s break it down 👇 function fn1() { function fn2() { function fn3() { console.log("fn3"); } fn3(); console.log("fn2"); } fn2(); console.log("fn1"); } fn1(); 🔍 What actually happens? JavaScript uses a Call Stack to execute functions. 📌 Rule: Call Stack follows LIFO (Last In, First Out) 🪜 Call Stack Flow (Visualized) Copy code fn3() ← executed & finished first fn2() fn1() ← called first, finished last ✔️ fn1 is called first ✔️ fn3 finishes first That’s LIFO in action 🔥 ❌ FIFO vs ✅ LIFO in JavaScript Call Stack ✅ LIFO Event Queue (setTimeout)✅ FIFO Microtask Queue (Promise)✅ FIFO 📌 Golden rule for interviews: Execution stack = LIFO Async queues = FIFO 🎯 Interview One-Liner JavaScript executes functions using a LIFO call stack, while asynchronous callbacks are processed via FIFO queues. If this cleared things up, drop a 👍 If you’ve ever been confused by this — you’re not alone 😄 Follow for JavaScript + Angular internals explained simply 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #CallStack #EventLoop #JSInterview #Angular #Programming #SoftwareEngineering
To view or add a comment, sign in
-
Explore related topics
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