Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ternary operators in a function with javascript

I am new to Javascript and sort of working through the weeds on these ternary operators. I have this small code segment:

const x = MSys.inShip ? 'ship launch' : '';
if (x != '') {send_command(x);} 

While this works efficiently enough I am curious as to if it can be rewritten inside of the function call. Something like the following:

send_command(const x = MSys.inShip 
             ? 'ship launch'
             : MSys.alert("You aren't in your ship!);

This may not make sense with the current example but it's the best idea I had at the time. Basically, I like the shorthand of the ternary style for easy if/then conditionals but I don't like how it's tied to a variable which must then be called. I'm looking for a way to use that shorthand without having to tie to a variable.

Finally, the purpose of this is to see if you are in the ship and if you are, launch. If you aren't don't do anything at all or just send an alert message.

like image 748
Jason Avatar asked Feb 21 '19 22:02

Jason


People also ask

Can you use functions in ternary operator?

Nope, you can only assign values when doing ternary operations, not execute functions.

What is the purpose of ternary operator in JavaScript?

A ternary operator evaluates a condition and executes a block of code based on the condition. The ternary operator evaluates the test condition. If the condition is true , expression1 is executed. If the condition is false , expression2 is executed.

Which is better ternary operator or if-else in JavaScript?

it shows ternary is more faster than if..else statement(Nodejs console, Chrome and Edge) but in the case of Firefox, shows opposite result (Windows 10). The below code gives the 40 average milliseconds for both test. Save this answer.

Is ternary operator faster than if JavaScript?

Here are the main differences between ternary operators and if-else blocks: A ternary operator is a single statement, while an if-else is a block of code. A ternary operator is faster than an if-else block.


1 Answers

I am curious as to if it can be rewritten inside of the function call.

Yes, it can. But, if you do it there, then there is no need for a variable. You would be passing the function's argument directly inline.

Having said that, you can't pass that MSys.alert() statement as the "else" value because it will be executed in all cases. You'd have to pass a value there that the function can use as its input argument

send_command(MSys.inShip ? 'ship launch' : 'some other string');

Here's an example:

function foo(x){
 console.log(x);
}

// If a random number is even, pass "even". If not, pass "odd"
foo(Math.floor(Math.random() * 10) % 2 === 0 ? "even" : "odd");
like image 118
Scott Marcus Avatar answered Oct 01 '22 20:10

Scott Marcus