JavaScript Statements
JavaScript statements are instructions to be executed by the web browser. Programs are composed of sequences of statements that are executed one by one, top to bottom, to accomplish specific tasks and create functionality.
Statement Types
JavaScript statements are the building blocks of programs—individual instructions that tell the browser what to do. Each statement performs a specific action, like declaring a variable, calculating a value, calling a function, or controlling program flow. JavaScript programs are essentially lists of these programming statements executed sequentially.
Statements are composed of various elements: values (literals and variables), operators (+, -, *, etc.), expressions (combinations that evaluate to values), keywords (special reserved words), and comments (explanatory text). When you write JavaScript, you're combining these elements into valid statements that the JavaScript engine can understand and execute.
Statements are executed in the order they are written, from top to bottom, unless you use control flow statements (like if, for, while) to change the execution order. This sequential execution is fundamental to how programs work—each statement completes before the next one starts. Understanding execution order is crucial for predicting how your code will behave.
Semicolons (;) separate JavaScript statements, marking where one instruction ends and another begins. While JavaScript has automatic semicolon insertion that can add them for you, explicitly including semicolons is considered best practice. It makes your code more predictable and prevents subtle bugs that can occur when the automatic insertion guesses wrong about your intent.
Statements can be grouped together in code blocks using curly braces { }. Code blocks are used with control structures like if statements, loops, and functions to group multiple statements that should execute together. The statements inside a code block are indented for readability, making it visually clear which statements belong together. Code blocks create scope boundaries that affect where variables can be accessed.
// Single statements
var x = 5;
var y = 6;
var z = x + y;
// Code block
if (x > 0) {
console.log("x is positive");
console.log("Value: " + x);
}
// Multiple statements
var a = 1;
var b = 2;
var sum = a + b;
console.log(sum);