JS Expression, Statement;

Two major syntax catogories in JS

  1. Statement
  2. Expression

We have expression statement but not statement expression because expression can sometime act as statements thus expression statement

Expression

Expression are js code snippets that results in a single value.They can be as long as you want them to be.

2 + 2

1 + 1, 2 + 2, 3 + 3

true && false

true || true

functionCall()

All the above code snippets are expressions and can be used anywhere where js expects a value.

console.log(true && 10 * 2);
// logs 20
console.log( 4 && 8);
// logs 8

Expression don't necessarily change state

var points = 10; // statement
points + 10; // expression
points * 10 // expression
console.log(points) // 10

after all the expressions still the value of points is 10 because expression dosent nescessarily change the state.

var points = 10;
// statement

points = points * 20; // statement

console.log(points)// 200

Function calls are expression but the function defination itself might contain statements that change state.

const bar = bar () => {
    points = 100;
}
bar() // expression

even though function call bar() is an expression but the function itself change the state of points

Statements

Statements are code snippets which perform some action or cause some state changes.

In JS statements can never be used where JS expects a value;

console.log(if(true) { return 20; } )
// error

The above code is an error because console.log() expects a value and we are providing it a statemnt.

Statements in JS

  1. if
  2. if-else
  3. while
  4. do-while
  5. for
  6. switch
  7. for-in
  8. with (deprecated)
  9. debugger
  10. variable declaration

Function Declaration, Function Expression, Named Function Expression

function hello (name) {
    return name
}
// function declaration statement

if we use the above syntax where js expects a value then the above syntax becomes a function expression.

console.log(foo(function bar() {}))
// named function expression

console.log(foo(function () {}))
// anonymos function expres // expressionsion

Remember this Where JS expects a value use an expression, You cannot use statements where JS expects a value

Converting an Expression to statement Expression Statement

Use semicolon at end of an expression to convert it into expression statement.

2 + 2 // expression
console.log(2 + 2);
// 4

2 + 2; // expression statement
console.log(2 + 2;)
// error
// as we cannot use statement where JS expects a value.