❓ Can You Solve This JavaScript Interview Puzzle?
🚀 Aspiring Full-Stack Developer Blogger 👨💻 Passionate about web development and coding. ✍️ Sharing my journey through tech via CodeOdyssey 🌍 "The code is a journey, not a destination."
💡 “Programming isn’t about typing code. It’s about thinking through problems.”
JavaScript interviews are known for throwing in some tricky questions that test more than just syntax — they challenge how well you understand how the language actually works.
Let’s explore a real-world style question:
🧠 The Question
What will the following code output — and why?
jsCopyEditconst obj = {
name: "Nora",
greet: function () {
return `Hello, ${this.name}`;
},
};
const greetFn = obj.greet;
console.log(greetFn()); // ❓
console.log(obj.greet()); // ✅
Can you guess the output?
🧐 Think Before Scrolling!
This isn’t just about remembering syntax. It’s about understanding how this works in JavaScript.
Let’s break it down.
🔍 What’s Happening Behind the Scenes?
When we call obj.greet(), it works as expected:
jsCopyEditobj.greet(); // "Hello, Nora"
But when we assign it like this:
jsCopyEditconst greetFn = obj.greet;
greetFn(); // ???
We're detaching the method from its object, so this no longer refers to obj. Instead, it defaults to:
undefinedin strict modeThe global object (
windowin browsers) in non-strict mode
In most environments, this.name becomes undefined.
So the output is:
jsCopyEditundefined
Hello, Nora
🛠️ How Can We Fix It?
If you want to keep the context (this) when passing methods around, use .bind():
jsCopyEditconst greetFn = obj.greet.bind(obj);
greetFn(); // "Hello, Nora"
Or use arrow functions (in other contexts), which don't bind their own this.
🧠 Key Takeaways
In JavaScript,
thisdepends on how a function is calledAssigning a method to a variable can lose its
thisbindingUse
.bind()to preserve contextThese are common traps in interviews and real-world apps!
❓Challenge for You
Can you guess the output of this?
jsCopyEditlet length = 10;
function callback() {
console.log(this.length);
}
const obj = {
length: 5,
method(callback) {
callback(); // ?
arguments[0](); // ?
},
};
obj.method(callback);
🧠 Think you know the answer? Try it, analyze it, and share your explanation!
✍️ Final Thoughts
Understanding how this works is key to mastering JavaScript — especially if you're preparing for job interviews or building complex web apps.
Want more puzzles like this? Follow me and stay tuned for weekly code challenges!

