Javascript expression and statement: compose your complete program

This tutorial is a part of the Learn everything about Javascript in one course.

Expression is equivalent to "phrase"

Expression is JavaScript phrase, combined of values, variables, and operators, which computes to a value. An expression always returns a value.

expression.js
// Expression is equivalent to "phrase"

// the followings are expressions
5 * 10 // computes to 50
x * 10 // expression can contain variable(s)
'John' + ' ' + 'Doe' // computes to 'John Doe'

Declaration & assignment statement, statement is equivalent to "sentence"

Statement is JavaScript sentence. As a human sentence to express some thought, a Javascript statement executed to complete logic.

Type Description Example
Declaration statement Assign a value to a variable let x
Assignment statement Assign a value to a variable x = 10
Statement block combination of multiple statements { // some statement }
Flow control statement Control what block of statement will be executed if, if else, if else if, switch case
Loop control statement Control if block of statement will be executed again and again do while, while, for, for in, for of
statement.js
// Statement is equivalent to "sentence"

// Declaration statement
let x

// Assignment statement
x = 10

// a statement block housed by curly brackets
{
  let name = 'John'
  let greet
  greet = 'Hello ' + name
  console.log(greet) // Hello John
}

Conditional statement: "if", "if...else", "if...else if"

The conditional statement control which statement block will be run based on given logical Boolean value. Only one statement block will be executed. else and esle if blocks are optional.

Type Description
if(condition) { // statements } If condition is true, run the statements
if(condition) { // statements1 }
else { // statements2 }
If condition is true, run statements1,
else run statements2
if(condition1) { // statements1 }
else if(condition2) { // statements2 }
... // as many else if as needed here
else { // lastStatements }
If condition1 is true, run statements1.
If condition2 is true, run statements2.
... and so on...
If none of the condition are true, run lastStatements
if_else_if.js
// Conditional statement: if, if else, if else if

// if
if (1 > 2) {
  console.log('not supposed to be seen on console.')
}

if (1 < 2) {
  console.log('running if logic!')
}
// running if logic!


// if else
if (2 <= 2) {
  console.log('running if else logic')
} else {
  console.log(`condition is true, this line won't show`)
}
//running if else logic


// if else if
if (2 < 2) {
  console.log(`this if block won't run`)
} else if (3 < 2) {
  console.log(`this else if block won't run`)
// you can have as many else if block as needed
} else if( 4 <= 4) {
  console.log(`this else if block will run`)
} else {
  console.log(`this else block won't run`)
}
// this else if block will run

Conditional statement: "switch...case"

switch statement:

  • matches given value to a case.
  • if there's a match, statements associated that that case will run.
  • if there's no match, statements associated with default (if given) case will run.
switch_case.js
// Conditional statement: switch... case

function getPrice(fruit) {
  switch(fruit) {
    case 'papaya':
      console.log('papaya $3.39/pound')
      break // break is to break out of this "case"
    case 'orange':
      console.log('orange $1.33/pound')
      break
    default:
      console.log('flat rate:', fruit, '$2.99/pound')
      break
  }
}

getPrice('orange') // orange $1.33/pound
getPrice('papaya') // papaya $3.39/pound
getPrice('mango') // flat rate: mango $2.99/pound
getPrice('blueberry') // flat rate: blueberry $2.99/pound

Loop statement: "do...while" and "while"

do... while: keep doing this statement block while condition is still true. while: while condition is true, execute statement block. Similarities of these two:

  • condition is re-evaluated after each statement block run.
  • statement block will run if condition is true.
  • break statement is used to break out of the loop anytime.
do...while while
Difference - statement block is executed at least once - statement block may not execute
do_while_loop.js
// Loop statement: do... while
let i = 0
do {
  console.log(i)
  i++
} while(i <= 3)
// 0
// 1
// 2
// 3

// we can use "break" statement to get out of a loop anytime
let j = 0
do {
  console.log(j)
  j++
  break
} while(j <= 3)
// 0
while_loop.js
// Loop statement: while
let i = 0
while(i <= 3) {
  console.log(i)
  i++
}
// 0
// 1
// 2
// 3

// we can use "break" statement to get out of a loop anytime
let j = 0
while(j <= 3) {
  console.log(j)
  j++
  break
} 
// 0

Loop statement: "for", full control of your loop

for loop statement usually used to loop through array and array-like objects.

Syntax: for(counterDeclaration; conditionToContinueLoop; counterModification) { // statements }.

for_loop.js
// Loop statement: "for"

// loop through array, in this example
// counterDeclaration: let i = 0
// conditionToContinueLoop: i < arr.length
// counterModification: i++
const arr = [1,2,3,'a','b']
for(let i = 0; i < arr.length; i++) {
  console.log(arr[i])
}
// 1
// 2
// 3
// a
// b

Loop statement: "for...in", loop through properties of object

for...in iterates over all properties of an object. Syntax: for(propertyDeclaration in object) { // statements }

for_in_loop.js
// Loop statement: "for...in"

// in this example
// propertyDeclaration: const property
// object: obj
const obj = {
  a: 'b',
  c: 'd',
  'x-y': 1,
  '2': 3
}
for(const property in obj) {
  console.log(property)
}
// 2
// a
// c
// x-y

Loop statement: "for...of", loop through elements of array

for...of iterates over all elements of an array. Syntax: for(elementDeclaration of array) { // statements }

for_of_loop.js
// Loop statement: for...of

// in this example
// elementDeclaration: const property
// array: arr
const arr = [1,2,3,'a','b']
for(const element of arr) {
  console.log(element)
}
// 1
// 2
// 3
// a
// b

Looping through object is very common. We will combine for...of and Object.entries(array) to effortlessly do this. Object.entries(myObject) returns an array [key, value] (note that destructuring is used here) of given object.

for_of_loop.js
// loop through object with "for...of" and "Object.entries()"

// in this example,
// myObject is: obj
// Object.entries(obj) returns: [['1',2], ['a','b'], ['c','d']]
// let [key, val] = ['1',2] (destructuring) -> key = '1', val = 2
const obj = {
  a: 'b',
  c: 'd',
  '1': 2
}
for (let [key, val] of Object.entries(obj)) {
  console.log(`key: ${key}, value: ${val}`)
}
// key: 1, value: 2
// key: a, value: b
// key: c, value: d

Jump statement: "break", break out of a loop anytime

break statement is used to terminate the current loop. Some examples:

for_of_loop.js
// Jump statement: "break", break out of a loop anytime

// break out of "for" loop
for(let i = 0; i < 3; i++) {
  console.log('"for" loop should print out only once!')
  break
}
// "for" loop should print out only once!

// break out of "while" loop
while(true) {
  console.log('"while" loop should print out only once!')
  break
}
// "while" loop should print out only once!

Jump statement: "continue", continue the loop from the beginning

We can use continue to skip the rest of the code in current round of loop and start a new round of loop.

for_of_loop.js
// Jump statement: continue, continue the loop from the beginning

// continue in "for" loop
for(let i = 0; i < 3; i++) {
  if(i != 1) continue
  console.log('current i:', i)
}
// current i: 1

// continue in "while" loop
let counter = 0
while(counter < 3) {
  counter++
  if(counter != 1) {
    continue
  }
  console.log('current counter:', counter)
}
// current counter: 1

Summary

  1. Expression ("phrase") computes and returns a value.
  2. Statement is like a "sentence", used to achieve a purpose.
  3. Delaration and assigment statement are for declaring and modifying your variables.
  4. Conditional statement (if, switch case) are to decide which statement block will be run.
  5. Loop statement (for, while) are to repeat running a statement block based on some condition.
  6. break and continue statement are to break or continue the statement loop.