Fly with code

Get wet inside ocean of code

0%

Statement vs Expression

The biggest difference between them

  • Expression will return a value, but Statement won’t.

All category of statement

From MDN Document

  • Control flow
  • Declarations
  • Functions and classes
  • Iterations
  • Others

Specifications

Statement

When declare a variable in JS, it will set up a space in memory.
for example

1
let a='apple';

But actually it can be separated into 2 steps.

1
2
let a; // statement, create a space in memory, and activate hoisting
a='apple'; // expression

Function Statement

Also called “Named Function”, example as below.
“apple” is the name of this function.

1
2
3
function apple(){
console.log('banana');
};

When we create Function Statement, same as variable declaration, but
It also set up a space inside memory, and will also activate hoisting.

Function Expression

Also called “Anonymous Function”, example as below.

1
2
3
var apple=function (){
console.log('orange');
};

But actually it can be separated into 2 steps.

1
2
3
var apple; // // statement, create a space in memory, and activate hoisting
apple=function ()
{console.log('orange');}; //// expression

Example 1

When we saw below code,

1
2
3
4
cat();
function cat(){
console.log("貓咪");
};

the real execution sequence will be as below

1
2
3
4
 function cat(){
console.log("貓咪");
};
cat();

Example 2

When we saw below code,

1
2
3
4
 var dog = function(){
console.log("狗");
};
dog();

the real execution sequence will be as below

1
2
3
4
5
var dog;
dog= function(){
console.log("狗");
};
dog();

Example 3

When we saw below code,

1
2
3
4
5
6
7
8
whosName()
function whosName() {
if (myName) {
myName = 'Jay';
}
}
var myName = 'Ming';
console.log(myName);

the real execution sequence will be as below

1
2
3
4
5
6
7
8
9
function whosName() {
if (myName) {
myName = 'Jay';
}
}
var myName;
whosName()
myName = 'Ming';
console.log(myName); // Ming