最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Shorthand for "if typeof undefined" in Javascript? - Stack Overflow

programmeradmin7浏览0评论

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

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] 
}
Share Improve this question edited Jan 29, 2016 at 11:17 Shashank Agrawal 25.8k11 gold badges96 silver badges125 bronze badges asked Jan 29, 2016 at 11:12 Badr HariBadr Hari 8,43421 gold badges71 silver badges101 bronze badges 1
  • As noticed by Tushar (in a deleted answer), you probably inverted both branchs, it should be "===", not "!==". – Denys Séguret Commented Jan 29, 2016 at 11:56
Add a ment  | 

3 Answers 3

Reset to default 3

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.

发布评论

评论列表(0)

  1. 暂无评论