ECMAScript Expression vs. Statement
In ECMAScript, expressions and statements are two fundamental language constructs that play distinct roles in code.
An expression is a snippet of code that evaluates to a value. Expressions can include elements such as literals, variables, operators, and function calls. For example, here are some common expressions:
5 + 3 // 8
"Hello" + " " + "World" // "Hello World"
x * y // The product of variable x and y
Math.max(1, 2, 3) // 3
A statement, on the other hand, is a set of instructions that are executed sequentially to modify program state. Common statements include control flow statements (if, for, while, etc.), declaration statements (var, let, const, etc.), and expression statements (such as AssignmentExpression or FunctionCallExpression). For example, here are some common statements:
var x = 5; // Declaration statement
if (x > 3) { // Control flow statement
console.log("x is greater than 3");
} else {
console.log("x is not greater than 3");
}
for (let i = 0; i < 10; i++) { // Control flow statement
console.log(i);
}
It is important to note that in ECMAScript, some statements can also return a value. These are known as expression statements. For instance, an assignment statement returns the assigned value, and a function call statement returns the result of the called function. Therefore, expressions and statements are not entirely independent concepts; there exists overlap between them.