Top 5 JavaScript Interview Problems (With Real-World Solutions)

1.59K 0 0 0 0

Chapter 3: Understanding this and Arrow Functions (with Real Challenges)

🧠 Why This Matters

If there's one concept in JavaScript that's infamous for confusing even seasoned developers, it's the this keyword. Combined with arrow functions (introduced in ES6), understanding this is critical for debugging, writing clean callbacks, and avoiding weird runtime errors.

Interviewers love to test your depth here β€” not just the definitions, but whether you can predict, debug, and refactor real code using this and arrow functions correctly.

In this chapter, you’ll:

  • Learn how this behaves in regular functions, arrow functions, and methods
  • Understand how this changes depending on context
  • Solve real-world bugs involving callbacks, timers, and DOM events
  • Master arrow function traps in object methods and classes

πŸ“ 1. What Is this?

In JavaScript, this refers to the context in which a function is executed.

It’s not determined when the function is defined β€” but when it’s called.


βœ… Example 1: Global Context

console.log(this); // In browser: `window`, in Node.js: `{}` or `global`


βœ… Example 2: Inside an Object Method

const user = {

  name: "Ava",

  greet() {

    console.log(this.name); // βœ… Ava

  }

};

 

user.greet();


⚠️ Example 3: Detached Function (Lost Context)

const user = {

  name: "Zain",

  greet() {

    console.log(this.name);

  }

};

 

const fn = user.greet;

fn(); // ❌ undefined (because `this` = global)

The method lost its context β€” this became global.


⚑ Arrow Functions: No Own this

Arrow functions don’t have their own this. Instead, they inherit this from the parent (lexical scope).


βœ… Example 4: Arrow Function Inside Method

const team = {

  name: "Dev Squad",

  members: ["Ali", "Sara"],

  logMembers() {

    this.members.forEach(member => {

      console.log(`${member} - ${this.name}`);

    });

  }

};

 

team.logMembers();

// βœ… Ali - Dev Squad

// βœ… Sara - Dev Squad

βœ… Works because arrow function captures this from logMembers


🚫 Example 5: Arrow Function as Object Method

const obj = {

  name: "Fail",

  greet: () => {

    console.log(this.name); // ❌ undefined

  }

};

 

obj.greet();

Arrow functions don’t get their own this, and in this case, this refers to the global object β€” not obj.


πŸš€ Real Interview Challenge #1: Fix the Callback this Bug

const user = {

  name: "Lina",

  greet() {

    setTimeout(function () {

      console.log(`Hi, I'm ${this.name}`);

    }, 1000);

  }

};

 

user.greet(); // ❌ Hi, I'm undefined

βœ… Fix using arrow function:

setTimeout(() => {

  console.log(`Hi, I'm ${this.name}`);

}, 1000);

βœ… Or save this into a variable:

const self = this;

setTimeout(function () {

  console.log(`Hi, I'm ${self.name}`);

}, 1000);


🧠 Real Interview Challenge #2: Predict the Output

const person = {

  name: "John",

  greet: function () {

    console.log("Hi " + this.name);

  }

};

 

const greetFn = person.greet;

greetFn(); // ???

βœ… Answer: Hi undefined
Why? The function was detached from person, and this is now the global object (in browser: window.name or undefined)


🧠 Real Interview Challenge #3: Use bind() to Fix Context

const dog = {

  sound: "woof",

  speak() {

    console.log(this.sound);

  }

};

 

const speakNow = dog.speak.bind(dog);

speakNow(); // βœ… woof

bind() permanently sets the value of this


πŸ” Arrow Functions in Classes

class Timer {

  constructor() {

    this.seconds = 0;

  }

 

  start() {

    setInterval(() => {

      this.seconds++;

      console.log(this.seconds);

    }, 1000);

  }

}

 

const t = new Timer();

t.start(); // βœ… Arrow function uses `this` from class instance


❌ Common Mistakes

Mistake

Fix

Arrow function as method

Use regular function if this is needed

Losing context when passing functions

Use .bind(), or arrow function to preserve this

Assuming this always refers to object

Remember: It depends on how the function is called

Using arrow functions in class prototypes

Avoid β€” methods should be regular functions


βœ… Summary

Concept

Description

this

Refers to the current execution context

Arrow function

Inherits this from outer scope

Object methods

Best written with regular function expressions

bind()

Used to manually set the value of this

Common bugs

Passing methods as callbacks, arrow functions in objects


Back

FAQs


1. What’s the best way to prepare for JavaScript interviews?

Focus on the fundamentals: closures, scoping, async/await, and the event loop. Practice real code challenges, not just theory.

2. Is ES6 knowledge enough for interviews?

Mostly yes, but you also need to understand JavaScript’s core behaviors beyond just syntax β€” like prototype chains and hoisting.

3. Why are closures and scopes such common questions?

Because they reveal whether a developer understands how memory, function environments, and execution context work in JS.

4. Do interviews test JavaScript beyond the browser?

Yes. Even full-stack roles often involve Node.js questions, but core JS concepts are always in play.

5. How important is async programming in interviews?

Very. Interviewers often test your ability to handle real-world async flows β€” promises, async/await, and the event loop.

6. Should I memorize definitions or practice solving problems?

Practice! Understand the why and how behind behaviors β€” interviews often involve debugging or refactoring.

7. Are array methods like .map() and .reduce() really asked?

Yes β€” often in coding challenges or refactor tasks to test clean, functional thinking.

8. Do I need to know prototypal inheritance?

Absolutely. You should understand how prototypes work and how classes build on top of them.

9. What tools should I use for practicing JavaScript interviews?

Platforms like LeetCode, CodeSignal, JSFiddle, and browser DevTools are great. Pair with actual coding in VS Code for muscle memory.

10. What’s the #1 mistake devs make in JS interviews?

Rushing to code without fully understanding the problem. Many JS bugs come from misunderstanding scope, context, or async behavior.

Tutorials are for educational purposes only, with no guarantees of comprehensiveness or error-free content; TuteeHUB disclaims liability for outcomes from reliance on the materials, recommending verification with official sources for critical applications.