DEV Community

Azaan Suhail
Azaan Suhail

Posted on

Day 6 of Complete JavaScript in 17 days | Visual Series📚✨

Day 6 of My JavaScript Visual Series 📚✨

💡 Arrow Function vs Normal Function in JavaScript – Why It Actually Matters in Interviews.

As a beginner, I used to think both functions are the same. But here's what interviewers love to ask the difference in how "this" behaves in both!
🔹 Normal Function:
this refers to the object calling the function.

🔹 Arrow Function:
this refers to the parent scope (lexical scope). It does not bind its own this.
So if you're using this inside a method, be very cautious using arrow functions!

const obj = {
 name: "Azaan",
 sayHi: function () {
 console.log("Hi", this.name); // Works ✅
 },
 greet: () => {
 console.log("Hello", this.name); // Undefined ❌
 }
};
Enter fullscreen mode Exit fullscreen mode

Fun Fact : Arrow function is also called fat arrow function.

Use Case:

A couple of days ago, I was debugging a login feature in my app. Everything seemed perfect... except it kept saying "Invalid Password" even for correct ones.
The issue? I used an arrow function inside my comparePassword method. 🤦‍♂️
It couldn't access this.password from the Mongoose model correctly.

// ❌ Wrong: 'this' doesn't refer to the document
userSchema.methods.comparePassword = (inputPassword) => {
 return bcrypt.compare(inputPassword, this.password);
};
Enter fullscreen mode Exit fullscreen mode
// ✅ Correct: 'this' refers to the Mongoose document
userSchema.methods.comparePassword = function (inputPassword) {
 return bcrypt.compare(inputPassword, this.password);
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)