PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. JavaScript Basics
  2. JavaScript: Conditionals
  • JavaScript

  • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

  • React Framework

  • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

  • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

  • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

  • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

  • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

  • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios

    • Lab#RE02-1: Router & Hooks

    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management

    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS

    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front

    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request

    • Lab#RE07-1: traffic lights simulation

  • React JS readings
    • ReactJS Resources

On this page

  • 1 Overview
  • 2 The “if” Statement
    • 2.1 Multiple Statements
  • 3 Boolean Conversion
    • 3.1 Examples
  • 4 The “else” Clause
  • 5 Several Conditions: “else if”
  • 6 Conditional (Ternary) Operator ‘?’
    • 6.1 Syntax
    • 6.2 Example
    • 6.3 Multiple ‘?’
  • 7 The “switch” Statement
    • 7.1 Syntax
    • 7.2 How it Works
    • 7.3 Example
    • 7.4 The Importance of break
    • 7.5 Grouping Cases
    • 7.6 Type Matters
  • 8 Comparison: if vs switch
    • 8.1 Use if/else when:
    • 8.2 Use switch when:
  • 9 Examples
    • 9.1 Example 1: Grade Calculator
    • 9.2 Example 2: Day of Week
    • 9.3 Example 3: Ternary Operator
    • 9.4 Example 4: Login System
    • 9.5 Example 5: Calculator with Switch
    • 9.6 Example 6: Season Checker
  • 10 Summary
  • Edit this page
  • View source
  • Report an issue
  1. JavaScript Basics
  2. JavaScript: Conditionals

JavaScript: Conditionals

JavaScript Conditional Statements

javascript
conditionals
control-flow
JavaScript Conditionals - if/else, Ternary Operator, and Switch Statements
Author

Pedro GeoGIS

Published

Monday, January 13, 2025

Modified

Monday, October 13, 2025

1 Overview

📘 Conditionals

Conditional statements allow you to execute different code blocks based on different conditions. JavaScript provides several ways to implement conditional logic: the if statement for basic conditions, else if for multiple conditions, the ternary operator ? for concise conditional assignments, and the switch statement for handling multiple specific values. These control structures are fundamental for creating dynamic and responsive programs.


2 The “if” Statement

The if statement evaluates a condition in parentheses and, if the result is true, executes a block of code.

let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year == 2015) {
  alert('You are right!');
}

2.1 Multiple Statements

If you want to execute more than one statement, wrap your code block inside curly braces:

if (year == 2015) {
  alert("That's correct!");
  alert("You're so smart!");
}

Tip

Best Practice: Always use curly braces {} even if there is only one statement. This improves readability and prevents errors.

// Good
if (condition) {
  doSomething();
}

// Avoid
if (condition) doSomething();

3 Boolean Conversion

The if (...) statement evaluates the expression in its parentheses and converts the result to a boolean.

Falsy values (become false): - 0 - "" (empty string) - null - undefined - NaN

Truthy values (become true): - All other values


3.1 Examples

if (0) {
  // This code never executes (0 is falsy)
}

if (1) {
  // This code always executes (1 is truthy)
}

if ("hello") {
  // This code executes (non-empty string is truthy)
}

4 The “else” Clause

The if statement may contain an optional else block. It executes when the condition is falsy.

let year = prompt('In which year was the ECMAScript-2015 specification published?', '');

if (year == 2015) {
  alert('You guessed it right!');
} else {
  alert('How can you be so wrong?');
}

5 Several Conditions: “else if”

Sometimes we need to test several variants of a condition. The else if clause lets us do that.

let year = prompt('In which year was the ECMAScript-2015 specification published?', '');

if (year < 2015) {
  alert('Too early...');
} else if (year > 2015) {
  alert('Too late');
} else {
  alert('Exactly!');
}

There can be multiple else if blocks. The final else is optional.


6 Conditional (Ternary) Operator ‘?’

Sometimes we need to assign a variable depending on a condition. The ternary operator provides a shorter and simpler way.

6.1 Syntax

let result = condition ? value1 : value2;
  • The condition is evaluated
  • If it’s truthy, value1 is returned
  • Otherwise, value2 is returned

6.2 Example

let age = prompt('How old are you?', '');
let accessAllowed = (age > 18) ? true : false;

alert(accessAllowed);

Since the comparison itself returns true/false, we can simplify:

let accessAllowed = age > 18; // same result

6.3 Multiple ‘?’

A sequence of question mark operators can return a value that depends on more than one condition:

let age = prompt('age?', 18);

let message = (age < 3) ? 'Hi, baby!' :
  (age < 18) ? 'Hello!' :
  (age < 100) ? 'Greetings!' :
  'What an unusual age!';

alert(message);

This is equivalent to:

if (age < 3) {
  message = 'Hi, baby!';
} else if (age < 18) {
  message = 'Hello!';
} else if (age < 100) {
  message = 'Greetings!';
} else {
  message = 'What an unusual age!';
}

Warning

Use ternary operator for assignment, not replacement of if

The ternary operator is great for conditional assignments but can reduce readability when used for complex logic. Use if/else for better clarity in such cases.


7 The “switch” Statement

The switch statement can replace multiple if checks. It provides a more descriptive way to compare a value with multiple variants.

7.1 Syntax

