Shorthand for if-else statement
Using 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.
Try this
hasName = name ? 'Y' : 'N';
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.