Conditional (Ternary) Operator in JavaScript Guide

By Piotr Sikora

  • development

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.

Categories

Recent Posts

About Me

Piotr Sikora - Process Automation | AI | n8n | Python | JavaScript

Piotr Sikora

Process Automation Specialist

I implement automation that saves time and money, streamlines operations, and increases the predictability of results. Specializing in process automation, AI implementation, and workflow optimization using n8n, Python, and JavaScript.

n8n Workflows

n8n workflow automation templates

Explore my workflow templates on n8n. Ready-to-use automations for blog management, data collection, and AI-powered content processing.

3Workflow Templates

• Auto-Categorize Blog Posts with AI

• Collect LinkedIn Profiles

• Export WordPress Posts for SEO

Similar Articles

Discover more related content

Unleash the Power of Autoexecuted Objects in JavaScript

Sometimes you will need to create autoexecuted object (for example in case of load/document ready events)

Pure JavaScript: Private and Public Methods Guide

Have you been creating your own classes in pure JavaScript?

Raspberry Pi node.js and how to start with programming GPIO

Start programming Raspberry Pi GPIO with Node.js. Introduction to the PixPress project on GitHub. Hardware meets JavaScript.