switch(x) {
  case 'value1':  // if (x === 'value1')
    ...
    break;
  case 'value2':  // if (x === 'value2')
    ...
    break;
  default:
    ...
    break;
}

7.2 How it Works

  1. The value of x is checked for strict equality (===) with the value from the first case
  2. If equality is found, switch executes the code starting from that case until the nearest break
  3. If no case is matched, the default code is executed (if it exists)

7.3 Example

let a = 2 + 2;

switch (a) {
  case 3:
    alert('Too small');
    break;
  case 4:
    alert('Exactly!');
    break;
  case 5:
    alert('Too big');
    break;
  default:
    alert("I don't know such values");
}

7.4 The Importance of break

If there is no break, execution continues with the next case without any checks (fall-through):

let a = 2 + 2;

switch (a) {
  case 3:
    alert('Too small');
  case 4:
    alert('Exactly!');
  case 5:
    alert('Too big');
  default:
    alert("I don't know such values");
}

This will output: - “Exactly!” - “Too big” - “I don’t know such values”


7.5 Grouping Cases

Several variants of case which share the same code can be grouped:

let a = 3;

switch (a) {
  case 4:
    alert('Right!');
    break;
    
  case 3:  // grouped two cases
  case 5:
    alert('Wrong!');
    alert("Why don't you take a math class?");
    break;
    
  default:
    alert('The result is strange. Really.');
}

Now both 3 and 5 show the same message.


7.6 Type Matters

The equality check in switch is always strict (===). The values must be of the same type to match.

let arg = prompt("Enter a value?");

switch (arg) {
  case '0':
  case '1':
    alert('One or zero');
    break;
    
  case '2':
    alert('Two');
    break;
    
  case 3:
    alert('Never executes!'); // prompt returns string, not number
    break;
    
  default:
    alert('An unknown value');
}

8 Comparison: if vs switch

8.1 Use if/else when:

  • You have complex conditions
  • You need to check ranges (e.g., age > 18)
  • You have boolean logic

8.2 Use switch when:

  • You have multiple specific values to check
  • You want cleaner code for many equality checks
  • You need to group similar cases

9 Examples

9.1 Example 1: Grade Calculator

let score = prompt('Enter your score (0-100):', '');
score = Number(score);

if (score >= 90) {
  alert('Grade: A');
} else if (score >= 80) {
  alert('Grade: B');
} else if (score >= 70) {
  alert('Grade: C');
} else if (score >= 60) {
  alert('Grade: D');
} else {
  alert('Grade: F');
}

9.2 Example 2: Day of Week

let day = prompt('Enter a day number (1-7):', '');
day = Number(day);

switch (day) {
  case 1:
    alert('Monday');
    break;
  case 2:
    alert('Tuesday');
    break;
  case 3:
    alert('Wednesday');
    break;
  case 4:
    alert('Thursday');
    break;
  case 5:
    alert('Friday');
    break;
  case 6:
  case 7:
    alert('Weekend!');
    break;
  default:
    alert('Invalid day number');
}

9.3 Example 3: Ternary Operator

let age = 20;

// Simple ternary
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status); // Adult

// Nested ternary
let category = (age < 13) ? 'Child' :
               (age < 20) ? 'Teenager' :
               (age < 60) ? 'Adult' : 'Senior';
console.log(category); // Adult

9.4 Example 4: Login System

let username = prompt('Enter username:', '');
let password = prompt('Enter password:', '');

if (username === 'admin' && password === 'secret123') {
  alert('Welcome, Admin!');
} else if (username === 'admin') {
  alert('Wrong password!');
} else if (password === 'secret123') {
  alert('Wrong username!');
} else {
  alert('Invalid credentials!');
}

9.5 Example 5: Calculator with Switch

let num1 = Number(prompt('Enter first number:', ''));
let operator = prompt('Enter operator (+, -, *, /):', '');
let num2 = Number(prompt('Enter second number:', ''));

let result;

switch (operator) {
  case '+':
    result = num1 + num2;
    break;
  case '-':
    result = num1 - num2;
    break;
  case '*':
    result = num1 * num2;
    break;
  case '/':
    if (num2 !== 0) {
      result = num1 / num2;
    } else {
      alert('Cannot divide by zero!');
      result = 'Error';
    }
    break;
  default:
    alert('Invalid operator!');
    result = 'Error';
}

if (result !== 'Error') {
  alert(`Result: ${num1} ${operator} ${num2} = ${result}`);
}

9.6 Example 6: Season Checker

let month = prompt('Enter month (1-12):', '');
month = Number(month);

switch (month) {
  case 12:
  case 1:
  case 2:
    alert('Winter');
    break;
  case 3:
  case 4:
  case 5:
    alert('Spring');
    break;
  case 6:
  case 7:
  case 8:
    alert('Summer');
    break;
  case 9:
  case 10:
  case 11:
    alert('Fall');
    break;
  default:
    alert('Invalid month!');
}

10 Summary

  • Use if to test conditions and execute code blocks
  • Use else to handle the opposite condition
  • Use else if to test multiple conditions sequentially
  • The ternary operator ? : is a concise way to assign values based on conditions
  • Use switch for multiple equality checks against a single value
  • switch uses strict equality (===)
  • Always use break in switch unless you want fall-through behavior
  • Group similar case statements to share code
  • Choose if/else for complex conditions, switch for multiple specific values
Back to top
JavaScript: Operators
JavaScript: Loops

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue