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
.