Function Improvements: Arrows and Default Arguments Flashcards
Name three benefits of arrow functions over normal functions.
Much more concise.
Implicit returns allow one liners.
Doesn’t rebind the value of this when you use an arrow function inside another function. (useful for click handlers etc)
What would you do to make this an arrow function?
var sayMyName = function(name){ };
- Remove the word ‘function’.
- Add a fat arrow =>
- Change var to use const
To make:
const sayMyName = (name) => { }
If an arrow function only has one parameter what can you do to simplify the code?
Remove the parenthesis around the parameter.
How could you simplify this function?
const fullNames2 = names.map((name) => { return `${name} bos`; });
Remove the parenthesis.
const fullNames2 = names.map(name => { return `${name} bos`; });
What is an explicit return?
When you explicitly write the word ‘return’ for what you’re returning.
What is an implicit return?
An implicit return allows one liner functions without having to specify the word ‘return’
How do you turn an explicit return arrow function into an implicit return?
Remove the word ‘return’
Put it all on one line.
Then delete the curly brackets.
If you have no arguments in an arrow function, what must you do?
Pass an empty parenthesis:
const sayMyName = () => { }
Arrow functions are always what type of function?
Anonymous functions.
What is an named function?
A function that is actually named.
A named function looks like this;
function sayMyName() {
What is an anonymous function?
Functions that don’t have names.
Name a disadvantage of using an arrow function over a named function?
Arrow functions are Anonymous functions so as they aren’t named they may not be as easy to stack trace.
If you wanted log a table of data, what would you use?
console.table(object);
If you wanted to implicitly return an object literal. What steps would you have to take to make it work?
const win = winners.map((winner, i) => {name: winner, race, place: i + 1});
to prevent having to remove the curly brackets as you usually would with an implicit return you need to add parenthesis around it.
const win = winners.map((winner, i) => ({name: winner, race, place: i + 1}));
How could you shorten this function?
const win = winners.map((winner, i) => ({name: winner, race: race, place: i + 1}));
If variable name and the property is the same you can just list ‘race’ once.
const win = winners.map((winner, i) => ({name: winner, race, place: i + 1}));