javascript - Shorthand for if-else statement -
i have code lot of if/else statements similar this:
var name = "true"; if (name == "true") { var hasname = 'y'; } else if (name == "false") { var hasname = 'n'; }; but there way make these statements shorter? ? "true" : "false" ...
using ternary :? operator [spec].
var hasname = (name === 'true') ? 'y' :'n'; the ternary operator lets write shorthand if..else statements want.
it looks like:
(name === 'true') - our condition
? - ternary operator itself
'y' - result if condition evaluates true
'n' - result if condition evaluates false
so in short (question)?(result if true):(result false) , can see - returns value of expression can assign variable in example above.
Comments
Post a Comment