admin管理员组文章数量:1134241
I have some code with a lot of if/else statements similar to this:
var name = "true";
if (name == "true") {
var hasName = 'Y';
} else if (name == "false") {
var hasName = 'N';
};
But is there a way to make these statements shorter? Something like ? "true" : "false"
...
I have some code with a lot of if/else statements similar to this:
var name = "true";
if (name == "true") {
var hasName = 'Y';
} else if (name == "false") {
var hasName = 'N';
};
But is there a way to make these statements shorter? Something like ? "true" : "false"
...
8 Answers
Reset to default 166Using the ternary :?
operator [spec].
var hasName = (name === 'true') ? 'Y' :'N';
The ternary operator lets us write shorthand if..else
statements exactly like you want.
It looks like:
(name === 'true')
- our condition
?
- the ternary operator itself
'Y'
- the result if the condition evaluates to true
'N'
- the result if the condition evaluates to false
So in short (question)?(result if true):(result is false)
, as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.
You can use an object as a map:
var hasName = ({
"true" : "Y",
"false" : "N"
})[name];
This also scales nicely for many options
var hasName = ({
"true" : "Y",
"false" : "N",
"fileNotFound" : "O"
})[name];
(Bonus point for people getting the reference)
Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.
?: Operator
If you want to shorten if/else
you can use ?:
operator as:
condition ? action-on-true : action-on-false(else)
For instance:
let gender = isMale ? 'Male' : 'Female';
In this case else
part is mandatory.
I see this kinda short hand format use for null
/undefined
checking like:
const avatarName = user.firstname ? user.firstname : user.lastname;
However in this case you can simply use:
const avatarName = user.firstname ?? user.lastname;
or
const avatarName = user.firstname || user.lastname;
To see the difference check this out
&& Operator
In another case, if you have only if
condition you can use &&
operator as:
condition && action;
For instance:
!this.settings && (this.settings = new TableSettings());
FYI: You have to try to avoid using if-else or at least decrease using it and try to replace it with Polymorphism or Inheritance. Go for being Anti-If guy.
Try this
hasName = name ? 'Y' : 'N';
Try like
var hasName = 'N';
if (name == "true") {
hasName = 'Y';
}
Or even try with ternary operator
like
var hasName = (name == "true") ? "Y" : "N" ;
Even simply you can try like
var hasName = (name) ? "Y" : "N" ;
Since name has either Yes
or No
but iam not sure with it.
Most answers here will work fine if you have just two
conditions in your if-else. For more which is I guess what you want, you'll be using arrays.
Every names corresponding element in names
array you'll have an element in the hasNames
array with the exact same index. Then it's a matter of these four lines.
names = "true";
var names = ["true","false","1","2"];
var hasNames = ["Y","N","true","false"];
var intIndex = names.indexOf(name);
hasName = hasNames[intIndex ];
This method could also be implemented using Objects and properties as illustrated by Benjamin.
Try this method;
Shorthand method:
let variable1 = '';
let variable2 = variable1 || 'new'
console.log(variable2); // new
Longhand method:
let variable1 = 'ya';
let varibale2;
if (variable1 !== null || variable1 !== undefined || variable1 !== '')
variable2 = variable1;
console.log(variable2); // ya
Try This
var name = "true";
var hashname;
name
? hashname = "Y"
: !name
? hashname = "N"
: ""
console.log(hashname)
本文标签: javascriptShorthand for ifelse statementStack Overflow
版权声明:本文标题:javascript - Shorthand for if-else statement - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736838035a1954976.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
true
? – Rich Bradshaw Commented Aug 16, 2013 at 8:48