Variables and Conditional Statements CheatSheet
Variables and Conditional Statements CheatSheet
Declaration:
Initialization:
variableName = value;
let variableName = value;
const constantName = value;
Example Codes:
// Constant variable
const PI = 3.14;
Conditional Statements
if Statement
if (condition) {
// Code block to be executed if condition is true
}
if-else Statement
if (condition) {
// Code block to be executed if condition is true
} else {
// Code block to be executed if condition is false
}
if (condition1) {
// Code block to be executed if condition1 is true
} else if (condition2) {
// Code block to be executed if condition2 is true
} else {
// Code block to be executed if none of the conditions are true
}
switch Statement
switch (expression) {
case value1:
// Code block to be executed if expression equals value1
break;
case value2:
// Code block to be executed if expression equals value2
break;
default:
// Code block to be executed if expression doesn't match any case
}
Example Codes:
// if statement
let temperature = 20;
if (temperature > 30) {
console.log("It's hot outside.");
}
//Nothing will be printed because the condition is false
// if-else statement
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
}
//Good afternoon will be printed because the condition inside the if statement is false
// switch statement
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday.");
break;
case "Tuesday":
console.log("Today is Tuesday.");
break;
default:
console.log("It's neither Monday nor Tuesday.");
}
//Today is Monday will be printed because the 1st case is true.
// Ternary operator
let isRaining = true;
let action = (isRaining) ? "Take an umbrella." : "Enjoy the weather.";
console.log(action
//Take an umbrella will be printed because the condition inside the isRaining is true
Variables
Declaration:
Variables in JavaScript can be declared using the var, let, or const keywords. var is the old way of
declaring variables, which is function-scoped. let and const are the new ways, introduced in ES6, which
are block-scoped.
Initialization:
Variables can be initialized at the time of declaration or later in the code by assigning them a value
using the assignment operator =.
Example Codes:
// Constant variable
const PI = 3.14
Conditional Statements
if Statement
The if statement allows you to execute a block of code if a specified condition is true.
if-else Statement
The if-else statement allows you to execute one block of code if the condition is true and another
block of code if the condition is false.
The if-else if-else statement allows you to check multiple conditions and execute a block of code
based on the first condition that is true.
switch Statement
The switch statement allows you to select one of many code blocks to be executed based on the value
of an expression.
The ternary operator ? : is a concise way to write an if-else statement in a single line.