There are subtle differences between expressions and statements in JavaScript.
An expression is a block of code that evaluates to a value. A statement is any block of code that is performing some action.
The distinction between an expression and a statement is important because an expression is a subset of a statement. You can use an expression wherever a statement is expected, but this does not work vice versa.
Conceptually speaking, there are two kinds of expressions: those that perform some sort of assignment and those that evaluate to a value.
For example, x = 10
is an expression that performs an assignment. This expression itself evaluates to . Such expressions make use of the assignment operator.
On the flip side, the expression 10 + 9
simply evaluates to . These expressions make use of simple operators.
There are five primary categories of expression in JavaScript:
Primary expressions consist of basic keywords in JavaScript.
this
this
is used to refer to the current object; it usually refers to the method or object that calls it.
this
is used either with the dot operator or the bracket operator.
this['element']
this.element
Grouping operator
The grouping operator ( )
is used to determine the evaluation precedence of expressions. For example, the two expressions below evaluate to different results because the order of operations is different in both of them.
a * b - c
a * (b - c)
a * b - c
applies the multiplication operator first and then evaluates the result of the multiplication with - b
, while a * (b - c)
evaluates the brackets first.
new
new
creates an instance of the object specified by the user and has the following prototype.
var objectName = new objectType([param1, param2, ..., paramN]);
super
super
calls on the current object’s parent and is useful in classes to call the parent object’s constructor.
super([arguments]); // parent constructor
super.method(args...) // parent's method
The arguments of a function must be an expression, not statements. For example, we can pass in a variable assignment expression as an argument, but we cannot declare a variable in the argument as it is a statement.
Suppose we have the following function:
const function myFunc(arg){
console.log(arg);
}
It is reasonable to pass an object or an expression, such as a ternary operator, in the argument as follows:
myFunc("This is okay");
myFunc(true ? "This is okay" : None);
But we cannot pass in a statement here:
var x = 10
myFunc(if(x > 10){'This will not work'});
As a rule of thumb, any code snippet that can be passed on to the console.log
function and printed can be used as an argument for a function.
Free Resources