40
loading...
This website collects cookies to deliver better user experience
undefined
. So, if you define a parameter but you don't provide it in the function call, the value will be undefined
.function greeting(name) {
console.log(`hello ${name}`)
}
greeting() // hello undefined
function greeting(name = 'guest') {
console.log(`hello ${name}`)
}
greeting() // hello guest
function makeSmoothie (type, sugarLevel = 1, topping = 'pudding', size: 'small'){
// code to make a smoothie
}
makeSmothie
, which has 1 required parameter, and 3 optional parameters (sugarLevel
, topping
, size
). In case you wrote code like this, you better keep reading this post.makeSmoothie('mango')
makeSmoothie('mango', 2)
makeSmoothie('mango', 1, 'red bean')
size
parameter.makeSmoothie('mango', 1, 'pudding', 'medium')
sugarLevel
and topping
? This is just a sample case to show you the problem you might face if you write code similar to the sample. Let's solve the problem.function makeSmoothie (type, sugarLevel = 1){
// code to make a smoothie
}
Object
and Object Destructuring
function makeSmoothie (type, { sugarLevel = 1, topping = 'pudding', size = 'small' } = {}){
// code to make a smoothie
}
type
and variant
. We can call the function in a more efficient way:makeSmoothie('mango')
makeSmoothie('mango', { sugarLevel: 2 })
makeSmoothie('mango', { topping: 'red bean'})
makeSmoothie('mango', { size: 'medium'})