Their secure, open-source backend asa service gives you all the core APIs you need to build anything you can think of.
function reduceLanguages (str, lang, i) { if (i === this.languages.length - 1) { return `${str} and ${lang}.`; } return `${str} ${lang},`; } const user = { name: "Tyler", age: 27, languages: ["JavaScript", "Ruby", "Python"], greet() { const hello = `Hello, my name is ${this.name} and I know`; const langs = this.languages.reduce(reduceLanguages, ""); return hello + langs; }, }; const greeting = user.greet()
If you run the original code, you’ll get “Uncaught TypeError: Cannot read properties of undefined (reading ‘length’)“. The only place we’re using .length is inside our reduceLanguages function, so we can infer that this.languages is undefined and we’re incorrectly using the this keyword.
Whenever you’re trying to figure out what the this keyword is referencing, you need to look at where the function using the this keyword is being invoked. In our example, we don’t know since it’s in the implementation of reduce. To make sure reduceLanguages gets invoked in the right context and therefor has the correct this binding, we have two choices. First, the old school way - using .bind.
greet() { const hello = `Hello, my name is ${this.name} and I know`; const langs = this.languages.reduce(reduceLanguages.bind(this), ""); return hello + langs; }
Second, the better way - using an arrow function.
greet() { const hello = `Hello, my name is ${this.name} and I know`; const langs = this.languages.reduce((str, lang, i) => { if (i === this.languages.length - 1) { return `${str} and ${lang}.`; } return `${str} ${lang},`; }, ""); return hello + langs; }
The reason this works is because with arrow functions, this is determined lexically. Arrow functions don’t have their own this. Instead, just like with variable lookups, the JavaScript interpreter will look to the enclosing (parent) scope to determine what this should reference.
Want to read more? Check out Understanding the “this” keyword, call, apply, and bind in JavaScript.