Last active
August 28, 2021 16:27
-
-
Save tararoutray/e945017d8c1c0275465eef9b7cab88aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's declare a variable of type array | |
let numbers = [1, 2, 3]; | |
// Let's write a function with old style | |
function calculateNumbers() { | |
this.total = 0; | |
numbers.forEach(function(singleNumber) { | |
// Here the "this" keyword is pointing to the wrong location. | |
// The "this" keyword is pointing towards the current function instead of outer function. | |
this.total += singleNumber; | |
}); | |
return total; | |
} | |
// Now see how we can solve this problem using the arrow function | |
const calculateNumbers = () => { | |
this.total = 0; | |
// Now the keyword "this" points to the outer function | |
// Correct implementation | |
numbers.forEach(singleNumber => (this.total += singleNumber)); | |
return total; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment