Badr Hari
Badr Hari

Reputation: 8374

Shorthand for "if typeof undefined" in Javascript?

Is it possible to write this in shorter and cleaner way? I'm reading it from an XML, sometimes the URL value does not exist.

if (typeof(entry[i].getElementsByTagName("url")[0].childNodes[0]) !== "undefined") { 
    var foo = 'baar' 
} else { 
    var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] 
}

Upvotes: 5

Views: 4263

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382102

It's been years it doesn't make sense anymore to use this construct (unless you don't know whether the variable, not the value, is undefined). undefined is now read only.

Simply use

if (entry[i].getElementsByTagName("url")[0].childNodes[0] === undefined) {

In almost all cases, typeof x === "undefined" is a bad practice.

In the specific case of a DOM element, you can also simply use

if (!entry[i].getElementsByTagName("url")[0].childNodes[0]) {

because you can't have a falsy node, and of course, when the goal is to apply a default value, just use

var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar';

(be careful that this test only works when all the parts before the the last [0] are present, it's usually convenient to use querySelector or a DOM selection API like jQuery to make everything less verbose).

Upvotes: 3

Arthur Osipenko
Arthur Osipenko

Reputation: 123

var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar'

Upvotes: 2

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

You can write in this way.

var ele = entry[i].getElementsByTagName("url");
if (ele && ele[0].childNodes[0]) {
    var foo = 'baar'
} else {
    //code
}

There is no need to check it explicitly for undefined.undefined is evaluated as false.

Upvotes: 0

Related Questions