简体   繁体   中英

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

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).

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM