Replace a value if null or undefined in JavaScript

javascript

Solution

Here’s the JavaScript equivalent:

var i = null;
var j = i || 10; //j is now 10

Note that the logical operator `||` does not return a boolean value but the first value that can be converted to true.

Additionally use an array of objects instead of one single object:

var options = {
    filters: [
        {
            name: 'firstName',
            value: 'abc'
        }
    ]
};
var filter  = options.filters[0] || '';  // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || '';  // is ''

That can be accessed by index.

Problem

I have a requirement to apply the `??` C# operator to JavaScript and I don't know how. Consider this in C#: ``` int i?=null; int j=i ?? 10;//j is now 10 ``` Now I have this set up in JavaScript: ``` var options={ filters:{ firstName:'abc' } }; var filter=options.filters[0]||'';//should get 'abc' here, it doesn't happen var filter2=options.filters[1]||'';//should get empty string here, because there is only one filter ``` How do I do it correctly? Thanks. EDIT: I spotted half of the problem: I can't use the 'indexer' notation to objects (`my_object[0]`). Is there a way to bypass it? (I don't know the names of the filters properties beforehand and don't want to iterate over them).

Original source