Learn JavaScript
  • Introduction
  • Basics
    • Comments
    • Variables
    • Types
    • Equality
  • Numbers
    • Math
    • Basic Operators
    • Advanced Operators
  • Strings
    • Creation
    • Replace
    • Length
    • Concatenation
  • Conditional Logic
    • If
    • Else
    • Switch
    • Comparators
    • Concatenate
  • Arrays
    • Unshift
    • Map
    • Spread
    • Shift
    • Pop
    • Join
    • Length
    • Push
    • For Each
    • Sort
    • Indices
  • Loops
    • For
    • While
    • Do...While
  • Functions
    • Higher Order Functions
  • Objects
    • Properties
    • Mutable
    • Reference
    • Prototype
    • Delete
    • Enumeration
    • Global footprint
  • Linked List
    • Add
    • Pop
    • Prepend
    • Shift
  • Browser Object Model (BOM)
    • Window
    • Popup
    • Screen
    • Navigator
    • Cookies
    • History
    • Location
  • Date and Time
  • JSON
  • Error Handling
    • try...catch...finally
  • Events
  • Regular Expression
  • Modules
  • Debugging
  • Classes
    • Static
    • Inheritance
    • Access Modifiers
  • Promise, async/await
    • Async/Await
  • Miscellaneous
    • Hoisting
    • Currying
    • Polyfills and Transpilers
  • Exercises
    • Console
    • Multiplication
    • User Input Variables
    • Constants
    • Concatenation
    • Functions
    • Conditional Statements
    • Objects
    • FizzBuzz Problem
    • Get the Titles!
Powered by GitBook
On this page

Was this helpful?

  1. Conditional Logic

If

The easiest condition is an if statement and its syntax is if(condition){ do this … }. The condition has to be true for the code inside the curly braces to be executed. You can for example test a string and set the value of another string dependent on its value:

let country = "France";
let weather;
let food;
let currency;

if (country === "England") {
  weather = "horrible";
  food = "filling";
  currency = "pound sterling";
}

if (country === "France") {
  weather = "nice";
  food = "stunning, but hardly ever vegetarian";
  currency = "funny, small and colourful";
}

if (country === "Germany") {
  weather = "average";
  food = "wurst thing ever";
  currency = "funny, small and colourful";
}

let message =
  "this is " +
  country +
  ", the weather is " +
  weather +
  ", the food is " +
  food +
  " and the " +
  "currency is " +
  currency;
  
console.log(message);
// 'this is France, the weather is nice, the food is stunning, but hardly ever vegetarian and the currency is funny, small and colourful'

Conditions can also be nested.

PreviousConditional LogicNextElse

Last updated 2 years ago

Was this helpful?