JS Expressions VS Statements

JS Expressions VS Statements

ยท

2 min read

You should understand what JS expressions and statements are, and what is the difference between them to

  • Distinguish between them, so you can use the right one in the right place.
  • Easily understand some others JS concepts that uses them like ternary operator.

What is a JS Expression

Simplify an expression is a unit of code that evaluate to a value, this value can be an object or primitive data like string, number...
Here is a list of expressions:

(x = 7) // evaluate to 7
2 + 3 // evaluate to 5
"str" // evaluate to "str"
(() => {}) // evaluate to a function object

Tip: Everything you can console log, it is an expression

What is a JS Statement

A statement is a snippet of code that performs an action, that means a statement tells JS to do an action.
Here is a list of statements:

let x = 0;  // tell JS to initial a variable with zero as its value
function add(a, b) { return a + b; } // tell JS to initial a add function
if (true) { console.log('Hi'); } // tell JS to console log 'Hi' if the condition truthy

If a statement evaluates to a value, we call it an expression statement

x = 4 // is an expression statement because it assigns 4 to the variable "x" and evaluates to 4.

The purpose of semicolon (;) is to separate between statements.

I hope this article was a good read for you. Thank you so much! โค๏ธ

๐Ÿ‘‰ Follow Me: Github LinkedIn Twitter

ย