What does the syntax in the first example mean?
the used syntax is a combination of default parameters syntax and destructuring assignment syntax
What is the significance of the '= {}' part?
using the default parameters syntax: the '= {}'
part set {}
(an empty object) as the default value for the single parameter taken by getMovies
let's break it down:
here, we set 'flying'
as default value for the power
parameter
function giveSuperPower(power='flying'){
console.log(`you have got: "${power}"`);
}
giveSuperPower('infinite energy');
// you have got: "infinite energy"
giveSuperPower();
// you have got: "flying"
what if the parameter was an object?
function giveSuperPower(power){
console.log(`you have got: "${power.name||'flying'}"`);
console.log(`it last for ${power.duration||'∞'}min`);
}
giveSuperPower({name: 'strength', duration: 5 });
// you have got: "strength"
// it last for 5min
looks good.. right?
lets try
giveSuperPower();
// Uncaught ReferenceError: power is not defined
okay that's a problem.
lets set a default parameter value (an empty object)
function giveSuperPower(power={}){
console.log(`you have got: "${power.name||'flying'}"`);
console.log(`it last for ${power.duration||'∞'}min`);
}
giveSuperPower();
//you have got: "flying"
//it last for ∞min
let's destructure the power power
parameter
function giveSuperPower({name, length} = {}){
console.log(`you have got: "${name||'flying'}"`);
console.log(`it last for ${duration||'∞'}min`);
}
let's set default parameter values for name
and length
function giveSuperPower({name = 'flying', length = '∞'} = {}){
console.log(`you have got: "${name}"`);
console.log(`it last for ${duration}min`);
}
that's it :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…