DEV Community

loading...
Cover image for JavaScript Interview Question #15: Getter function

JavaScript Interview Question #15: Getter function

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・1 min read

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

Discussion (2)

pic
Editor guide
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