Conditional operator (ternary operator) in JavaScript (or TypeScript)

0 0
Read Time:43 Second

Let’s imagine that we could optimize / minify if statement. What could we do?

In case we have if…else statement like:

if (condition) {
// do sth if condition is true
}
else {
// do sth else if condition isn't true
}

we can change it to ternary expression

condition ? /* do sth if condition is true */ : /* do sth if condition isn't true */;

Let’s check how it works with functions:

const actionOne = () => console.log('actionOne');
const actionTwo = () => console.log('actionTwo');


true ? actionOne() : actionTwo(); // actionOne
false ? actionOne() : actionTwo(); // actionTwo

And how to use it with more complex functions:

const multiply = (a) => a*a; 
const add = (a) => a+a;
 
const variable = 4;

let newVar; 

newVar = true ? multiply(variable) : add(variable);

console.log(newVar) // 16

newVar = false ? multiply(variable) : add(variable);

console.log(newVar) // 8

As you can see ternary can be useful when you want to make inline if operations.

About Post Author

Piotr Sikora

Piotr Sikora Founder of WolePapierowe.com Co-founder of Liderazgo.pl MeetJS Kielce Committee member. JavaScript and Python enthusiast.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

© UiCore 2024. All Rights Reserved.