Skip to content

JavaScript default value if undefined | Code

  • by

With the Nullish Coalescing Operator, you can set a default value if a value is null or undefined in JavaScript. However, you should be aware that the nullish coalescing operator does not return the default value for other types of falsy values such as 0 and ''.

value1 ?? value2

JavaScript default value if undefined

A simple example code sets a variable value if it’s undefined in JavaScript.

<!DOCTYPE html>
<html>
<body>
  <script>
    const foo = undefined  ?? 'default string';
    console.log(foo);

    var a;
    const baz = a ?? 100;
    console.log(baz);
    console.log(a);
  </script>
</body>
</html> 

Output:

JavaScript default value if undefined

Replace a value if null or undefined in JavaScript

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 ''

Logical nullish assignment, 2020+ solution

A new operator has been added, ??=. This is equivalent to value = value ?? defaultValue.

||= and &&= are similar, links are below.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

// Equivalent to
a = a ?? true

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Functional Example

function config(options) {
    options.duration ??= 100
    options.speed ??= 25
    return options
}

config({ duration: 555 })   // { duration: 555, speed: 25 }
config({})                  // { duration: 100, speed: 25 }
config({ duration: null })  // { duration: 100, speed: 25 }

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS undefined topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading