Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inline if statement

Tags:

javascript

I had a bit of a weird result in the javascript console. I was trying to look for an alternative (more readable) version of the ternary operator, just for fun. Typing:

{ if(3===4) {5} else {6} }

Evaluates in my console to 6, but for some reason, I can not assign it to a variable, so running:

let a = { if(3===4) {5} else {6} }

Does not let me store it to the variable directly. So my main question is, if this block is returning something, why can't I assign it?

like image 558
user2662833 Avatar asked Feb 13 '26 04:02

user2662833


1 Answers

The fact that blocks (and other statements) return values isn't accessible to your code. Consoles can see the result, and it exists at a language specification level, but not in your code.

Your options are the conditional operator¹ (which is quite readable when you're used to it, but you've said you're looking for alternatives to it) or the if/else assigning to a in both parts:

let a;
if (3 === 4) {
    a = 5;
} else {
    a = 6;
}

Or you could use an inline function (IIFE):

let a = (() => { if (3 === 4} return 5 else return 6; })();

There is also a proposal being floated for "do expressions", which would look like this:

// Currently a proposal, not implemented in engines yet
let a = do { if (3 === 4) 5; else 6; };

That proposal is at Stage 1 of the process, so it may or may not progress, and if it progresses it could change markedly before doing so.


¹ Although you see "the ternary operator" a lot, the proper name is the conditional operator. It is a ternary operator (an operator accepting three operands), and currently JavaScript's only ternary operator, but that could change someday. :-)

like image 159
T.J. Crowder Avatar answered Feb 15 '26 18:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!