Fergal
Fergal

Reputation: 2474

Javascript shortest possible check for undefined, if it is assign a default value

If passing params or an object full of properties into function, it's useful to check for undefined params and give default values to those that are undefined.

Without using a library function like jQuery extent, what would be the shortest about of code to do this kind of assigning defaults?

Here is the shortest I can think of:

var test;
var output = (typeof test != "undefined") ? test : "Default";

Before someone suggests:

var test;
var output = test || "Default";

That will not work with false, 0 or ""

Upvotes: 3

Views: 10253

Answers (5)

Papooch
Papooch

Reputation: 1645

In ES2021 this is now possible using the Nullish coalescing operator.

Usage:

const str = null ?? 'default string';
console.log(str);
// expected output: "default string"

const num = 0 ?? 42;
console.log(num);
// expected output: 0

const bool = false ?? true;
console.log(bool)
// expected output: false

Upvotes: 4

Tarkin
Tarkin

Reputation: 333

https://github.com/jed/140bytes/wiki/Byte-saving-techniques is your friend:

var output = test===[]._ ? "Default" : test;

Shorter:

var output=test===[]._?"Default":test;

No spaces needed between operators and tokens.

Upvotes: 1

Aels
Aels

Reputation: 11

Ok, so if the "undefined" it the longest value of types, the shortest way to check object presence is

!(typeof console).charAt(8)

where "console" is our examinated object. .charAt(8) will return empty string "" if object is anything else than "undefined", that equals false It's a safe way for old IE supporting. But if u need only modern browsers support, you can use just

if(!(typeof console)[8]) { doWork(); }

to check that object is defined.

Upvotes: 1

War10ck
War10ck

Reputation: 12508

You could try this:

var output = if(test === undefined) ? test: "Default";

If you know that you will never pass 0, false, or "" as valid parameters you could simplify this to be:

var output = if(test) ? test : "Default";

However, this gets into the cryptic "truthy falsey" part of JavaScript. By having the === you are doing an equality check with type comparison.

Hope this helps.

Upvotes: 0

antyrat
antyrat

Reputation: 27765

Try this:

var output = test != null ? test : "Default";

I.g:

null == undefined // true
null == null // true
null == 0 // false
null == "" //false
null == false // false

Upvotes: 5

Related Questions