var rahul = {
name: 'Rahul',
lastName: 'Kumar',
yearOfBirth: 1990,
calculateAge: function() {
return 2018 - this.yearOfBirth;
}
}
console.log(rahul.calculateAge());
// output : 31
var rahul = {
name: 'Rahul',
lastName: 'Kumar',
yearOfBirth: 1990,
calculateAge: () => {
return 2018 - this.yearOfBirth;
}
}
console.log(rahul.calculateAge());
// Output : NaN
Asked
Active
Viewed 38 times
0

Scath
- 3,777
- 10
- 29
- 40

Rahul Kumar
- 777
- 1
- 5
- 14
-
1@PraveenKumar arrow functions are **significantly** different from ordinary functions. – Pointy Jun 19 '18 at 13:15
-
@PraveenKumar — You mean there are major differences between them that trip people up, and make code harder to maintain if you use them inappropriately? – Quentin Jun 19 '18 at 13:15
-
@Quentin Kinda, yeah... – Praveen Kumar Purushothaman Jun 19 '18 at 13:16
-
I swear finding duplicates here is way harder than it should be. – Pointy Jun 19 '18 at 13:16
-
@Pointy Do you mean the scope changes? – Praveen Kumar Purushothaman Jun 19 '18 at 13:16
-
@PraveenKumar it's not *scope*, it's the way `this` is treated, the fact that there's no `arguments` object, etc. – Pointy Jun 19 '18 at 13:16
-
I am getting different outputs by using different function – Rahul Kumar Jun 19 '18 at 13:16
-
@RahulKumar Yes... You don't have the option to use `this` in case of arrow functions. Right! – Praveen Kumar Purushothaman Jun 19 '18 at 13:18
-
@PraveenKumar — Wrong. – Quentin Jun 19 '18 at 13:18
-
@Quentin Sure... Thanks. Correct me for that statement. I need to improve as well. There's something related to `this` in this context. What's `this` here? – Praveen Kumar Purushothaman Jun 19 '18 at 13:19
-
@PraveenKumar — There's a perfectly good duplicate question linked at the top of the page that explains. – Quentin Jun 19 '18 at 13:19
-
@Quentin Sorry for being dumb... `:P` Gotcha... Nice one BTW... – Praveen Kumar Purushothaman Jun 19 '18 at 13:20
-
Still not able to understand the difference in the output. BTW thanks. – Rahul Kumar Jun 19 '18 at 13:39