Learn JavaScript
  • Introduction
  • Basics
    • Comments
    • Variables
    • Types
    • Equality
  • Numbers
    • Creation
    • Basic Operators
    • Advanced Operators
  • Strings
    • Creation
    • Concatenation
    • Length
  • Conditional Logic
    • If
    • Else
    • Comparators
    • Concatenate
  • Arrays
    • Indices
    • Length
  • Loops
    • For
    • While
    • Do...While
  • Functions
    • Declare
    • Higher order
  • Objects
    • Creation
    • Properties
    • Mutable
    • Reference
    • Prototype
    • Delete
    • Enumeration
    • Global footprint
Powered by GitBook
On this page
  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:

var country = "France";
var weather;
var food;
var 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";
}

var message =
  "this is " +
  country +
  ", the weather is " +
  weather +
  ", the food is " +
  food +
  " and the " +
  "currency is " +
  currency;

Note: Conditions can also be nested.

PreviousConditional LogicNextElse

Last updated 4 years ago