Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - Can you add a condition to a variable declaration?

This doesn't make sense to me, but I have a feeling I saw a code using this:

var abc = def || ghi;

My question is, is this valid? Can we add a condition to a variable declaration? I imagine the answer is no but I have this at the back of my mind that I saw something similar in code once.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This gives to abc the value of def if it isn't falsy (i.e. not false, null, undefined, 0 or an empty string), or the value of ghi if not.

This is equivalent to:

var abc;
if (def) abc = def;
else abc = ghi;

This is commonly used for options:

function myfunc (opts) {
    var mything = opts.mything || "aaa";
}

If you call myfunc({mything:"bbb"}) it uses the value you give. It uses "aaa" if you provide nothing.

In this case, in order to let the caller wholly skip the parameter, we could also have started the function with

opts = opts || {};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...