const - JS | lectureJavaScript Fundamentals 1

Statements and Expressions

JavaScript Fundamentals 1

An expression is a piece of code that produces a value. For example 1+1 is an expression because it's going to produce a value. This same goes for any number like 2021 because it will produce a value in JavaScript.

On the other hand, a statement is like a bigger piece of code that is executed and which does not produce a value on itself.

Basically, we write our whole program as a sequence of actions and these actions are statements. Let's have as an example the below if/else statement :

if(40 > 25) {
     * The string '40 is greater than 25' is an expression
     * const compareResult = '40 is greater than 25' isn't an expression but a statement
    const compareResult = '40 is greater than 25'

The if/else statement is infact a statement, reason why I call it the if/else statement all the time and the same goes for the switch statement. The above if/else statement doesn't really provide a value because, all it does is to simply declare a variable compareResult without producing a value.

I know it's a little bit confusing, but what you really have to keep in mind is that expressions produce values and statements are like full sentences that translate our actions. Actions which we want our program to perform.

The difference between expressions and statements is important to know because JavaScript expects statements and expressions in different places. For example in template literals, we can only insert expressions and not statements.

console.log(`I just bought ${30} apples.`)