JavaScript Statements
In JavaScript, a statement is a syntactic unit of code that expresses an action to be carried out. Statements form the building blocks of a JavaScript program, instructing the interpreter or browser to perform specific actions such as declaring variables, making decisions, or iterating over collections. Each statement ends with a semicolon (;), though in many cases, JavaScript allows you to omit the semicolon if the statement is on a single line.
Declaring Variables
- var: Declares a variable, optionally initializing it to a value.
- let: Declares a block-scope local variable, optionally initializing it to a value.
- const: Declares a read-only named constant.
- function: Declares a function with specified parameters.
- class: Declares a class.
Control Flow
- return: Specifies the value to be returned by a function.
- break: Terminates the current loop, switch, or label statement and transfers control to the statement following the terminated statement.
- continue: Terminates the execution of the statements in the current iteration of the loop and continues with the next iteration.
- throw: Throws a user-defined exception.
- if…else: Executes a statement if a specified condition is true; otherwise, another statement can be executed.
- switch: Evaluates an expression, matches the expression’s value to a case clause, and executes statements associated with that case.
- try…catch: Marks a block of statements to try and specifies a response should an exception be thrown.
Loops
- do…while: Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, ensuring the
statement executes at least once. - for: Creates a loop with three optional expressions enclosed in parentheses, separated by semicolons, followed by a statement to be executed in the loop.
- for…in: Iterates over the enumerable properties of an object in arbitrary order, executing statements for each distinct property.
- for…of: Iterates over iterable objects (including arrays, array-like objects, iterators, and generators), invoking a custom iteration hook with statements to be executed for the
value of each distinct property. - for await…of: Iterates over async iterable objects, array-like objects, iterators, and generators, invoking a custom iteration hook with statements to be executed for the
value of each distinct property. - while: Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.