admin管理员组文章数量:1391929
I think below code can be simpleer somehow. Can this code be optimized?
let name = app.short_name;
if (name === undefined) {
name = app.name;
if (name === undefined) {
name = 'Untitled';
}
}
I think below code can be simpleer somehow. Can this code be optimized?
let name = app.short_name;
if (name === undefined) {
name = app.name;
if (name === undefined) {
name = 'Untitled';
}
}
Share
Improve this question
edited Jun 14, 2017 at 7:14
RNA
asked Jun 14, 2017 at 6:47
RNARNA
1,0913 gold badges20 silver badges43 bronze badges
1
-
5
yes,
name
could ben
:plet name = app.short_name || app.name || 'Untitled';
– Jaromanda X Commented Jun 14, 2017 at 6:48
3 Answers
Reset to default 9Use Logical OR
(||
) operator
let name = app.short_name || app.name || 'Untitled';
You could use a default chain with logical OR ||
in a short-circuit evaluation.
let name = app.short_name || app.name || 'Untitled';
But I suggest to use a variable name different of name
, because it is usually a property of window
Javascript will assign what it considers true
. If you concat with ||
(OR
) then each value is checked for true until a true value is found and is assigned.
There are a number of values that bee false
for example:
undefined
0
null
''
(empty String)NaN
This is why you could write
let name = app.short_name || app.name || 'Untitled';
because if app.short_name
has a value it will be true
rather than false
and it is assigned. But if it is undefined
it will be considered false
and app.name
will be checked if it is true
. If it is undefined
it will be again considered false
and so finally 'Untitled'
is considered and deemed true
and assigned to name
. Might want to look at this link.
本文标签: javascriptcan this code (nested IF statement) be shorterStack Overflow
版权声明:本文标题:javascript, can this code (nested IF statement) be shorter? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744715962a2621403.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论