Day 22/50 – JavaScript Interview Question? Question: What is the this keyword and how is it determined? Simple Answer: this refers to the object that is executing the current function. Its value is determined by how the function is called: in a method it's the object, in a regular function it's the global object (or undefined in strict mode), in an arrow function it's lexically inherited from the enclosing scope. 🧠 Why it matters in real projects: Understanding this is critical for object-oriented programming, event handlers, and React class components. Incorrect this binding is one of the most common sources of bugs, especially when passing methods as callbacks. 💡 One common mistake: Losing the this context when passing object methods as callbacks (like event handlers), resulting in this being undefined or pointing to the wrong object. 📌 Bonus: const user = { name: 'Alice', greet: function() { console.log(`Hello, ${this.name}`); }, greetArrow: () => { console.log(`Hello, ${this.name}`); // Won't work! } }; user.greet(); // "Hello, Alice" ✓ const greetFunc = user.greet; greetFunc(); // "Hello, undefined" - lost context! // Solutions for callback context: // 1. Bind button.addEventListener('click', user.greet.bind(user)); // 2. Arrow function wrapper button.addEventListener('click', () => user.greet()); // 3. Arrow function in class (React) class Component { handleClick = () => { // Auto-bound! console.log(this); } } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #ThisKeyword #InterviewPrep #OOP
Understanding the this Keyword in JavaScript
More Relevant Posts
-
Day 24/50 – JavaScript Interview Question? Question: What is the difference between Object.freeze(), Object.seal(), and Object.preventExtensions()? Simple Answer: Object.freeze() makes an object completely immutable (can't add, delete, or modify properties). Object.seal() prevents adding/deleting properties but allows modifying existing ones. Object.preventExtensions() only prevents adding new properties. 🧠 Why it matters in real projects: These methods enforce immutability and data integrity, crucial for functional programming, Redux state management, and preventing accidental mutations in configuration objects or constants. 💡 One common mistake: Thinking Object.freeze() creates a deep freeze. It only freezes the top level—nested objects remain mutable. You need recursive freezing for complete immutability. 📌 Bonus: // Object.freeze() - completely immutable const frozen = Object.freeze({ name: 'Alice', age: 30 }); frozen.age = 31; // ✗ Ignored (or throws in strict mode) frozen.city = 'NYC'; // ✗ Can't add delete frozen.name; // ✗ Can't delete // Object.seal() - modify only const sealed = Object.seal({ name: 'Bob', age: 25 }); sealed.age = 26; // ✓ Can modify sealed.city = 'LA'; // ✗ Can't add delete sealed.name; // ✗ Can't delete // Object.preventExtensions() - most permissive const limited = Object.preventExtensions({ name: 'Charlie' }); limited.name = 'Chad'; // ✓ Can modify limited.age = 30; // ✗ Can't add delete limited.name; // ✓ Can delete // Deep freeze for nested objects function deepFreeze(obj) { Object.freeze(obj); Object.values(obj).forEach(val => { if (typeof val === 'object' && val !== null) { deepFreeze(val); } }); } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🛑 JavaScript Interview: Do you know the Return Types? We use .map(), .filter(), and .reduce() every day. But can you explain precisely what they Return? Here is the breakdown that separates Junior Devs from Senior Devs: 1️⃣ .map() ➡️ Returns a New Array 📦 It creates a modified copy of the original array. Input: [1, 2, 3] (Array) Output: [2, 4, 6] (Array of same length) Use case: Transformation. 2️⃣ .filter() ➡️ Returns a New Array 📦 It returns a subset of the original array. Input: [1, 2, 3] (Array) Output: [2] (Array of smaller length) Use case: Selection/Removal. 3️⃣ .reduce() ➡️ Returns a Single Value 💎 This is the game changer. It processes the array to produce ONE result. Input: [1, 2, 3] (Array) Output: 6 (Number / String / Object) Use case: Accumulation (Sum, Object creation). 💡 The "Gotcha": If you assign .forEach() to a variable, it returns undefined. But .map() and .filter() will always give you an Array. Which one do you find most powerful? For me, .reduce() is pure magic. ✨ #javascript #webdevelopment #codingtips #reactjs #frontenddeveloper #softwareengineering #interviewquestions
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 23/50 – JavaScript Interview Question? Question: What is memoization and how do you implement it? Simple Answer: Memoization is an optimization technique that caches function results based on input arguments. When the function is called again with the same arguments, it returns the cached result instead of recalculating. 🧠 Why it matters in real projects: Memoization dramatically improves performance for expensive computations like recursive Fibonacci, API response parsing, or complex filtering/sorting. React's useMemo and React.memo are built on this principle to prevent unnecessary re-renders. 💡 One common mistake: Over-memoizing everything, which adds memory overhead. Only memoize truly expensive operations. Also, not considering cache size limits, which can cause memory leaks in long-running applications. 📌 Bonus: // Basic memoization implementation function memoize(fn) { const cache = new Map(); return function(...args) { const key = JSON.stringify(args); if (cache.has(key)) { console.log('Returning cached result'); return cache.get(key); } const result = fn.apply(this, args); cache.set(key, result); return result; }; } // Usage: Expensive calculation const fibonacci = memoize((n) => { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }); fibonacci(40); // Calculated once fibonacci(40); // Instant! (from cache) // React example const expensiveComponent = React.memo(({ data }) => { // Only re-renders if data changes }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 17 Topic: Recursion in JavaScript Continuing my JavaScript interview preparation journey, today I revised a classic and frequently asked concept: 👉 Recursion Many developers fear recursion at first, but once the idea clicks, it becomes very intuitive. 🪆 Real-World Example: Russian Nesting Dolls Think of Russian Matryoshka dolls. You open one doll… Inside it, there’s a smaller doll You keep opening until you reach the smallest doll That’s where you stop Then you close them back one by one This is exactly how recursion works. Mapping to JavaScript Opening a doll → Function calling itself Smaller doll → Smaller input Smallest doll → Base case (stop condition) Closing dolls → Returning values back up 💻 Simple JavaScript Example (Factorial) function factorial(n) { // Base case if (n === 0 || n === 1) { return 1; } // Recursive case return n * factorial(n - 1); } console.log(factorial(5)); // 120 How it works: factorial(5) → 5 * factorial(4) → 5 * 4 * factorial(3) → 5 * 4 * 3 * factorial(2) → 5 * 4 * 3 * 2 * factorial(1) → returns 1 (base case) Then values return back: 2 * 1 = 2 3 * 2 = 6 4 * 6 = 24 5 * 24 = 120 ⚠️ Important Rules of Recursion ✔ Must have a base case ✔ Each call should reduce the problem ✔ Otherwise → infinite loop / stack overflow ✅ Why Interviewers Ask This Recursion tests: • Problem-solving skills • Understanding of call stack • Base vs recursive case clarity • Ability to break problems into smaller ones Common recursion problems: • Factorial • Fibonacci • Tree traversal • Nested data handling 📌 Goal: Share daily JavaScript interview topics while revising fundamentals and learning in public. Next topics: Event Delegation, Call Stack deep dive, Async Iteration, and more. Let’s keep learning step by step 🚀 #JavaScript #InterviewPreparation #Recursion #DSA #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Go through this JavaScript Interview questions to crack most of the Interviews. I hope you get your dream Job. #hiring #javascript #hr
📷||Content Creator ||UGC Creator || 📢 Brand Promotion Specialist || Helping Brands Grow with High-Impact Content || 📩 Open for collaborations, UGC projects & brand pramotion.🤝
🚀 Top 50 JavaScript Interview Questions Every Developer Should Know in 2026. JavaScript interviews are no longer just about syntax — recruiters now test logic, concepts, and real-world understanding. Compiled 50 must-know JavaScript interview questions covering: ✅ Core JavaScript Concepts ✅ Closures & Scope ✅ Hoisting & Execution Context ✅ Promises & Async/Await ✅ Event Loop ✅ ES6+ Features ✅ DOM & APIs ✅ Practical Coding Scenarios Perfect for: 💡 Students preparing for placements 💡 Frontend Developers 💡 Web Development Beginners 💡 Developers switching roles Save this post 📌 before your next interview — consistency + concept clarity = selection. 💬 Comment **"JS"** if you want the answers or detailed explanations. Prachi Dwivedi #JavaScript #WebDevelopment #FrontendDeveloper #CodingInterview #100DaysOfCode #Developers #Programming #TechCareers #InterviewPreparation
To view or add a comment, sign in
-
🚀 JavaScript Interview Questions – Are You Really Prepared? Here are 5 questions many developers struggle to answer clearly: 1️⃣ What is the difference between parseInt() and Number()? Answer: parseInt() parses until invalid character; Number() converts entire string or returns NaN. 2️⃣ How do you check if a variable is an array? Answer: Using Array.isArray(). 3️⃣ What is the output of typeof null? Answer: "object" (a known JS quirk). 4️⃣ What is destructuring assignment? Answer: Syntax for unpacking values from arrays or properties from objects. 5️⃣ What is event bubbling? Answer: When an event propagates from child to parent elements. ⚠️ These are just 5 out of 3000+ JavaScript Interview Questions & Answers covered in my book. If you're preparing for: Frontend interviews React / Node roles Product-based companies Startup technical rounds This book is designed for clear, precise, interview-focused answers. 📘 3000+ Questions 📘 Beginner to Advanced 📘 Concise, interviewer-ready explanations If you're serious about cracking JavaScript interviews, this resource will save you months of preparation time.
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 8 Topic: Object Methods in JavaScript Continuing my JavaScript interview brush-up, today I revised a very practical topic: 👉 Object Methods in JavaScript We often create objects with data, but objects can also perform actions using methods. 🔧 Real-World Example: Swiss Army Knife Think of a Swiss Army knife. It is one tool with multiple functions: Knife to cut Screwdriver to fix Bottle opener to open bottles Similarly, in JavaScript: The object is the knife body. The methods are the tools. Each method performs a different action. One object → multiple capabilities. 💻 JavaScript Example const person = { name: "John", age: 30, greet() { console.log("Hello, my name is " + this.name); }, walk() { console.log(this.name + " is walking"); }, sleep() { console.log(this.name + " is sleeping"); } }; person.greet(); person.walk(); person.sleep(); Output Hello, my name is John John is walking John is sleeping Here: name and age are properties greet, walk, sleep are methods this refers to the current object. ✅ Why This Matters in Interviews Object methods help explain: • How objects encapsulate behavior • Usage of this keyword • OOP patterns in JavaScript • Class syntax internally 📌 Goal: Share daily JavaScript concepts while preparing for interviews and help others revise fundamentals. Next topics: this deep dive, bind/call/apply, promises, async/await, and more. Let’s keep learning in public 🚀 #JavaScript #InterviewPreparation #ObjectMethods #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
🚀 JavaScript Interview Prep Series — Day 12 Topic: Error Handling in JavaScript (try, catch, finally) Continuing my JavaScript interview revision series, today’s focus was on a very important but often overlooked topic: 👉 Error Handling using try–catch–finally Good developers don’t just write code that works — they write code that handles failures gracefully. 🎪 Real-World Example: Circus Safety Net Imagine a trapeze performance in a circus. 1️⃣ Acrobat attempts a risky trick (TRY). 2️⃣ If something goes wrong, the safety net catches them (CATCH). 3️⃣ After performance, crew resets equipment no matter what (FINALLY). Whether success or failure, cleanup always happens. JavaScript error handling works the same way. 💻 Practical JavaScript Example async function fetchUser() { try { console.log("Fetching user data..."); const response = await fetch("https://lnkd.in/dAktZdHe"); if (!response.ok) { throw new Error("Failed to fetch data"); } const data = await response.json(); console.log("User:", data); } catch (error) { console.error("Something went wrong:", error.message); } finally { console.log("Cleanup: Stop loader / close connection"); } } fetchUser(); Execution Flow ✅ If request succeeds → catch block is skipped ❌ If request fails → catch handles error 🔁 finally runs in both cases ✅ Why Interviewers Ask This Because it tests: • Defensive coding skills • Async error handling understanding • Custom error throwing • Production-ready code thinking 📌 Goal: Share daily JavaScript concepts while preparing for interviews and help others revise fundamentals. Next topics: Event delegation, closures deep dive, execution context, and more. Let’s keep learning in public 🚀 #JavaScript #InterviewPreparation #ErrorHandling #AsyncJavaScript #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
"This popular JavaScript question might surprise you! 🔍" Ever been thrown off by a simple question about closures in JavaScript during an interview? You’re not alone. Closures are fundamental but often misunderstood. Interviewers ask about them to see if you grasp the inner workings of functions and scopes. Typical mistake: "Closures are just functions inside functions." Not quite. Closures allow an inner function to access variables of its outer function even after the outer function has executed. But why do they matter? Closures power essential JS concepts like data encapsulation and the module pattern. They’re crucial for writing efficient code. In interviews, showing you understand real-world applications of closures sets seasoned developers apart from the juniors. Next time you face this question, remember to demonstrate: - How closures help manage state - Real-life scenarios like event handlers and callbacks Ask yourself: "Can I explain closures without jargon?" "Save this to ace your next coding interview! 💡" #interviewprep #javascript #frontend
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
Nicely explained. this is determined by the call site, not the definition losing context in callbacks is where most bugs sneak in