JavaScript statements are instructions that a browser executes. These instructions define the logic of your program, enabling you to interact with web pages dynamically.
Each statement can perform a specific task, like displaying a message, making calculations, or manipulating HTML elements.
What Are JavaScript Statements?
Definition: A JavaScript statement is a command written in the script to perform an action.
Example:
let x = 5; // Assigns value 5 to the variable x
console.log(x); // Displays the value of x in the console
Components of JavaScript Statements
1. Keywords
Reserved words in JavaScript that indicate specific actions.
Example: let
, const
, if
, for
.
2. Identifiers
Names are used to identify variables, functions, or objects.
Example:
let name = "Junaid"; // "name" is the identifier
3. Expressions
Pieces of code that produce values.
Example:
let total = 10 + 20; // "10 + 20" is an expression
4. Operators
Symbols are used to perform operations on variables or values.
Example: +
, -
, *
, /
.
Writing JavaScript Statements
Single-line Statement:
Executes one action in a single line.
console.log("Hello, World!");
Multi-line Statements:
Uses multiple lines for better readability.
let a = 10;
let b = 20;
console.log(a + b);
Semicolon Usage:
Semicolons (;
) are optional but are recommended for separate statements.
Types of JavaScript Statements
1. Variable Declaration
Used to create variables to store data.
Example:
let age = 29; // Using let
const pi = 3.14; // Using const
var name = "Junaid"; // Using var
Assignment Statement
Assigns values to variables.
Example:
let x = 10;
let y = x + 5; // x + 5 is assigned to y
Best Practices for Writing JavaScript Statements
Use Descriptive Variable Names:
Example: Instead of x
, use age
or totalAmount
.
JavaScript statements are the foundation of any program, enabling dynamic interactions on web pages.