If-only Ternary Operation

I have a suggestion for ternary operations for ease of use and cleaner code. The main premise is as follows:

There are plenty of situations where people implement a conditional statement without including an else clause such as :

var x = "World";
var y = "";
if(typeof x === "string")
y = Hello ${x});

This is prevalent in much coding, and sometimes people choose to use ternary operators to go through that process but end up either not being able to do so, or end up having longer than necessary resolutions to their code.

What I SHOULD be able to do INSTEAD of needing the bracketing is this:

var x = "World";
var y = typeof x === "string" ? Hello ${x};

with it yet being decided as to whether or not the return should be the default value of what was the original assignment, null, or both depending on whether or not there was an original assignment. As you can see above, the assignment is much cleaner and in one line versus multiple, and despite the fact that you could have a return of null, the simplicity of simply having it AS a default isn't the worst option to help clean things up and then only offer an alternative solution as needed/defined.

there's a part in your original code that you forgot to include in the version with the conditional operator:

That's the else value, and to make your code both correct and syntactically valid you'd write

var x = "World";
var y = typeof x === "string" ? `Hello ${x}` : "";

The ": """ is not "longer than necessary", it is absolutely required for the code to work. Omitting it would not work, even if that was valid syntax (as you suggest) the variable y would end up as null or undefined, but not as the empty string as desired.

1 Like
foo = foo ? foo : bar;
foo := bar;
foo = bar ? bar : foo;
foo ?= bar;

wherein the condition could be specified more explicitly, e.g. as (x != null) or something more useful.

@Crissov that looks like a different use case? And I think it is already covered by the nullish coalescing operator proposal:

foo = foo ?? bar;

Only thing that's missing in there is a shorthand assignment operator

foo ??= bar;
1 Like

The ??= operator is part of the Logical Assignment operators proposal, which reached state 3 this week.

1 Like

I'm not necessarily arguing for a null coalescer because I'm not wanting to merely check as to whether a value is null when it comes to assignment. It'll be nice to have and C# has had this for a while now with "??". I am wanting to base it off of true and false conditional statements with the else clause (which after ":" essentially is) not being necessary and simply defaulting to null or some other value. I prefer the null value since as a default check it would allow for better cohesion and less need to check for other values.