JavaScript Evaluation Shorthand issue

Viewed 36

Possibly very simple but I'm not sure how to correctly write the following evaluation and assignment, where I'm trying to assign configuration values to a widget and set a fallback default value if the config isn't set. If it's not possible in the way I'm attempting, I can fall back to an if/else before setting the value. Grateful for any pointers.

console.log(config);

    // Outputs
    {autoplay: false}

    $(el).slick({
        // Sets autoplay to true instead of false, as it evaluates it as not null (I think)
        autoplay: config.autoplay || true,
        // If i set it this way, it works with the correct value as not being evaluated, but then i have no fallback value
        //autoplay: config.autoplay
    });
2 Answers
$(el).slick({
  autoplay: config.autoplay != null ? config.autoplay : true
});

This will check if the value is neither null nor undefined.

Since the autoplay is false, false || true will always result in true.

You can also use this if you just want a default value(s).

let config
const defaults = {autoplay:true}

config = {}
console.log({...defaults,...config})

config = {autoplay:true}
console.log({...defaults,...config})

config = {autoplay:false}
console.log({...defaults,...config})

//inlined
config = {}
console.log({autoplay:"default",...config})

//multiple
config = {arg2:"replaced",arg10:"extended"}
console.log({arg1:1, arg2:2, arg3:3,...config})

Related