JavaScript Statements

JavaScript statements are the instructions that a browser executes. These statements form the building blocks of a JavaScript program, instructing the browser to perform specific tasks such as declaring variables, manipulating HTML elements, or performing calculations.

Key Topics

What Are JavaScript Statements?

JavaScript statements are composed of values, operators, expressions, keywords, and comments. Each statement instructs the browser to perform a specific task. For example:

let x, y, z;  // Declare variables
x = 5;          // Assign value to x
y = 10;         // Assign value to y
z = x + y;      // Calculate and assign the sum

Output

x = 5

y = 10

z = 15

Semicolon Usage

Semicolons are used to separate JavaScript statements. Although optional due to automatic semicolon insertion, it is recommended to use them for clarity and to prevent potential errors.

let a = 5;
let b = 10;
let c = a + b;
console.log(c); // Outputs 15

Output

15

JavaScript White Space

JavaScript ignores multiple spaces, allowing you to add white space for better readability. For example:

let person = "John"; // With space
let person="John";   // Without space

Output

Both lines produce the same result: person = John

JavaScript Code Blocks

Code blocks are groups of JavaScript statements enclosed in curly braces {}. They are often used in functions, loops, and conditional statements to group related code.

function greet() {
    let name = "Alice";
    console.log("Hello, " + name);
    console.log("How are you?");
}

greet();

Output

Hello, Alice

How are you?

Key Takeaways

  • Statements: Instructions executed one by one in order.
  • Semicolons: Recommended for separating statements.
  • White Space: Improves code readability without affecting execution.
  • Code Blocks: Group statements together for logical organization.