Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Conditions

Conditions let a program choose which code to run. Without them a program would always do the same thing regardless of the data: show a discount to everyone or let anyone into the site without a password.

if

The code in curly braces after if runs only when the condition in parentheses is true. Code in curly braces is called a block:

const age = 20;
 
if (age >= 18) {
  console.log('Access granted'); // Access granted
}

If the condition is false, the block is skipped and the program moves on. Code inside a block is indented by two spaces — that shows it belongs to the condition.

else

The else block runs when the condition is false. Exactly one of the two blocks always runs:

const age = 15;
 
if (age >= 18) {
  console.log('Access granted');
} else {
  console.log('Access denied'); // Access denied
}

else if

When there are more than two options, add else if between if and else. Conditions are checked from top to bottom, and the first matching block runs — the rest are skipped:

const score = 75;
 
if (score >= 90) {
  console.log('Excellent');
} else if (score >= 70) {
  console.log('Good'); // Good
} else {
  console.log('Needs work');
}

Order matters: if the >= 70 check came first, a score of 95 would also get "Good".

What counts as true

A condition can use any value, not just a comparison. The values false, 0, the empty string, null, undefined and NaN are falsy. Everything else is truthy:

const name = '';
 
if (name) {
  console.log(`Hello, ${name}!`);
} else {
  console.log('No name given'); // No name given
}

This is a convenient way to check that a string is not empty or that a value is set at all.

The ternary operator

The ternary operator is a short form of if-else for picking one of two values. First comes the condition, after ? the value for true, after : the value for false:

const age = 15;
const group = age >= 18 ? 'adult' : 'child';
 
console.log(group); // child

It suits simple cases, such as choosing a word to print. Leave complex logic to a regular if — it is easier to read.

Common mistake

A single = in a condition is assignment, not comparison. Such a condition does not check the value — it changes it, and the block runs almost always:

let role = 'guest';
 
if (role = 'admin') {
  console.log('Welcome to the dashboard'); // Welcome to the dashboard
}

For comparison, always write three signs: role === 'admin'.

Thanks for reading!

Donate to the site — we work hard for you.