Coderslang

Search IconIcon to open search

Use Arrow Function as a Getter in JavaScript [Tech Interview Quiz]

Last updated Jan 11, 2023

With the advent of ES6, arrow functions have conquered the JavaScript world.

Consider the following code snippet and determine the result.

Code snippet as a picture

1
2
3
const obj = { id: 1, getId: () => this.id };  
  
console.log(obj.getId());

Are there any issues with the getId function? What will be logged to the console? (think well, then click for the answer and explanation)

Explanation

The function getId is an arrow function, so it doesn’t have this of its own.

It’s not bound to this of the obj object and when we try to get this.id it will be evaluated to undefined and not 1.

Answer

undefined will be logged to the console

🔥 START LEARNING 🔥