Working with data is not enough to create a program. Expressions are not the ultimate solution, albeit we can prescribe an action on a certain condition using an expression. Sure, we will have data and we can write an expression to evaluate the condition, but how do we tell the program to perform this or that action? And what if an action has to be repeated several times?
To tackle this issue, there are things called statements in programming languages. They are not expressions, but they allow us to set the order in which they are executed. A statement is a separate command in code that performs a specific action. For example, if
allows you to create a branch in the program, for
allows you to repeat the same action.
For example, using an if
statement, write a program with the following condition:
const randomNumber = getRandomNumber()
if (randomNumber > 50) {
console.log("More than fifty")
} else {
console.log("Less than fifty")
}
Statements do not evaluate anything or return a result, so they are not expressions. For example, the if
statement allows you to describe several ways of executing a program. Its condition will be calculated using an expression (randomNumber> 50
is an expression and returns a result), and other expressions will also be present inside the conditional branches (a function call is an expression and it returns a result).
Please, note that you can code a program only by combining expressions that operate on data with statements that control the order of execution.
How to write JavaScript statements
On the practical side, it is worth remembering the essential trait of statements - they cannot be used in places where expression should be. An expression is a code that, when executed, returns a value. For example, 5 + 3
will return 8
, and Math.random()
will return a random number.
To understand what this is about, let's look at an example:
getBioAbout(
if (num > 10) { return 'Sherlock' }
else { return 'Watson' }
)
// SyntaxError: Unexpected token 'if
An example like this won't work. A simple expression, for example, "Elon Musk"
or the number 5
, can be passed as an argument when calling, or a compound expression that will evaluate and return a value (e.g. a call to another function getCurrentUser). But you cannot pass an instruction to a function.
// Pass a compound expression that will evaluate and return a string
getBioAbout ("Elon Musk")
getBioAbout ("Sherlock" + " " + "Holmes")
getBioAbout (getCurrentUser())
Consecutive statements can be separated by the semicolon operator.
// Separate sequential statements
const num = 5;
if (5 <10) {};
if (5> 10) {};
But expressions can be separated using the comma operator. In this case, all expressions will be executed in order from left to right, but the result will only be returned from the last one in the chain. The comma operator is almost never used, as its use often complicates the code.
function x() {
return 1
}
function z() {
return 2
}
x(), z()
// returns 2 because z() was last executed
In JavaScript, all statements can be divided into several categories:
Control flow (
block
,break
,continue
,empty
,if...else
,switch
,throw
,try...catch
)Declarations (
var
,let
,const
)Functions and classes (
function
,async function
,return
,class
)Iterations (
do...while
,for
,for...in
,for...of
,for await...of
,while
)Others (
debugger
,export
,import
,import.meta
,label
,with
)
Now let's take a closer look at each category.
Control flow
Block
A block is simply a group of statements. It is denoted by curly brackets.
Syntax
{
StatementList
}
Examples
let variable = 10;
let variable = 20;
console.log(variable);
// logs 10
or
const constanta = 10;
{
const constanta = 20;
}
console.log(constanta);
// logs 10
Break
A JS statement that kills the existing loop or label statement and passes program control to the statement that's next after the broken one.
Syntax
break [label];
Examples
function testBreak(z) {
let i = 0;
while (i < 6) {
if (i === 3) {
break;
}
i += 1;
}
return i * z;
}
Continue
It eliminates execution of statements in the iteration of the loop, and moves on to execute the next iteration.
Syntax
continue [label];
Examples
let x = 0;
let y = 0;
while (x < 5) {
x++;
if (x === 3) {
continue;
}
y += i;
}
Empty
This statement is meant to designate specifically that there's no statement where JavaScript syntax is anticipating one. Empty is a semicolon (i.e ;) and it means that no statement will be exercised.
Syntax
;
Examples
let array = ["one", "two", "three"];
// Assign all array values to 0
for (let i = 0; i < array.length; arr[i++] = 0 /* empty statement */);
console.log(arr);
// [0, 0, 0]
If...else
This one carries out a statement when the condition is true. When false, another statement can still be carried out.
Syntax
if (condition) {
statement1
} else {
statement2
}
Examples
function testNum(userInput) {
let result;
if (uswerIno > 0) {
result = 'positive';
} else {
result = 'NOT positive';
}
return result;
}
console.log(testNum(-5));
// expected output: "NOT positive"
Switch
It inspects an expression, matching its value to a case clause, and then carries out associated statements.
Syntax
switch (expression) {
case value1:
//Statements executed when the
//result of expression matches value1
[break;]
case value2:
//Statements executed when the
//result of expression matches value2
[break;]
...
case valueN:
//Statements executed when the
//result of expression matches valueN
[break;]
[default:
//Statements executed when none of
//the values match the value of the expression
[break;]]
}
Examples
switch (input) {
case "Potatoes":
console.log("Potatoes are $0.90");
break;
case "Onions":
console.log("Onions are $0.52");
break;
case "Carrot":
console.log("Carrot are $0.85.");
break;
case "Cucumbers":
case "Tomatoes":
console.log("Cucumbers and tomatoes are $1.59 a pound.");
break;
default:
console.log("Sorry, we have no" + input + ".");
}
Throw
This JavaScript statement is used to implement exceptions defined by users.
Syntax
throw expression;
Examples
throw 'Error2'; // generates an exception with a string value
throw 42; // generates an exception with the value 42
throw true; // generates an exception with the value true
throw new Error('Required'); // generates an error object with the message of Required
Try...catch
It denotes a block of statements to try out, and implements a response if an exception is set.
Syntax
try {
try_statements
}
catch (exception_var) {
catch_statements
}
finally {
finally_statements
}
Examples
try {
try {
throw new Error("Error occured");
} catch (error) {
console.error("inner error msg", error.message);
} finally {
console.log("finally execution");
}
} catch (error) {
console.error("outer err msg", error.message);
}
// Output:
// "inner error msg" "Error occured"
// "finally execution"
Declarations
Var
Var statement sets a variable, it can be initialized to a value too.
Syntax
var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]];
Examples
var variable;
variable = 5;
Let
It is used to declare a block variable, it can be initialized to a value too.
Syntax
let name1 [= value1] [, name2 [= value2]] [, ..., nameN [= valueN];
Examples
let y = 1;
if (y === 1) {
let y = 2;
console.log(y);
// expected output: 2
}
console.log(y);
// expected output: 1
Const
This statement is used to declare a read-only constant.
Syntax
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
Examples
const number = 42;
or
// define MY_CONSTANT as a constant and give it the value 7
const MY_CONSTANT = 7;
// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_CONSTANT = 20;
//MY_CONSTANTA is 7
console.log('my favorite number is: ' + MY_CONSTANT);
// trying to redeclare a constant throws an error
// Uncaught SyntaxError: Identifier 'MY_CONSTANT' has already been declared
const MY_CONSTANT = 20;
// the name MY_CONSTANTis reserved for constant above, so this will fail too
var MY_CONSTANT = 20;
// this throws an error too
let MY_CONSTANT = 20;
Functions and classes
Function
Function statement sets functions with the designated parameters.
Syntax
function name([param[, param,[..., param]]]) {
[statements]
}
Examples
function calcSales(units1, units2, units3) {
return units1 + 89 + units2 + 229 + units3 * 899;
}
Async function
It is used to declare asynchronous functions with the designated parameters.
Syntax
async function name([param[, param[, ...param]]]) {
statements
}
Examples
async function asyncFuncExample() {
try {
let response = await fetch("/no-user-here");
let user = await response.json();
} catch (error) {
alert(error);
}
}
asyncFuncExample();
Return
It is used to specify the value that is to be returned by a function.
Syntax
return [expression];
Examples
function exampleReturn() {
return function calcNum(number) {
return number * 62;
};
}
Class
This JS statement simply declares a class.
Syntax
class name [extends otherName] {
// class body
}
Examples
class FullRectangle extends InitialRectangle {
constructor(height, width, color) {
super(height, width);
this.name = "Full New Rectangle";
this.color = color;
}
}
Iterations
Do...while
It initiates a loop executing a designated statement right until the condition is false. Condition is checked after carrying out the statement, resulting in such a statement that is executed at least one time.
Syntax
do {
statement;
} while (condition);
Examples
let result = "";
let i = 0;
do {
i += 1;
result += i + " ";
} while (i > 0 && i < 10);
For
The statement that initiates a loop comprising 3 expressions (encased in parentheses and divided by semicolons). It is usually followed by a statement carried out in the loop.
Syntax
for ([initialization]; [condition]; [final-expression])
statement
Examples
for (let i = 0; i < 45; i++) {
console.log(i);
// more statements
}
For...in
It replicates object properties in random order. Statements can be executed for each distinct property.
Syntax
for (variable in object) {
statement
}
Examples
const objForIteration = { a: 1, b: 2, c: 3 };
for (const props in objForIteration) {
console.log(`objForIteration.${props} = ${objForIteration[props]}`);
}
// Output:
// "objForIteration.a = 1"
// "objForIteration.b = 2"
// "objForIteration.c = 3"
For...of
It re-iterates objects, e.g. arrays, generators, initiating an iteration hook with statements to be carried out for the value of every property.
Syntax
for (variable of iterable) {
statement
}
Examples
const iterableArr = [11, 21, 31];
for (let val of iterableArr) {
value += 1;
console.log(val);
}
// 12
// 22
// 32
For await...of
It replicates asynchronous iterable objects, array-like objects, generators, iterators, and initiates an iteration hook with statements to be carried out for the value of every property.
Syntax
for await (const variable of iterable) {
statement
}
Examples
const asyncIterable = {
[Symbol.asyncIterator]() {
return {
i: 0,
next() {
if (this.i < 3) {
return Promise.resolve({ value: this.i++, done: false });
}
return Promise.resolve({ done: true });
},
};
},
};
(async function () {
for await (let num of asyncIterable) {
console.log(num);
}
})();
// 0
// 1
// 2