javascriptfunctionecmascript-6default-parameters

javaScript function - why my default argument fails?


My Javascript function leads my console to return me :

TypeError: style is null

Here the snippet:

let style = {
  one: 1,
  two: 2,
  three: 3
}

function styling(style = style, ...ruleSetStock) {

  return ruleSetStock.map(ruleSet => {
    console.log(ruleSet)
    return style[ruleSet]
  })
}

console.log(styling(null, "one", "two", "three"))

I can't understand why. It seems to me everything is great,

Any hint would be great, thanks.


Solution

  • Default parameters is assigned only if no value or undefined is passed

    let defaultStyle = {  one: 1, two: 2, three: 3 }
    
    function styling(style = defaultStyle, ...ruleSetStock) {
      return ruleSetStock.map(ruleSet => {
        return style[ruleSet]
      })
    }
    
    console.log(styling(undefined, "one", "two", "three"))

    What if i want to use default value on all sorts of falsy values such as false, '', null ?

    You can't use default parameter for that but you can use ||

    let style1 = {  one: 1, two: 2, three: 3 }
    
    function styling(style, ...ruleSetStock) {
      style = style || style1
      return ruleSetStock.map(ruleSet => {
        return style[ruleSet]
      })
    }
    
    console.log(styling(undefined, "one", "two", "three"))
    console.log(styling(null, "one", "two", "three"))
    console.log(styling('', "one", "two", "three"))
    console.log(styling(0, "one", "two", "three"))