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

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -