At the core of every interactive web application and dynamic website lies two essential pillars in JavaScript: variables, which represent the memory of the program, and conditional statements, which form its decision-making brain. Mastering these concepts is not just a first step, but the foundation upon which all advanced programming skills are built.
In this comprehensive guide, we will explore how to give our programs memory to store information, and how to teach them to make smart decisions based on that information, with a focus on the best modern practices in JavaScript.
Variables are containers used to store data that our program needs, such as a user's name, the result of a calculation, or the login status. In modern JavaScript, there are three ways to declare variables, but the focus is on two.
let
and const
: The Modern Gold Standardlet: Used to declare a variable whose value is expected to change later. It’s like a whiteboard where you can write, erase, and modify its contents.
let userScore = 0; // Starts at zero
userScore = userScore + 10; // Now it's 10
const: Used to define a constant, i.e., a variable whose value will never be reassigned after it is given an initial value. Ideal for values that should not change, such as a birth year or an API key.
const birthYear = 1995;
// birthYear = 1996; // This would throw an error, which is a good thing!
And what about var
? var
was the old way to declare variables. It’s advised to avoid it in modern projects because it can cause unexpected issues related to variable scope, which let
and const
address effectively.
These variables can store data types like strings (String
), numbers (Number
), and boolean values (Boolean
).
Once our program has memory, we now need to give it the ability to make decisions in the code. This is where conditional statements come in.
if...else
: The Basic Decision-Making ToolThis is the simplest and most common tool for making decisions. "If this condition is true, do this. Otherwise, do something else."
let userAge = 22;
if (userAge >= 18) {
console.log("Welcome! You are eligible to enter.");
} else {
console.log("Sorry, you must be 18 or older to enter.");
}
else if
: For Multi-Level DecisionsWhen you have more than two conditions, you can use else if
to create a chain of checks.
let grade = 85;
if (grade >= 90) {
console.log("Excellent (A)");
} else if (grade >= 80) {
console.log("Very Good (B)");
} else if (grade >= 70) {
console.log("Good (C)");
} else {
console.log("Needs Improvement (F)");
// Will print: Very Good (B)
To write compound conditions, we use logical operators:
&&
(AND): Both conditions must be true.||
(OR): Only one of the conditions must be true.!
(NOT): Inverts the boolean value (turns true
into false
and vice versa).let isLoggedIn = true;
let hasAdminRights = false;
// The user can access if they are logged in and have admin rights
if (isLoggedIn && hasAdminRights) {
console.log("Admin dashboard access granted.");
} else {
console.log("Access denied.");
}
Data often comes from users in the form of strings, even when it's numeric. It needs to be converted before it can be used in calculations or comparisons.
let ageInput = "25"; // A string value from an input field
let ageNumber = parseInt(ageInput); // Convert the string to a number
if (ageNumber > 21) {
console.log("Can purchase alcohol.");
}
Pro Tip: The Ternary Operator is a shorthand and elegant way to write simple if...else
statements in one line.
let userType = userAge >= 18 ? "Adult" : "Minor";
console.log(userType); // A more professional approach
While variables and conditional statements may seem like basic concepts, they are in fact the DNA of every JavaScript program. By gaining a deep understanding of how to store information using let
and const
, and how to create logical pathways with if
and its derivatives, you have laid the foundation that will enable you to build complex, interactive, and smart applications. Always remember: every great code is essentially a sequence of data and decisions made intelligently.