JavaScript Scope and this.name Puzzle

🚨 Quick JavaScript challenge Looks like a simple object method accessing this.name. Nothing fancy. Should work… right? But the output is not what most people expect. Before running it - Ask yourself: 👉 Does an object create scope? 👉 Where does this really come from? 👉 Arrow vs normal function - who controls it? Guess the output 👇 #JavaScript #Frontend #CodingChallenge

  • text

The output is undefined because the outer function is an arrow function, which does not have its own this and inherits it from the surrounding lexical scope (global). The inner function is a normal function, and since it is called without an object reference, its this also points to the global scope,therefore this.name is undefined. What happens to this when an arrow function is defined inside a normal function? What will be the output and why?

Answer will be undefined. because arrow fn don't have their own this, so this in outer fn call will point to global scope. and regular functions this point to the environment where it has been executed. So inside inner fn call also this will be global object And we do not have any variable "name" in global scope that gives result `undefined`

It will be either undefined or window (based on whether it is in strict mode or not).

Like
Reply

Undefined. Because outer is an arrow function, this is not bound to user, and inner is called without a context, so this.name resolves to undefined.

Undefined, because it's window.inner() and this refer to window here and window.name will be undefined

Objects don’t create scope. Arrow functions don’t bind this. Normal functions decide this at call time. Answer will be undefined.

See more comments

To view or add a comment, sign in

Explore content categories