Statement in JavaScript – Explained with Examples
A JavaScript statement is a piece of code used to instruct the computer on an action to execute.
Here’s an example:
let bestColor;
The code in the snippet above is a JavaScript statement instructing the computer to create a let
variable named bestColor
.
There are five typical types of JavaScript statements:
- Declaration statements
- Expression statements
- Conditional statements
- Loops statements
- Error handling statements
Let’s discuss each statement type.
What Is a JavaScript Declaration Statement?
A declaration statement is a piece of code that declares the creation of variables and functions.
Here’s an example:
var myBestColor;
The code in the snippet above is a declaration statement that declares the creation of myBestColor
variable.
Keep in mind that var
is a keyword—not a storage space.
The var
keyword declares to the computer that myBestColor
is a JavaScript variable—not a mathematical nor generic variable.
Here’s another example:
function writeName() {}
The code in the snippet above is a declaration statement that declares the creation of the writeName
function.
Remember that function
is a keyword—not a storage space.
The function
keyword declares to the computer that writeName
is a JavaScript function—not a mathematical nor generic function.
So, now that you know what a declaration statement is, we can talk about expression statements.
What Is a JavaScript Expression Statement?
An expression statement is any piece of code that expresses a value.
JavaScript expressions generally get classified into two types and five categories. Let’s discuss these classifications below.
Types of expressions in JavaScript
There are two types of JavaScript expressions: assignment and non-assignment.
What is an assignment expression?
An assignment expression is any piece of code that assigns its evaluated value to a variable (or property).
Here’s an example:
x = 3;
The code in the snippet above is an assignment expression because it uses the equal (=
) operator to assign its evaluated value (3
) to the variable x
.
What is a non-assignment expression?
A non-assignment expression is a piece of code that does not assign its evaluated value to any variable (or property).
Here’s an example:
3 + 7;
The code in the snippet above is a non-assignment expression because it does not assign its evaluated value (10) to any variable (or property).
Let’s now discuss the categories of expressions in JavaScript.
Categories of expressions in JavaScript
The five categories of JavaScript expressions are arithmetic, string, logical, primary, and left-hand side.
What is an arithmetic expression?
An arithmetic expression is a piece of code that expresses a numeric value.
Here’s an example:
10;
Number ten (10
) in the snippet above is an arithmetic expression because it expresses a numeric value.
Consider this other example:
5 + 2;
The code in the snippet above is a non-assignment arithmetic expression that expresses the numeric value of seven (7).
Here’s another example of an arithmetic expression:
z = 5 + 2;
The code in the snippet above is an assignment arithmetic expression that expresses the numeric value of seven (7) and assigns it to the variable z
.
What is a string expression?
A string expression is a piece of code that expresses a string value.
Here’s an example:
"Hello";
The code in the snippet above is a string expression because it expresses a string value.
Here’s another example:
"Hello" + " " + "World";
The string expression in the snippet above expresses the string value "Hello World"
.
Here’s a third example of a string expression:
"1234";
Above is a non-assignment string expression that expresses a string number value.
Here’s another example of a string expression:
let greeting = "Hello, World!";
The code in the snippet above is an assignment string expression that expresses the string value of "Hello, World!"
and assigns it to the let
variable named greeting
.
What is a logical expression?
A logical expression is a piece of code that expresses the Boolean values, true
or false
.
Keep in mind that logical expressions often involve using logical operators like &&
, ||
, and !
.
Here’s an example:
100 > 7;
The code in the snippet above is a logical expression because it expresses the Boolean value of true
.
Consider this other example:
7 > 100;
The code in the snippet above is a logical expression that expresses the Boolean value of false
.
Here’s another example of a logical expression:
true;
The code in the snippet above is a logical expression that expresses the Boolean value of true
.
What is a primary expression?
A primary expression is a piece of code that serves as the basis for creating other expressions.
Typical types of primary expressions are variable references, literal values, and some keywords.
Here are some examples:
"Hello" // String literal1234 // Number literal/(joy)/ // Regular expression literalnull // null valueundefined // undefined valuethis // this keywordtrue // Boolean valuex // variable referencefunction // function keywordclass // class keyword
Each code in the snippet above is a primary expression because they are all expressions you can use to construct other expressions.
What is a left-hand side expression?
A left-hand side expression is a piece of code on the left-hand side of an assignment operator.
A left-hand side expression typically serves as the destination of the value expressed by the right-hand expression.
For instance, consider this code:
x = 100 + 30;
In the snippet above, x
is a left-hand side expression because it is on the left-hand of the assignment operator (=
) and serves as the destination of the value expressed by 100 + 30
.
Another type of JavaScript statement is the conditional statement. Let’s see what it is.
What Is a JavaScript Conditional Statement?
A conditional statement is any code used to specify the prerequisites necessary for the computer to perform specific actions.
The four types of conditional statements in JavaScript are if
, else
, else if
, and switch
.
Let’s discuss each type—starting with the if
conditional statement.
if
conditional statement
The if
conditional statement instructs the computer to execute a JavaScript code block only if a specified condition is true.
Here is its syntax:
if (condition) { // code to execute if the stated condition is true}
Here’s an example:
if (new Date().getHours() < 21) { console.log("Today is special!");}
The snippet above instructs the computer to log "Today is special!"
on the browser’s console if the time is less than 21:00
.
else
conditional statement
The else
conditional statement is an optional add-on to the if
statement.
When used with an if
statement, the else
conditional statement instructs that if the if
statement’s condition is false, the computer should execute the else
statement’s code block.
Here is its syntax:
if (condition) { // code to execute if the stated condition is true} else { // code to execute if the stated condition is false}
Here’s an example:
if (new Date().getHours() < 21) { console.log("Today is special!");} else { console.log("Last minutes embodies great opportunities!");}
The snippet above instructs the computer to log "Today is special!"
on the browser’s console if the time is less than 21:00
. Else, "Last minutes embodies great opportunities!"
should get logged.
Keep in mind that some developers prefer writing their if...else
statements without curly braces. So, they would write the previous code like so:
if (new Date().getHours() < 21) console.log("Today is special!");else console.log("Last minutes embodies great opportunities!");
The snippet above is a valid code. However, some may find it difficult to read.
Therefore, to make your code readable, it’s best to use curly braces.
Another common practice is to omit the else
keyword and its curly braces.
So, you may encounter some code like so:
if (new Date().getHours() < 21) { console.log("Today is special!");}console.log("Last minutes embodies great opportunities!");
While nothing is functionally wrong with the snippet above, note that the second console.log
code is detached from the if
statement.
Therefore, the second console.log
code will always execute—regardless of whether the if
statement’s condition is true or false.
People choose to omit curly braces and the else
keyword because they desire to make their code neater. However, a better alternative is to use the conditional (ternary) operator.
So, now that you know about if
and else
statements let’s discuss the else if
conditional statement.
else if
conditional statement
The else if
conditional statement instructs the computer that if the if
statement’s condition is false, JavaScript should execute the else if
’s code block based on a different condition.
Here is its syntax:
if (condition1) { // code to execute if condition1 is true} else if (condition2) { // code to execute if condition1 is false and condition2 is true} else if (condition3) { // code to execute if condition1 and condition2 are false but condition3 is true} else { // code to execute if all the stated conditions are false}
Here’s an example:
if (new Date().getHours() < 21) { console.log("Today is special!");} else if (new Date().getHours() < 22) { console.log("Don't waste today's opportunities!");}
The snippet above instructs the computer to log "Today is special!"
on the browser’s console if the time is less than 21:00
.
Else, if the time is less than 22:00
, "Don't waste today's opportunities!"
should get logged.
Here’s another example:
if (new Date().getHours() < 21) { console.log("Today is special!");} else if (new Date().getHours() < 22) { console.log("Don't waste today's opportunities!");} else if (new Date().getHours() < 23) { console.log("Fear obscures the eyes of glorious opportunities!");} else { console.log("Last minutes embodies great opportunities!");}
The snippet above instructs the computer to log "Today is special!"
on the browser’s console if the time is less than 21:00
.
Else, if the time is less than 22:00
, "Don't waste today's opportunities!"
should get logged.
Else, if the time is less than 23:00
, "Fear obscures the eyes of glorious opportunities!"
should get logged.
Else, "Last minutes embodies great opportunities!"
should get logged.
Is there any way to make an if...else if...else
conditional statement neater? Welcome to the Chained Ternary Operator.
What is a chained ternary operator?
A chained ternary operator is an alternate (shortcut) way of writing an if...else if...else
statement.
Here is its syntax:
(condition1) ? code to execute if condition1 is true : (condition2) ? code to execute if condition1 is false and condition2 is true : (condition3) ? code to execute if condition1 and condition2 are false but condition3 is true : code to execute if all the stated conditions are false;
Here’s an example:
new Date().getHours() < 21 ? console.log("Today is special!") : new Date().getHours() < 22 ? console.log("Don't waste today's opportunities!") : new Date().getHours() < 23 ? console.log("Fear obscures the eyes of glorious opportunities!") : console.log("Last minutes embodies great opportunities!");
The snippet above instructs the computer to log "Today is special!"
on the browser’s console if the time is less than 21:00
.
Else, if the time is less than 22:00
, "Don't waste today's opportunities!"
should get logged.
Else, if the time is less than 23:00
, "Fear obscures the eyes of glorious opportunities!"
should get logged.
Else, "Last minutes embodies great opportunities!"
should get logged.
Here’s another example:
function checkIfQualified(age) { return age > 34 ? "Qualified" : age >= 30 && age <= 34 ? "Probation period!" : age === 29 ? "Come next year" : "Not qualified!";}
console.log(checkIfQualified(32));
// The invocation above will return: "Probation period!"
The snippet above instructs the computer to log "Qualified"
on the browser’s console if age
is greater than 34
.
Else, if age
is greater or equal to 30
and less than or equal to 34
, "Probation period!"
should get logged.
Else, if age
is strictly equal to 29
, "Come next year"
should get logged.
Else, "Not qualified!"
should get logged.
Keep in mind that the if...else if...else
equivalence of the ternary operator above is like so:
function checkIfQualified(age) { if (age > 34) { return "Qualified"; } else if (age >= 30 && age <= 34) { return "Probation period!"; } else if (age === 29) { return "Come next year"; } else { return "Not qualified!"; }}
console.log(checkIfQualified(32));
// The invocation above will return: "Probation period!"
So, now that you know about the if...else if...else
statement and the chained ternary operator, we can discuss the switch
conditional statement.
switch
conditional statement
The switch
conditional statement instructs the computer to execute a code block if the block’s case value matches the given expression.
The switch
statement is similar to the if...else if...else
conditional statement—except that switch
has a predefined expression which the computer uses to assess all other conditions.
Here is its syntax:
switch (benchMarkExpression) { case value1: // code to execute if value1 matches the benchMarkExpression break; case value2: // code to execute if value1 does not match the benchMarkExpression but value2 does break; default: // code to execute if no value matches the benchMarkExpression}
What is the benchMarkExpression
?
The benchMarkExpression
is required in every switch
conditional statement. It is an expression whose value serves as the prerequisite to executing the case
clause.
What is the case
clause?
The case clause comprises:
- the
case
keyword, - the value you want to match against the
benchMarkExpression
, and - the code the computer will execute if the specified value matches the
benchMarkExpression
.
What is the break
keyword?
The break
keyword stops the execution of other codes in the block if the case
value preceding it matches the benchmark value.
Suppose you omit the break
clause. In such an instance, the next case
clause will run—regardless of whether the case
matches the benchmark.
What is the default
keyword?
The default
keyword specifies the code the computer will run if none of the cases matches the benchmark.
Although the default
keyword is optional, it’s best to include it in every switch
statement as it takes care of unexpected scenarios.
However, note that you can have only one default
keyword in a switch
statement.
Also, keep in mind that you do not need to specify any value with the default
keyword.
It is also not compulsory for the default
clause to be the last case in a switch
block.
Here’s an example:
const currentHour = new Date().getHours();
switch (currentHour) { case 9: console.log("Today is special!"); break; case 15: console.log("Don't waste today's opportunities!"); break; case 21: console.log("Fear obscures the eyes of glorious opportunities!"); break; default: console.log("Last minutes embodies great opportunities!");}
When computers process the switch
code above, here’s what will happen:
- The computer will evaluate the benchmark expression (
currentHour
) to get its current value. - The computer will analyze
switch
’s code block to confirm whether anycase
’s value matches the benchmark. - If a
case
matches the expression’s value, the computer will execute thatcase
’s code. - If none of the cases matches the expression’s value, the
default
clause will get executed.
Here’s another example:
switch (new Date().getDay()) { case 0: console.log("Sunday is here! The workdays begin..."); break; default: console.log("This day is all about work...work...work."); break; case 5: console.log("It's Friday! Prepare for the parties!"); break; case 6: console.log("Saturday is a good day to rest well.");}
Here’s how the snippet above will run:
- The computer will evaluate the benchmark expression (
new Date().getDay()
) to get its current value. - The computer will analyze
switch
’s code block to confirm whether anycase
’s value matches the benchmark. - If a
case
matches the expression’s value, the computer will execute thatcase
’s code. - If none of the cases matches the expression’s value, the computer will execute the
default
clause.
Important stuff to know about the switch
conditional statement
A case
clause’s value can be a primitive data type or a variable.
For instance, consider these examples below:
Example 1: Primitive data used as the case
clauses’ values
// Define three variables:const color1 = "Blue";const color2 = "White";const color3 = "Yellow";
// Define a function:function getColor(color) { switch (color) { case "Blue": console.log("Blue color value"); break; case "White": console.log("White color value"); break; case "Yellow": console.log("Yellow color value"); break; default: console.log("Got no color value"); }}
// Invoke the getColor() function:getColor(color1); // "Blue color value"getColor(color2); // "White color value"getColor(color3); // "Yellow color value"
We used string primitives as the three case
clauses’ values in the snippet above.
Example 2: Variable used as the case
clauses’ values
// Define three variables:const color1 = "Blue";const color2 = "White";const color3 = "Yellow";
// Define a function:function getColor(color) { switch (color) { case color1: console.log("color1 variable name"); break; case color2: console.log("color2 variable name"); break; case color3: console.log("color3 variable name"); break; default: console.log("Got no variable's name"); }}
// Invoke the getColor() function:getColor(color1); // "color1 variable name"getColor(color2); // "color2 variable name"getColor(color3); // "color3 variable name"
The snippet above used variables as the three case
clauses’ values.
Whenever you use a variable as your case
clause’s value, the value will match any argument with the same value.
Here’s an example:
// Define six variables:const color1 = "Blue";const color2 = "White";const color3 = "Yellow";
const carColor = "Blue";const pcColor = "White";const shoeColor = "Yellow";
// Define a function:function getColor(color) { switch (color) { case color1: console.log("color1 variable name"); break; case color2: console.log("color2 variable name"); break; case color3: console.log("color3 variable name"); break; default: console.log("Got no variable's name"); }}
// Invoke the getColor() function:getColor(carColor); // "color1 variable name"getColor(pcColor); // "color2 variable name"getColor(shoeColor); // "color3 variable name"
The switch
statement’s arguments matched the case
clauses’ variables because they have the same values.
So, now that you know about switch
and the if...else if...else
conditional statements, let’s discuss their differences.
switch
vs. if...else if...else
conditional statements – What’s the difference?
Here are some of the differences between switch
and the if...else if...else
conditional statements.
Difference 1: Which of the syntaxes is easier to read?
switch
’s syntax is arguably simpler and less cumbersome than the if...else if...else
statement.
For instance, consider this if...else if...else
statement below:
const myBio = "Oluwatobi";
if (myBio === "CodeSweetly") { console.log("My website is CodeSweetly.com");} else if (myBio === "Oluwatobi") { console.log("My Name is Oluwatobi Sofela");} else { console.log("Oluwatobi Sofela runs CodeSweetly.com");}
Now, consider the switch
alternative:
const myBio = "Oluwatobi";
switch (myBio) { case "CodeSweetly": console.log("My website is CodeSweetly.com"); break; case "Oluwatobi": console.log("My Name is Oluwatobi Sofela"); break; default: console.log("Oluwatobi Sofela runs CodeSweetly.com");}
Which of the two syntaxes do you find neater and easier to read?
Majority say switch
’s syntax is neater. However, the preference is yours to own.
Difference 2: Which of the two conditional statements work best with multiple logical operators?
Suppose you wish to specify complex conditions such as multiple logical operators. In such a case, it’s best to use an if...else if...else
conditional statement.
Here’s an example:
function checkIfQualified(age, canDrive, canCycle) { if (age > 34 && (canDrive === "Yes" || canCycle === "Yes")) { return "Qualified"; } else if ( age >= 30 && age <= 34 && (canDrive === "Yes" || canCycle === "Yes") ) { return "Probation period!"; } else if (age === 29) { return "Come next year"; } else { return "Not qualified!"; }}
checkIfQualified(89, "Yes", "No");
// The invocation above will return: "Qualified"
An if...else if...else
conditional statement is best for complex conditions like the one above.
Another typical JavaScript statement is the iteration (loops) statement. Let’s learn more about it below.
What Is a JavaScript Iteration (Loops) Statement?
An iteration statement is any piece of code that allows you to repeat a program’s execution easily and quickly.
In other words, loops offer a DRY (Don’t Repeat Yourself) way to instruct the computer to execute a specific code repeatedly.
For instance, consider the snippet below:
// Log numbers 1 to 15 on the console without using a loop statement:console.log(1);console.log(2);console.log(3);console.log(4);console.log(5);console.log(6);console.log(7);console.log(8);console.log(9);console.log(10);console.log(11);console.log(12);console.log(13);console.log(14);console.log(15);
Notice that the omission of an iteration statement forced us to repeat the same code (console.log
) fifteen times.
Let’s now see how loops make things neater and DRYer.
// Use a loop statement to log numbers 1 to 15 on the console:for (let i = 1; i <= 15; i++) { console.log(i);}
You see, like magic, we’ve cleaned up our code by using an iteration statement to instruct the computer to log numbers 1
to 15
to the console.
Don’t worry if you don’t understand any part of the loop statement. This article has got you covered!
In the following sections, you will learn about the various types of loop statements that exist in JavaScript.
Types of JavaScript loops
There are five main types of loops statements in JavaScript:
- while loop statement
- do…while loop statement
- for loop statement
- for…in loop statement
- for…of loop statement
Let’s learn about each type—starting with the while
loop statement.
while
loop statement
A while
loop instructs the computer that while a specified condition is true, it should execute the while
loop’s code block repeatedly.
Here is its syntax:
while (condition) { // code to execute if the stated condition is true}
Notice how similar the while
loop’s syntax is to the if
conditional statement. The similarity is no coincidence, as they both work similarly. Their main difference is that an if
statement does not loop through its code block, whereas a while
statement does.
In other words, an if
statement’s code block executes just once. However, a while
loop’s code block executes repeatedly until its specified condition evaluates to false
.
Here’s an example:
let currentDigit = 1;
while (currentDigit < 5) { console.log(currentDigit); ++currentDigit;}
The while
loop statement in the snippet above states that:
- While
currentDigit
’s value is less than5
, the computer should log the value to the console. - Then, increment
currentDigit
by1
. - And start the loop process again until
currentDigit
’s value is5
.
Once currentDigit
’s value equals 5
, the system will realize that the specified condition for the loop process to repeat its execution is now false.
Therefore, the computer will stop looping the statement.
Keep in mind that suppose you wrote the snippet above as an if
statement. In that case, the code will execute just once.
Here’s an example:
let currentDigit = 1;
if (currentDigit < 5) { console.log(currentDigit); ++currentDigit;}
The if
statement in the snippet above will execute only once—because an if
conditional statement does not loop through its code block.
Suppose we did not specify a way for the while
loop’s condition to become false
eventually. In such a case, the loop will never end! It will run infinitely.
For instance, the while
loop below will execute forever because the specified condition is not programmed to become false
eventually.
do…while
loop statement
A do...while
loop instructs the computer to do the task in the code block once. Then, while the specified condition is true, it should repeat the block’s execution.
Here is its syntax:
do { // code to execute} while (condition);
Here’s an example:
let currentDigit = 1;
do { console.log(currentDigit); ++currentDigit;} while (currentDigit < 0);
The do...while
loop statement in the snippet above tells the computer to:
- Do the task in the code block once.
- Then, while
currentDigit
is less than0
, the computer should re-execute the block’s code.
for
loop statement
A for
loop works similarly to a while
loop statement. The main difference is their syntax.
For instance, here is a while
loop’s syntax:
while (condition) { // code to execute if the stated condition is true}
And here is a for
loop’s syntax:
for (initialExpression; condition; expressionUpdater) { // code to execute if the stated condition is true}
initialExpression
states the value the computer should use to begin the loop.condition
defines the prerequisite required for the computer to execute the code block.expressionUpdater
allows you to update an expression at the end of each loop.
So, what exactly does this mean? Let’s see with some examples—starting with this while
loop:
let currentDigit = 1;
while (currentDigit < 5) { console.log(currentDigit); ++currentDigit;}
The for
loop equivalence of the while
loop code above is this:
for (let currentDigit = 1; currentDigit < 5; ++currentDigit) { console.log(currentDigit);}
In the snippet above, the for
loop implies that:
- For an initial value of
1
, and on the condition thatcurrentDigit
is less than5
, the computer should logcurrentDigit
’s value to the console. - Then, increment
currentDigit
by1
. - And start the loop process again until
currentDigit
’s value is5
.
Once currentDigit
’s value equals 5
, the system will realize that the specified condition for the loop process to repeat its execution is now false.
Therefore, the computer will stop looping the statement.
Note that some developers prefer to omit the block ({}
) of a for
loop if the loop contains only one statement. So, you may see the previous snippet written like so:
for (let currentDigit = 1; currentDigit < 5; ++currentDigit) console.log(currentDigit);
Also, keep in mind that you can use the for
loop’s expressionUpdater to update any expression in your script.
For instance, consider this code:
let anotherExpression = 20;
for (let currentDigit = 1; currentDigit < 5; anotherExpression += 10) { console.log(currentDigit); console.log(anotherExpression); ++currentDigit;}
Notice that we did not use the loop’s expressionUpdater (anotherExpression
) to update the loop’s initialExpression (currentDigit
).
Another interesting loop statement is for...in
. Let’s learn more about it below.
for…in
loop statement
A for...in
loop instructs the computer to loop through each property in a given object.
Here is its syntax:
for (const propertyKey in object) { // code to execute}
You can translate the snippet above as:
for
eachpropertyKey
in
the specifiedobject
, the computer should execute the code block.
Keep in mind that const propertyKey
is a regular variable that we’ve named propertyKey
. So, when defining your for...in
loop, feel free to give the variable any name you prefer.
Here’s an example:
const myBio = { firstName: "Oluwatobi", lastName: "Sofela", website: "CodeSweetly.com",};
for (const eachProp in myBio) { const aboutMe = `${myBio[eachProp]} is my ${eachProp}.`; console.log(aboutMe);}
// The for...in code above will return:// "Oluwatobi is my firstName."// "Sofela is my lastName."// "CodeSweetly.com is my website."
In the snippet above, the for...in
code states that for each property in myBio
, the computer should execute the loop’s code block.
So, now that you know about for...in
, we can talk about the for...of
loop.
for…of
loop statement
A for...of
loop instructs the computer to loop through each of an iterable object’s values.
for...of
allows you to loop over Arrays, Sets, Maps, Strings, Nodelist, arguments, and user-defined iterables.
Here is its syntax:
for (const value of iterableObject) { // code to execute}
You can translate the snippet above as:
for
eachvalue
of
the specifiediterableObject
, the computer should execute the code block.
Here’s an example:
const bestColors = ["Blue", "White", "Pink", "Green"];
for (const item of bestColors) { console.log(item);}
// The for...of loop statement above will return:// "Blue"// "White"// "Pink"// "Green"
The for...of
code states that for each value of the bestColors
iterable object, the computer should execute the loop’s code block.
Before we wrap up our discussion on loop statements, you should know the difference between for...in
and for...of
. So, let’s talk about that below.
for…in
vs. for…of
loop statement – What’s the difference?
The main difference between the for...in
loop and the for...of
statement is this:
for...in
loops through the names of each item in an object. Butfor...of
loops through each value.
For instance, consider the code below, where we used a for...in
loop to iterate over an array object:
const bestColors = ["Blue", "White", "Pink", "Green"];
for (const item in bestColors) { console.log(item);}
// The for...in loop above will return:// "0"// "1"// "2"// "3"
Notice that the snippet above iterated over the names (keys) of each item in the bestColors
array.
Let’s now replace the for...in
code with for...of
to see the loop’s output:
const bestColors = ["Blue", "White", "Pink", "Green"];
for (const item of bestColors) { console.log(item);}
// The for...of loop statement above will return:// "Blue"// "White"// "Pink"// "Green"
Observe that the for...of
code looped over the values of each item of the bestColors
array.
So, whenever you need to iterate over the values of an iterable object, use for...of
. But suppose you aim to loop over enumerable properties. In such a case, use for...in
.
There are instances when you need to manage errors. For those use cases, JavaScript provides the error handling statement. Let’s learn more about it below.
What Is a JavaScript Error Handling Statement?
An error handling statement is a piece of code that allows you to test, manage, and create custom error messages.
The four error handling statements in JavaScript are: try
, catch
, finally
, and throw
.
Let’s discuss each type—starting with try
.
Learn Flexbox with Images
try
statement
The try
statement allows you to test a specific code block for errors.
Here’s an example:
try { ccconsole.log("Can you spot any error?");}
Suppose the computer finds an error in try
’s code block. In that case, JavaScript will create an Error
object containing a name
and message
properties.
Keep in mind that a try
statement defined alone (as done above) will do nothing. Instead, you must chain it to either a catch
or finally
statement.
catch
statement
The catch
statement allows you to handle the exceptions thrown by try
.
For instance, consider the try...catch
code below:
try { ccconsole.log("Can you spot any error?");} catch (err) { console.log(err.message);}
// The try...catch statement above will return:// "ccconsole is not defined"
The snippet above used try
to test if any error exists in {ccconsole.log("Can you spot any error?");}
.
Then, we used catch
to handle any exception thrown by the try
statement.
As such, if the computer catches an error in the try
statement, it will do the following:
- Create an
Error
object. - Pass the
Error
object to thecatch
statement’serr
parameter. catch
will handle the exception thrown by loggingerr.message
’s value to the browser’s console.
Note that whenever you log an error to the console in a catch
statement, it’s advisable to use console.error()
instead of console.log()
.
So, let’s refactor the previous snippet to use console.error()
.
try { ccconsole.log("Can you spot any error?");} catch (err) { console.error(err.message);}
// The try...catch statement above will return:// "ccconsole is not defined"
Keep in mind that you are not mandated to reference the Error
object in your catch
statement.
So, for instance, you can define the previous try...catch
code like so:
try { ccconsole.log("Can you spot any error?");} catch { console.error("There is a spelling mistake!");}
// The try...catch statement above will return:// "There is a spelling mistake!"
Let’s now discuss the finally
statement.
finally
statement
The finally
statement allows you to run some code after try
or catch
’s execution—regardless of whether try
threw an exception or whether catch
handled any error.
Here’s an example:
try { ccconsole.log("Can you spot any error?");} finally { console.log("I will always execute—regardless of try or catch's actions!");}
// The try...finally statement above will return:// "I will execute always—regardless of try or catch's actions!"// "Uncaught ReferenceError: ccconsole is not defined"
Notice that the computer executed finally
’s code—even though we did not specify a catch
statement.
Here’s another example:
try { console.log("Can you spot any error?");} finally { console.log("I will always execute—regardless of try or catch's actions!");}
// The try...finally statement above will return:// "Can you spot any error?"// "I will always execute—regardless of try or catch's actions!"
Now, consider this third example:
try { ccconsole.log("Can you spot any error?");} catch (exception) { console.error(exception.message);} finally { console.log("I will always execute—regardless of try or catch's actions!");}
// The try...catch...finally statement above will return:// "ccconsole is not defined"// "I will always execute—regardless of try or catch's actions!"
Another vital error handling statement is throw
. Let’s talk about it below.
throw
statement
The throw
statement allows you to create your custom error message.
throw "I am a custom-made error!";
// The throw statement above will return:// "Uncaught I am a custom-made error!"
throw
causes JavaScript to stop the current function’s execution. Therefore, all statements after throw
will not run.
// Define a function:function throwCustomError() { throw "I am a custom-made error!"; console.log("JavaScript won't read me."); console.log("The throw statement blocks my execution.");}
// Invoke the throwCustomError function:throwCustomError();
// The invocation above will return:// "Uncaught I am a custom-made error!"
The snippet above did not run the two console.log
s because JavaScript skips all the statements after throw
.
After executing the throw
statement, the computer will pass control to the first catch
block in the call stack.
Here’s an example:
try { throw { myCustomTest: "CodeSweetlyTest", text: "This Test Works!" };} catch (exp) { console.error(exp.myCustomTest + ": " + exp.text);}
// The try...catch statement above will return:// "CodeSweetlyTest: This Test Works!"
Suppose the call stack has no catch block. In that case, JavaScript will terminate the program.