Skip to main content

JavaScript Statements

Introduction

JavaScript statements are instructions that tell the browser what actions to perform. They are the building blocks of any JavaScript program, similar to how sentences are the building blocks of a paragraph. Each statement performs a specific task, such as declaring a variable, assigning a value, or controlling program flow.

In this tutorial, we'll explore different types of JavaScript statements, how they work, and how to use them effectively in your code.

What is a JavaScript Statement?

A JavaScript statement is a command to the browser to do something. Every JavaScript statement typically ends with a semicolon (;), although JavaScript has automatic semicolon insertion, so they're not always required (but are considered a best practice).

javascript
// This is a single JavaScript statement
let greeting = "Hello, World!";

Types of JavaScript Statements

1. Declaration Statements

Declaration statements create variables or functions.

javascript
// Variable declarations
let name = "Alex";
const age = 25;
var city = "New York";

// Function declaration
function sayHello() {
console.log("Hello!");
}

2. Expression Statements

Expression statements evaluate to a value and can be combined with other expressions.

javascript
// Basic expression statements
x = 5;
y = x + 10;
z = x * y;

// Function call expressions
console.log("This is an expression statement");
Math.random();

3. Conditional Statements

Conditional statements execute different actions based on different conditions.

If...Else Statement

javascript
let hour = new Date().getHours();

if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}

Switch Statement

javascript
let day = new Date().getDay();
let dayName;

switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Unknown";
}

console.log(`Today is ${dayName}`);

4. Loop Statements

Loop statements allow you to execute a block of code multiple times.

For Loop

javascript
// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5

While Loop

javascript
// Print numbers 1 to 5 using a while loop
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Output is the same as the for loop above

Do...While Loop

javascript
// A do...while loop will always execute at least once
let j = 1;
do {
console.log(j);
j++;
} while (j <= 5);
// Output is the same as the previous loops

For...Of Loop (for iterables)

javascript
// Loop through elements of an array
const fruits = ["Apple", "Banana", "Orange"];
for (const fruit of fruits) {
console.log(fruit);
}
// Output:
// Apple
// Banana
// Orange

For...In Loop (for object properties)

javascript
// Loop through properties of an object
const person = {
name: "John",
age: 30,
job: "Developer"
};

for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: John
// age: 30
// job: Developer

5. Jump Statements

Jump statements transfer control to another part of the program.

Break Statement

javascript
// Exit a loop early when a condition is met
for (let i = 1; i <= 10; i++) {
if (i === 6) {
break; // Exit the loop when i equals 6
}
console.log(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5

Continue Statement

javascript
// Skip an iteration when a condition is met
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
// Output:
// 1
// 3
// 5
// 7
// 9

Return Statement

javascript
// Function with a return statement
function multiply(a, b) {
return a * b; // Returns the product and exits the function
// Any code after return is not executed
}

console.log(multiply(5, 3)); // Output: 15

6. Error Handling Statements

Error handling statements allow you to gracefully handle errors in your code.

javascript
try {
// Code that might throw an error
let x = y + 5; // y is not defined
} catch (error) {
// Code to handle the error
console.log("An error occurred:", error.message);
} finally {
// Code that runs regardless of whether an error occurred
console.log("This always executes");
}
// Output:
// An error occurred: y is not defined
// This always executes

Statement Blocks

Multiple statements can be grouped into blocks using curly braces {}. This is commonly used with conditional statements and loops.

javascript
// A statement block with multiple statements
if (true) {
let message = "This is inside a block";
console.log(message);
console.log("Still inside the block");
}

Real-world Example: Form Validation

Here's a practical example that combines different types of statements to create a simple form validation function:

javascript
function validateForm(username, password) {
// Declaration statements
let errors = [];
const minPasswordLength = 8;

// Conditional statements
if (username.length === 0) {
errors.push("Username cannot be empty");
}

if (password.length < minPasswordLength) {
errors.push(`Password must be at least ${minPasswordLength} characters long`);
}

// Check if password contains at least one number
let hasNumber = false;

// Loop statement
for (let i = 0; i < password.length; i++) {
if (!isNaN(parseInt(password[i]))) {
hasNumber = true;
break; // Jump statement
}
}

if (!hasNumber) {
errors.push("Password must contain at least one number");
}

// Return statement with conditional
if (errors.length > 0) {
return {
valid: false,
errors: errors
};
} else {
return {
valid: true
};
}
}

// Test the validation
const result = validateForm("john", "password");
console.log(result);
// Output: { valid: false, errors: [ 'Password must contain at least one number' ] }

const result2 = validateForm("john", "password123");
console.log(result2);
// Output: { valid: true }

Best Practices for JavaScript Statements

  1. End statements with semicolons: While JavaScript has automatic semicolon insertion, it's considered good practice to explicitly add semicolons.

  2. Use consistent indentation: Indent your code to make it more readable, especially in statement blocks.

  3. Use meaningful variable names: This makes your code self-documenting and easier to understand.

  4. Keep statements focused: Each statement should perform a specific, well-defined task.

  5. Comment complex logic: Add comments to explain the purpose of complex statements or blocks.

Summary

JavaScript statements are the fundamental building blocks of any JavaScript program. They come in various types, including:

  • Declaration statements for creating variables and functions
  • Expression statements for evaluations and assignments
  • Conditional statements for decision-making
  • Loop statements for repetitive tasks
  • Jump statements for control flow
  • Error handling statements for graceful error management

Understanding how to use these statements effectively will help you write cleaner, more efficient JavaScript code.

Exercises

  1. Write a function that uses a loop statement to find the sum of all numbers from 1 to n.
  2. Create a switch statement that converts numerical grades to letter grades (A, B, C, D, F).
  3. Write a function that validates a phone number using conditional statements.
  4. Create a function that uses error handling to safely parse JSON data.
  5. Write a nested loop that creates a simple multiplication table.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)