DEV Community

Cover image for JavaScript Interview Question #15: Getter function
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

9 1

JavaScript Interview Question #15: Getter function

js-test-15

Can we use an arrow function as a getter in JavaScript? What’s going on and what will be logged to the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

So, we have an object with a single field id equal to 1 and two functions getIdArrow and getIdFunction which supposedly do the same thing, return the value of id.

Unfortunately, that’s not the case. In JavaScript, arrow functions are different from the regular ones. There’s no binding between this inside of the arrow function and the object obj. Thus this.id will be evaluated to undefined.

In case of the getIdFunction, this is bound to the obj and this.id is the same as obj.id, which is 1.


ANSWER: the first console.log will print the number 1 to the console. The second one will print false.

Learn Full Stack JavaScript

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (2)

Collapse
 
thi3rry profile image
Thierry Poinot • Edited

Is "this" in the arrow function doesn't return the id prop of the global scope ?
If you define an id prop on window, your arrow getter would return the window.id value no ?

Collapse
 
coderslang profile image
Coderslang: Become a Software Engineer

Yes, it absolutely would.

window-id

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay