Back to JavaScript
2025-12-307 min read

Statements and declarations by category (JavaScript)

Learn Statements and declarations by category (JavaScript) step by step with clear examples and exercises.

Title: Statements and Declarations by Category (JavaScript)

Why This Matters

In JavaScript, statements and declarations are fundamental building blocks for writing efficient and error-free code. Understanding their differences, usage, and best practices can help you avoid common pitfalls and write cleaner, more maintainable code. This knowledge is crucial for acing coding interviews, debugging real-world issues, and ensuring your JavaScript applications run smoothly.

Prerequisites

Before diving into statements and declarations, it's important to have a good grasp of the following concepts:

  1. Variables and data types in JavaScript
  2. Basic syntax and operators
  3. Control structures (if-else, loops)
  4. Functions
  5. Understanding the difference between strict mode and non-strict mode
  6. Familiarity with ES6 features such as arrow functions, template literals, and destructuring assignments
  7. Mastery of JavaScript's flow control mechanisms like break, continue, and return
  8. Comprehension of error handling techniques using try-catch blocks

Core Concept

Statements

In JavaScript, a statement is a standalone instruction that performs an action or modifies the program's control flow. A single statement may span multiple lines, but multiple statements must be separated by semicolons (;) on the same line.

Here are some common types of statements:

  1. Expression Statements: Assignments, arithmetic operations, function calls, and other expressions that produce a value and then discard it. For example:
let x = 5; // assignment statement
console.log(x + 3); // expression statement
  1. Declaration Statements: Declare variables, constants, or functions. For example:
const PI = 3.14; // declaration statement (constant)
function greet(name) { ... } // declaration statement (function)
  1. Control Flow Statements: Control the program's flow using conditional statements and loops. For example:
if (x > 0) {
console.log('Positive number');
} else if (x < 0) {
console.log('Negative number');
} else {
console.log('Zero');
}
  1. Loop Statements: Iterate through collections or perform repetitive tasks using for, while, and do-while loops. For example:
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log(sum); // Output: 55
  1. Flow Control Statements: Manage the program's flow using break, continue, and return. For example:
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // exit the loop when i equals 5
}
console.log(i);
}
  1. Error Handling Statements: Handle errors using try-catch blocks. For example:
try {
let x = y / 0; // Division by zero error
} catch (error) {
console.error('Error: ' + error);
}

Declarations

Declarations are a special type of statement used to create variables, constants, and functions in JavaScript. A declaration begins with the keyword let, const, or function.

  1. Variable Declaration: Use the let keyword to declare a variable. For example:
let x; // declaration statement (variable)
x = 5; // assignment statement
  1. Constant Declaration: Use the const keyword to create an immutable variable (a variable whose value cannot be changed). For example:
const PI = 3.14; // declaration statement (constant)
PI = 3; // error: Assignment to constant variable.
  1. Function Declaration: Use the function keyword to create a function. For example:
function greet(name) { ... } // declaration statement (function)

Block Statements

A block is a sequence of statements enclosed in curly braces {}. A block can be used to group multiple statements and create a new scope. For example:

let x = 5;
{
let y = 10; // y is only accessible within this block
console.log(x + y);
}
console.log(y); // error: y is not defined

Worked Example

Let's create a simple JavaScript program that declares variables, defines a function, and uses control flow statements to calculate the sum of even numbers in an array. We will also implement error handling using try-catch blocks.

// Declare a variable for the input array
let arr = [1, 2, 3, 4, 5, 6];

// Function to find the sum of even numbers (using ES6 features)
const sumEvenNumbers = (arr) => {
try {
let sum = 0;
// Loop through the array and add only even numbers to the sum
for (const num of arr) {
if (num % 2 === 0) {
sum += num;
}
}
// Return the calculated sum
return sum;
} catch (error) {
console.error('Error: ' + error);
}
}

// Call the function with our input array and store the result in a variable
let result;
try {
result = sumEvenNumbers(arr);
} catch (error) {
console.error('Error: ' + error);
}

// Print the result or an error message if one occurred
if (result !== undefined) {
console.log(result); // Output: 12
} else {
console.error('An error occurred while calculating the sum.');
}

Common Mistakes

  1. Missing semicolons: JavaScript allows automatic semicolon insertion, but it can lead to unexpected behavior and bugs. Always include semicolons after statements for clarity and consistency.
  2. Variable hoisting: JavaScript hoists variable declarations, but not assignments. Be aware of this when using variables before they are declared.
  3. Improper use of var: Avoid using the var keyword to declare variables, as it has function-level scope and can lead to unintended variable collisions. Use let or const instead.
  4. Misunderstanding let, const, and var: Understand the differences between let, const, and var in terms of scope, block scoping, and hoisting behavior.
  5. Using == instead of ===: Using the loose equality operator (==) can lead to unexpected results due to type coercion. Use the strict equality operator (===) for more accurate comparisons.
  6. Not handling errors properly: Failing to handle errors can cause your program to crash or produce incorrect results. Always use try-catch blocks to manage errors gracefully.
  7. Overusing alert, confirm, and prompt: These functions are not suitable for modern web development, as they can be intrusive and disrupt the user's experience. Use more sophisticated methods like custom modal dialogs or event listeners instead.
  8. Not using linting tools: Linting tools help enforce consistent coding standards and catch potential errors early on. Use tools like ESLint to ensure your code is clean and efficient.

Practice Questions

  1. Declare a constant called GRAVITY and assign it the value of 9.81 m/s².
  2. Write a function that calculates the area of a rectangle with given base (base) and height (height).
  3. Given an array of numbers, write a function that returns the second largest number in the array.
  4. Understand the difference between let, const, and var and explain when to use each one.
  5. Write a program that uses a for loop to calculate the factorial of a given number (using recursion or iteration).
  6. Implement a simple JavaScript game where the user has to guess a randomly generated number within a given range. Use error handling to handle incorrect guesses.
  7. Create a function that takes an array of numbers and returns a new array containing only the odd numbers.
  8. Write a function that sorts an array of objects by a specific property (e.g., name).
  9. Implement a function that finds the longest word in a given string.
  10. Create a function that takes a callback function as an argument and calls it after a specified delay using setTimeout().

FAQ

What is the difference between a statement and a declaration?

A statement is a standalone instruction that performs an action or modifies the program's control flow. A declaration is a specific type of statement used to create variables, constants, or functions in JavaScript.

Why should I avoid using var to declare variables?

Using var can lead to unintended variable collisions and make your code harder to understand and maintain. It's better to use let or const instead, as they have block-level scope.

What happens if I forget to include semicolons in my JavaScript code?

JavaScript allows automatic semicolon insertion, but it can lead to unexpected behavior and bugs. Always include semicolons after statements for clarity and consistency.

What is the difference between let, const, and var?

let and const are block-scoped variables that have a defined lifetime within their enclosing block. They also follow the TDZ (temporal dead zone) rule, meaning they cannot be accessed before their declaration. On the other hand, var is function-scoped and does not follow the TDZ rule, which can lead to unexpected behavior.

What are some best practices for writing clean JavaScript code?

  1. Use descriptive variable names and consistent naming conventions.
  2. Write modular code by breaking your application into smaller, reusable functions and modules.
  3. Follow a coding style guide such as Airbnb's JavaScript Style Guide or Google's JavaScript Style Guide.
  4. Document your code with clear comments and JSDoc-style comments.
  5. Use linting tools like ESLint to enforce consistent coding standards across your team.
  6. Write test cases for your functions using testing frameworks like Mocha, Jest, or Jasmine.
  7. Use strict mode ("use strict") in all of your JavaScript files to avoid common errors and ensure a more secure environment.
  8. Keep your code organized by using appropriate file structure and naming conventions.
  9. Minimize the use of global variables and avoid polluting the global namespace.
  10. Use modern ES6 features like arrow functions, template literals, and destructuring assignments to make your code more concise and readable.
Statements and declarations by category (JavaScript) | JavaScript | XQA Learn