DEV Community

Kemi Owoyele
Kemi Owoyele

Posted on

What is JavaScript statement

Code that performs a specified task is called a statement. It is a complete command that often ends with a semicolon (;). Examples include loops, conditional statements (such as if or switch statements), and variable declarations.
It is a comprehensive command that the computer is capable of executing. Every action adds to a program's overall logic and functionality. The majority of computer languages operate on statements in a sequential fashion. Because good layout is essential to the proper execution of a program, it is therefore imperative to pay attention to the arrangement of statements.
There are several types of JavaScript statements. Some of them will be covered in this piece.

Declaration statements:

A code segment that declares the creation of variables and functions is called a declaration statement. Examples of declaration statements include:
i) Variable declaration
A variable attaches a name to a data point to enable the reuse of such data in the future.
var name;

in this example, The variable is declared but not assigned a value, and its type is initially considered undefined.
let age = 10; here, age is declared and assigned the value of 10.
ii) Function Declaration: function declaration declares a function. A function performs a task or calculates a value. eg
function addNumbers(x, y){
return x + y;

};
iii) constant declaration: constants in javaScript are declared using the const keyword. Constants, declared with const, cannot be reassigned after their initial assignment.
eg.
const x = 6;

2). Expression statements:

An expression is a combination of one or more values, variables, operators, and functions that, when evaluated, result in a single value. eg,
let sum = 3 + 5;
sum is an expression because it will combine the values of 3 + 5, and give a single value ie, 8.
expression statements are expressions used on their own as statements. They are usually used for action (to do something) and are expected to have side effects (such as modifying variables, calling functions, changing control flow, or interacting with external systems.).

3). Assignment statements

Earlier, we discussed that a variable could be declared but not assigned a value. Assignment statements are used to attach values to variables. Example;
let name;
name = “Ade Ola”;

4). Conditional statements

Some codes do have requirement(s), that meeting them will determine if the code will run or how it will run. There are two major types of conditional statements, they are the "if" statement and the "switch" statements.
(i) if statement
if statements will run if the condition is true. For example,
let name = "James";
if(name === "Mike"){
console.log("hello Mike")
}
else if (name === "Peter"){
console.log("hi Peter")
}
else {
console.log("hello person")
}
The if statement can be used alone without the else and else if. But it can’t go the other way round. For example, you can just write
if ( name === " Mike") {
console.log("hello Mike")
}
and leave it like that. If name is Mike "hello mike will be logged into the console, but if name is not mike, nothing will happen. But you can’t start a statement with just the else statement or the else if statement.
(ii) Switch statement
Switch statement checks for strict equality of case scenario with the variable whose value we intend to compare. A switch statement usually contains case values and default values. The case values are compared to the variable for comparison, if any of the values match the comparison; the code for that case is executed. If none of the cases matches the comparison, the default code will be executed.
Syntax:
let age = 6;

switch (age) {
case 1:
console.log( 'day care' );
break;
case 2:
console.log( 'pre-nursery' );
break;
case 3:
console.log( 'nursery 1' );
break;
case 4:
console.log( 'nursery 2' );
break;
default:
console.log( "elementary school" );
}
Once a match is found and the code in the corresponding case block executes, break immediately exits the entire switch statement. No further cases are evaluated.
(iii) Conditional ternary operator:
A ternary operator takes three operands.
condition ? expression if true : expression if false;
It is a simplified way of writing an if/else statement.
Example;
Let age = 6;
Let daycareAge = age <= 2 ? "bring to daycare" : "Send to School";

Loop statements:

Loop statements are used to perform repetitive tasks, to repeat a block of code for a specific number of times. There are several ways of programming repetitive tasks in JavaScript, for example
For loop, forEach loop, for..of loop, while loop, do..while loop etc.
We shall only discuss the for loop and while loop statements in this article.
for loop
Syntax:
for ( initialExpression; condition; counter) {
// code to execute if the stated condition is true
}

• Initial expression: index value of the loop
• Condition: the requirement for the code to execute
• Counter: increments or decrements the initial value or the value derived after each iteration.
Example
for (let i = 0; i <= 5; i++) {
console.log(i);
}

Image description

In the above example, index/initial value is i, and i is set to 0. The condition is that for as long as i is less than 5, the index value should be incremented by one.
i++ as indicated in this example is the same as i = i + 1; hence, upon the first iteration, 0 is logged into the console. Then the program is run again, it checks if i is still <= 5; then it prints 1. The program will continue to run with the incremented value for each time until it reaches a point where i is greater than 5.
While loop:
While loop used to repeat a program for as long as a specified condition remains true.
Syntax:
while (condition) {
// code to be executed repeatedly until condition is met.
}
• Condition: This expression is evaluated before each iteration of the loop. If it evaluates to true, the code block inside the loop executes. If it's false, the loop terminates.
Example:
let count = 0;
while (count < 5) {
console.log(count);
count++; // increment count within the loop
}

Image description

Just like in the for loop example, the program will continue to run while count is less than 5.

Error handling statement

Error handling statements are written to handle anticipated problems in our code. Error handling helps with preparation for eventualities while running our program, and gives us the opportunity to handle such eventualities elegantly. Issues could be handled without the entire program crashing. Error messages could be customized and debugging will be more effective if errors are properly handled.
In JavaScript, there are four error handling statements.
Try statement:
Try is used to test code for errors.
Catch statement:
Catch is used to determine what happens if any errors are found in the try block.
Throw statement:
Throw statement is used to create desired/custom error message.
Finally statement:
Finally statement runs regardless of if errors were encountered or not.
Example

function calculateSquare(number) {
if (typeof number !== "number") {
throw new TypeError("Input must be a number!");
}

try {
const result = number * number;
return result;
} catch (error) {
console.error("Error calculating square:", error.message);
return null; // Or handle the error differently
} finally {
console.log("Square calculation complete (even if with errors).");
}
}
Error handling makes debugging a lot easier for programmers. It also allows for user friendly error messages. Some cases where try, catch statements are used include;
• To validate user inputs
• To handle network errors when fetching data from an api
• To improve code readability
• To isolate errors
• To contain errors within a specific block of code

Summary

A statement is a piece of code that can do something. It is a complete instruction that a computer can execute. There are different types of statements in JavaScript. Some of them are
Declaration statements: for creating variables and functions*.
Expression statements:
* for combining values to create a single value.
Assignment statements: for assigning values to variables.
Conditional statement: code that runs if a certain requirement is met.
Loop statement: used to perform repetitive tasks.
Error handling statements: used for detecting and handling errors before they crash the entire program.
By combining and arranging these statements in various sequences and patterns, you can perform a wide range of tasks. Statements are essential building blocks in JavaScript. They contribute to the overall performance and functionality of programs.

Top comments (0)