The Difference Between Statements and Expressions in Javascript
Expression returns (expresses) a value:
1 + 2 // expresses 3
"foo".toUpperCase() // expresses 'FOO'
5 // this is a literal that expresses number 5
Statements are individual instructions that runtime will execute:
let x; // declare a variable 'x'
function foo() {} // declare a function 'foo'
function bar() {
return null // return is also a statement
}
Some statements are also expressions:
x = 1; // assignment statement returns right side value
This means that you can treat them as values, for example log them:
console.log(x = 2) // logs '2'
But not all "=" are made equal:
let y = 3; // Here "=" represents initialization.
It is one statement where we declare a variable y
with initial value 3
.
This is not an expression (can't be used as a value) so you cannot do this:
console.log(let y = 3) // you'll get a syntax error.
You can gain more insight by playing with AST trees. Try https://astexplorer.net/ for example.
On the left side you can enter Javascript code and on the right part you'll see it broken down into an Abstract Syntax Tree.
Try adding a variable declaration:
let x;
It will be parsed as the following structure:
type: "VariableDeclaration",
kind: "let"
declarations: [
{
type: "VariableDeclarator",
id: {
type: "Identifier",
name: "x"
},
init: null
}
]
Here it says that we have a VariableDeclaration
of kind let
, then an array of declarations
. It is an array because you can declare multiple variables at once: let x,y,z;
. In this case declarations
array contains only one VariableDeclarator
. This declarator has two fields: id
and init
. The id
field defines the name of the variable and the init
can contain the initial value;
Try adding another line:
x = 2;
Now it will be parsed as an expression:
type: "ExpressionStatement",
expression: {
type: "AssignmentExpression",
operator: "=",
left: {
type: "Identifier",
name: "x"
},
right: {
type: "Literal",
value: 2,
raw: "2"
}
}
As it is an individual instruction it will also be a statement. The name is not very inventive, it's just a combination of expression
and statement
: ExpressionStatement
. Inside of it the actual expression
is defined. The type is AssignmentExpression
and it has two sides: the Identifier
on the left and the Literal
value on the right.
Try parsing some more code as an AST, I'm sure you'll have fun and maybe even learn something new.