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

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

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