pedalpete
pedalpete

Reputation: 21566

Set a variable if undefined in JavaScript

I know that I can test for a JavaScript variable and then define it if it is undefined, but is there not some way of saying

var setVariable = localStorage.getItem('value') || 0;

seems like a much clearer way, and I'm pretty sure I've seen this in other languages.

Upvotes: 275

Views: 404785

Answers (13)

Gibolt
Gibolt

Reputation: 47297

Logical nullish assignment, ES2021+ solution

New operators are currently being added to the browsers, ??=, ||=, and &&=. This post will focus on ??=.

This checks if left side is undefined or null, short-circuiting if already defined. If not, the right-side is assigned to the left-side variable.

Comparing Methods

// Using ??=
name ??= "Dave"

// Previously, ES2020
name = name ?? "Dave"

// or
if (typeof name === "undefined" || name === null) {
    name = true
}

// Before that (not equivalent, but commonly used)
name = name || "Dave" // Now: name ||= "Dave"

Basic Examples

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

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

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" }

??= Browser Support Nov 2024 - 95%

??= Mozilla Documentation

||= Mozilla Documentation

&&= Mozilla Documentation

Upvotes: 180

T S
T S

Reputation: 1905

It seems to me, that for current javascript implementations,

var [result='default']=[possiblyUndefinedValue]

is a nice way to do this (using object deconstruction).

As noted on mdn, in this case the default value really is only used if the value is undefined, not if it is merely falsy or null.

Upvotes: 0

SuperNova
SuperNova

Reputation: 27486

You can use any of below ways.

let x;
let y = 4;
x || (x = y)

in ES12 or after

let x;
let y = 4;
x ||= y;

Upvotes: 3

wentjun
wentjun

Reputation: 42596

ES2020 Answer

With the Nullish Coalescing Operator, you can set a default value if value is null or undefined.

const setVariable = localStorage.getItem('value') ?? 0;

However, you should be aware that the nullish coalescing operator does not return the default value for other types of falsy value such as 0 and ''.

However, do take note of the browser support. You may need to use a JavaScript compiler like Babel to convert it into something more backward compatible. If you are using Node.js, it has been supported since version 14.

Upvotes: 31

tarkh
tarkh

Reputation: 2559

In our days you actually can do your approach with JS:

// Your variable is null
// or '', 0, false, undefined
let x = null;

// Set default value
x = x || 'default value';

console.log(x); // default value

So your example WILL work:

const setVariable = localStorage.getItem('value') || 0;

Upvotes: 7

Damian Green
Damian Green

Reputation: 7535

If you're a FP (functional programming) fan, Ramda has a neat helper function for this called defaultTo :

usage:

const result = defaultTo(30)(value)

It's more useful when dealing with undefined boolean values:

const result2 = defaultTo(false)(dashboard.someValue)

Upvotes: 2

Alnitak
Alnitak

Reputation: 340055

Yes, it can do that, but strictly speaking that will assign the default value if the retrieved value is falsey, as opposed to truly undefined. It would therefore not only match undefined but also null, false, 0, NaN, "" (but not "0").

If you want to set to default only if the variable is strictly undefined then the safest way is to write:

var x = (typeof x === 'undefined') ? your_default_value : x;

On newer browsers it's actually safe to write:

var x = (x === undefined) ? your_default_value : x;

but be aware that it is possible to subvert this on older browsers where it was permitted to declare a variable named undefined that has a defined value, causing the test to fail.

Upvotes: 382

Tsz Lam
Tsz Lam

Reputation: 71

Works even if the default value is a boolean value:

var setVariable = ( (b = 0) => b )( localStorage.getItem('value') );

Upvotes: 0

Sterling Bourne
Sterling Bourne

Reputation: 3372

The 2018 ES6 answer is:

return Object.is(x, undefined) ? y : x;

If variable x is undefined, return variable y... otherwise if variable x is defined, return variable x.

Upvotes: 31

Mcestone
Mcestone

Reputation: 864

I needed to "set a variable if undefined" in several places. I created a function using @Alnitak answer. Hopefully it helps someone.

function setDefaultVal(value, defaultValue){
   return (value === undefined) ? defaultValue : value;
}  

Usage:

hasPoints = setDefaultVal(this.hasPoints, true);

Upvotes: 13

Bruno
Bruno

Reputation: 978

It seems more logical to check typeof instead of undefined? I assume you expect a number as you set the var to 0 when undefined:

var getVariable = localStorage.getItem('value');
var setVariable = (typeof getVariable == 'number') ? getVariable : 0;

In this case if getVariable is not a number (string, object, whatever), setVariable is set to 0

Upvotes: 6

Mark Seefeldt
Mark Seefeldt

Reputation: 592

Ran into this scenario today as well where I didn't want zero to be overwritten for several values. We have a file with some common utility methods for scenarios like this. Here's what I added to handle the scenario and be flexible.

function getIfNotSet(value, newValue, overwriteNull, overwriteZero) {
    if (typeof (value) === 'undefined') {
        return newValue;
    } else if (value === null && overwriteNull === true) {
        return newValue;
    } else if (value === 0 && overwriteZero === true) {
        return newValue;
    } else {
        return value;
    }
}

It can then be called with the last two parameters being optional if I want to only set for undefined values or also overwrite null or 0 values. Here's an example of a call to it that will set the ID to -1 if the ID is undefined or null, but wont overwrite a 0 value.

data.ID = Util.getIfNotSet(data.ID, -1, true);

Upvotes: 1

Zikes
Zikes

Reputation: 5886

var setVariable = (typeof localStorage.getItem('value') !== 'undefined' && localStorage.getItem('value')) || 0;

Upvotes: 1

Related Questions