Day 2/50 – JavaScript Interview Question? Question: What's the difference between call(), apply(), and bind()? Simple Answer: All three methods allow you to set the this context explicitly. call() invokes the function immediately with arguments passed individually, apply() invokes it with arguments as an array, and bind() returns a new function with this bound permanently. 🧠 Why it matters in real projects: These methods are crucial when working with object methods, event handlers, and callbacks where you need precise control over the this context. They're especially important in React class components and when borrowing methods between objects. 💡 One common mistake: Using bind() and expecting the function to execute immediately. Remember, bind() returns a new function—it doesn't invoke it! 📌 Bonus: const person = { name: 'Alice' }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } greet.call(person, 'Hello'); // "Hello, Alice" greet.apply(person, ['Hi']); // "Hi, Alice" const boundGreet = greet.bind(person); boundGreet('Hey'); // "Hey, Alice" #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
JavaScript call(), apply(), and bind() explained
More Relevant Posts
-
Day 17/50 – JavaScript Interview Question? Question: What is debouncing and how do you implement it? Simple Answer: Debouncing is a technique that delays function execution until a certain amount of time has passed since the last invocation. It's perfect for limiting how often a function runs in response to rapid events. 🧠 Why it matters in real projects: Debouncing is essential for optimizing search autocomplete, form validation, window resize handlers, and scroll events. Without it, you'd make hundreds of unnecessary API calls or trigger expensive calculations on every keystroke. 💡 One common mistake: Confusing debouncing with throttling. Debouncing waits for a pause in events, while throttling executes at regular intervals regardless of event frequency. 📌 Bonus: // Debounce implementation function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } // Usage: Search autocomplete const searchAPI = (query) => { console.log('Searching for:', query); // Actual API call here }; const debouncedSearch = debounce(searchAPI, 500); // User types "javascript" // Only makes 1 API call after user stops typing for 500ms searchInput.addEventListener('input', (e) => { debouncedSearch(e.target.value); }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 11/50 – JavaScript Interview Question? Question: What is the difference between Promise.all() and Promise.race()? Simple Answer: Promise.all() waits for all promises to resolve (or one to reject) and returns an array of results. Promise.race() returns as soon as the first promise settles (resolves or rejects), ignoring the others. 🧠 Why it matters in real projects: Use Promise.all() when you need multiple API calls to complete before proceeding (like fetching user data and their posts). Use Promise.race() for implementing timeouts or choosing the fastest response from multiple sources. 💡 One common mistake: Not realizing that Promise.all() fails fast—if any promise rejects, the entire operation fails immediately, even if other promises are still pending. 📌 Bonus: // Promise.all - all must succeed const results = await Promise.all([ fetch('/api/user'), fetch('/api/posts'), fetch('/api/comments') ]); // If any fails, all fail // Promise.race - first one wins const result = await Promise.race([ fetch('/api/data'), new Promise((_, reject) => setTimeout(() => reject('Timeout'), 5000) ) ]); // Implements a 5-second timeout // Use Promise.allSettled() to get all results regardless of failures #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 13/50 – JavaScript Interview Question? Question: What is hoisting in JavaScript? Simple Answer: Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase. Function declarations are fully hoisted, var declarations are hoisted but initialized as undefined, and let/const are hoisted but remain in the Temporal Dead Zone. 🧠 Why it matters in real projects: Understanding hoisting helps you avoid confusing bugs and write more predictable code. It explains why you can call functions before they're declared and why accessing var variables before declaration returns undefined instead of an error. 💡 One common mistake: Thinking hoisting physically moves code. It doesn't—it's about when variables and functions are registered in memory during the creation phase. 📌 Bonus: // Function hoisting - works! greet(); // "Hello" function greet() { console.log("Hello"); } // var hoisting - returns undefined console.log(name); // undefined (not ReferenceError) var name = "Alice"; // let/const - Temporal Dead Zone console.log(age); // ReferenceError let age = 25; // Function expressions are NOT fully hoisted sayHi(); // TypeError: sayHi is not a function var sayHi = function() { console.log("Hi"); }; #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 8/50 – JavaScript Interview Question? Question: What's the difference between == and === in JavaScript? Simple Answer: == (loose equality) performs type coercion before comparison, while === (strict equality) checks both value and type without any conversion. 🧠 Why it matters in real projects: Using === prevents subtle bugs caused by unexpected type coercion. It makes your code more predictable and is considered a best practice in modern JavaScript development. Most linters enforce strict equality by default. 💡 One common mistake: Thinking that == is just "more forgiving" without understanding the complex coercion rules that can lead to confusing results like [] == ![] being true. 📌 Bonus: // Confusing results with == 0 == false // true '' == false // true null == undefined // true '0' == 0 // true // Clear and predictable with === 0 === false // false '' === false // false null === undefined // false '0' === 0 // false // Exception: checking for null/undefined if (value == null) // checks both null AND undefined #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 26/50 – JavaScript Interview Question? Question: What is currying in JavaScript? Simple Answer: Currying transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument. Instead of add(a, b), you get add(a)(b). 🧠 Why it matters in real projects: Currying enables partial application, function composition, and more reusable code. It's fundamental to functional programming libraries like Ramda and is used in Redux middleware, event handlers, and configuration functions. 💡 One common mistake: Over-currying simple functions where it adds complexity without benefit. Use currying when you need partial application or composition, not everywhere. 📌 Bonus: // Regular function function add(a, b, c) { return a + b + c; } add(1, 2, 3); // 6 // Curried version function curriedAdd(a) { return function(b) { return function(c) { return a + b + c; }; }; } curriedAdd(1)(2)(3); // 6 // Practical use: Partial application const add5 = curriedAdd(5); const add5and10 = add5(10); console.log(add5and10(3)); // 18 // Generic curry function function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args); } return function(...nextArgs) { return curried.apply(this, [...args, ...nextArgs]); }; }; } // Usage const multiply = (a, b, c) => a * b * c; const curriedMultiply = curry(multiply); curriedMultiply(2)(3)(4); // 24 curriedMultiply(2, 3)(4); // 24 - flexible! #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #FunctionalProgramming #Currying #WebDev #InterviewPrep
To view or add a comment, sign in
-
Day 10/50 – JavaScript Interview Question? Question: What's the difference between null and undefined? Simple Answer: undefined means a variable has been declared but not assigned a value, or a function doesn't return anything. null is an explicit assignment representing "no value" or "empty." 🧠 Why it matters in real projects: Understanding this distinction helps with API responses, function returns, and optional parameters. null is typically used to explicitly indicate "no object" while undefined usually indicates something wasn't initialized or doesn't exist. 💡 One common mistake: Using typeof null and expecting "null", but it actually returns "object" due to a historical JavaScript bug that was never fixed for backward compatibility. 📌 Bonus: let x; console.log(x); // undefined console.log(typeof x); // "undefined" let y = null; console.log(y); // null console.log(typeof y); // "object" (legacy bug!) // Checking for both if (value == null) { // true for both null AND undefined } if (value === null) { // true only for null } if (value === undefined) { // true only for undefined } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 6/50 – JavaScript Interview Question? Question: How do arrow functions differ from regular functions? Simple Answer: Arrow functions don't have their own this (they inherit from the enclosing scope), don't have arguments object, and cannot be used as constructors with new. They also have a more concise syntax. 🧠 Why it matters in real projects: Arrow functions are perfect for callbacks and methods where you want to preserve the outer this context (like in React class components or event handlers). However, they're not suitable for object methods where you need dynamic this. 💡 One common mistake: Using arrow functions as object methods and wondering why this is undefined or refers to the wrong object. Always use regular functions for object methods! 📌 Bonus: const obj = { name: 'Widget', // ❌ Wrong - arrow function greet: () => { console.log(this.name); // undefined (this = window/global) }, // ✅ Correct - regular function greet2: function() { console.log(this.name); // "Widget" } }; #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 20/50 – JavaScript Interview Question? Question: What is prototypal inheritance in JavaScript? Simple Answer: Prototypal inheritance is JavaScript's mechanism for objects to inherit properties and methods from other objects through the prototype chain. When you access a property, JavaScript first checks the object itself, then walks up the prototype chain until it finds the property or reaches null. 🧠 Why it matters in real projects: Understanding prototypes is fundamental to JavaScript's object model. It's how classes work under the hood, how built-in methods like Array.prototype.map() are available, and how you can extend native objects or create efficient object hierarchies. 💡 One common mistake: Confusing __proto__ (the actual link) with prototype (the property on constructor functions). Also, modifying built-in prototypes like Array.prototype in production code is considered a bad practice. 📌 Bonus: // Constructor function function Person(name) { this.name = name; } // Add method to prototype (shared by all instances) Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; const alice = new Person('Alice'); alice.greet(); // "Hello, I'm Alice" // Prototype chain alice.hasOwnProperty('name'); // true (own property) alice.hasOwnProperty('greet'); // false (inherited) alice.__proto__ === Person.prototype; // true // Modern ES6 class syntax (same prototype underneath) class Employee extends Person { constructor(name, title) { super(name); this.title = title; } } const bob = new Employee('Bob', 'Developer'); console.log(bob.greet()); // Inherits from Person #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Prototypes #OOP
To view or add a comment, sign in
-
#Interview Prep JavaScript array.sort() array.sort() is a JavaScript method used to arrange array elements in a specific order. By providing a compare function, we can control whether the sorting is ascending or descending. Example array Explanation ✅ arr = [6, 2, 4] arr.sort((a, b) => { return a - b; }) How TWO elements are chosen (visual angle) [ 6 , 2 , 4 ] ↑ ↑ a b JS picks neighbor elements a = 6 b = 2 Compare: 6 - 2 = 4 → swap After swap: [ 2 , 6 , 4 ] ▶️ Second pick [ 2 , 6 , 4 ] ↑ ↑ a b Now picks: a = 6 b = 4 Compare: 6 - 4 = 2 → swap After swap: [ 2 , 4 , 6 ] ▶️ Third (check) [ 2 , 4 , 6 ] ↑ ↑ a b Compare: 2 - 4 = -2 → no swap Array stays same ✅ JS always picks TWO values Assigns: first value → a second value → b It compares adjacent elements Moves forward like a sliding window [ a , b ] → compare → swap / no swap → move right 🔄 Same idea for descending arr.sort((a,b) => { return b - a }) [ 6 , 2 , 4 ] ↑ ↑ a b 2 - 6 = -4 → no swap → bigger stays first Result: [ 6 , 4 , 2 ] #JavaScript #Frontend #WebDevelopment #CodingTips #LinkedInLearning #ArrayMethods #Interview
To view or add a comment, sign in
-
Recent javascript interview questions I was interviewed. Though i wasn't selected but it gave me clear picture of the missing gaps. When i retrospect : Idea here is not just understanding the concepts is enough, you need to practice them with examples to stay with them to demonstrate when asked. Most intervewiers start with asking its definition and then a followup to demonstrate with an example problem to be given to you. Also very importantly simulate to build logic under pressurized circumstances (This can be done by keeping consistency in writing atleast 1 or 2 programs everyday to solve from simple to medium complexity problems). You may start with already seeing the solution to program them to 'wet' yourself but over the time start thinking first to build a pseudocode and then gradually uplift to solve problems atleast partially before looking for answers. Key here is : Patience and the practice and I truly mean here after experiencing the rejection under the hot seat. 1.) Event loop test by predicting output below : console.log('1'); console.log('2'); setTimeout(() => { console.log("This message appears after 2 seconds."); }, 0) Promise.resolve(console.log('4')); console.log('5'); 2.) Implement to sort by ID and then by score : const users = [{ id: '3', name: 'Alex', score: '45'}, { id: '4', name: 'Steve', score: '10'}, { id: '1', name: 'John', score: '24'}, { id: '2', name: 'James', score: '45'}]; 3.) write a closure to increment/decrement count in javascript 4.) What is event propagation and delegation, stateless vs stateful Vs Pure components 5.) What are synthetic events , throttling and debouncing 6.) React lifecycle and what is producer and consumer in Context in react 7.) what is CORS 8.) CSS rendering and styling 9.) Different types of Promise with specifically allSettled.
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