Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 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 Answer

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 || {};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...