Computer for SEE and NEB

It is a complete SEE and NEB solution for computer science. It includes Computer Fundamentals, Database (SQL), Programming in C QBASIC, CSS, JavaScript, and PHP for beginners.

Breaking

Post Top Ad

Your Ad Spot

Sunday, February 12, 2023

if..else Statement in JavaScript



if..else Statement in JavaScript


The if..else statement in JavaScript is a conditional statement that allows you to execute one block of code if a specified condition is true, and another block of code if the condition is false.
if..else Statement in JavaScript



Syntax:

The basic syntax of the if...else statement is as follows:

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

Here, condition is an expression that can be either true or false. If the condition is true, the code inside the first set of curly braces {} will be executed. If the condition is false, the code inside the second set of curly braces {} will be executed instead.

Example:


Output:




The above program uses the prompt function to ask the user to enter a number. The input number is stored in the number variable.


The if...else statement then tests whether the number is even or odd. To check if a number is even, we can use the modulo operator % to find the remainder when the number is divided by 2. If the remainder is 0, the number is even; otherwise, it is odd.


In the if statement, the condition number % 2 === 0 checks if the remainder of number divided by 2 is equal to 0. If this condition is true, the code inside the if block will be executed, and the message "number is an even number." will be displayed in the console.
If the condition is false, the code inside the else block will be executed, and the message "number is an odd number." will be displayed in the console.


This program demonstrates how to use the if..else statement in JavaScript to make a simple decision based on a condition and execute different blocks of code depending on whether the condition is true or false.




No comments:

Post a Comment

Post Top Ad

Your Ad Spot

Pages