Start running JavaScript

JavaScript Statements

Learn what JavaScript statements are and how they perform operations, covering expression, declaration, control flow and loop statements.

Expressions are single units the engine can evaluate. Statements are bigger steps: they can contain expressions, and the engine runs them to do work.

Programs are built from statements. A statement can span several lines.

JavaScript groups statements into a few families:

  • expression statements
  • declaration statements
  • control flow statements
  • loop statements
  • miscellaneous statements

Separating statements

Statements can end with an optional semicolon ;. Semicolons let you put multiple statements on one line. I usually skip semicolons, but either style works.

Expression statements

An expression on its own is also a statement:

2
0.02
'something'
true
false
this //the current scope
undefined
i //where i is a variable or a constant
1 / 2
i++
i -= 2
i * 2
'A ' + 'string'
[] //array literal
{} //object literal
[1,2,3]
{a: 1, b: 2}
{a: {b: 1}}
a && b
a || b
!a
object.property //reference a property (or method) of an object
object[property]
object['property']
new object()
new a(1)
new MyRectangle('name', 2, {a: 4})
function() {}
function(a, b) { return a * b }
(a, b) => a * b
a => a * 2
() => { return 2 }
a.x(2)
window.resize()

Declaration statements

A declaration assigns a value to a variable name.

Examples:

var i = 0
let j = 1
const k = 2

//declare an object value
const car = {
  color: 'blue'
}

Here are function declarations:

//declare a function
function fetchFromNetwork() {
  //...
}
//or
const fetchFromNetwork = () => {
  //...
}

Control flow statements

Statements can be grouped in a block:

{
  //this is a block
  const a = 1;
  const b = 2;
}

Use a block when JavaScript expects one statement but you need several.

Conditional statements evaluate an expression first. Depending on the result, they run one statement or block:

if (condition === true) {
  //execute this block
} else {
  //execute this block
}

You can omit curly braces when you only have one statement:

if (condition === true) /* statement */ else /* another statement */

We cover every control flow structure in the next lessons.

Loop statements

Loops work like if statements. Some loops repeat while an expression stays true. Others walk a list and run a statement for each item.

See my full JavaScript loops tutorial.

Miscellaneous statements

return

Returns a value from a function and stops execution there.

throw

Throws an exception. We cover exceptions in a later lesson.

try and catch

A try/catch block catches exceptions.

try {

} catch (<expression>) {

}

use strict

This statement applies strict mode.

debugger

Adds a breakpoint the debugger can use.

Lesson completed