Skip to content

Instantly share code, notes, and snippets.

@tararoutray
Last active August 28, 2021 16:27
Show Gist options
  • Save tararoutray/e945017d8c1c0275465eef9b7cab88aa to your computer and use it in GitHub Desktop.
Save tararoutray/e945017d8c1c0275465eef9b7cab88aa to your computer and use it in GitHub Desktop.
// 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