Conditional statements in javascript

JavaScript is a commonly used lightweight open source computer programming language used to design part of web pages for the interaction of the client to the server or from the server to the client.

Conditional Statements in JavaScript

A conditional statement is a set of commands that executes if a specified condition is true.

JavaScript supports two conditional statements:

if..else and switch.

IF…ELSE STATEMENT

The if statement is executed if a logical condition is true. The optional else clause is executed if the condition is false.

* * *

if (condition) {

statement_1;

}else {

statement_2;

}

IF…ELSE STATEMENT

The condition can be any expression that evaluates to true or false.

If the condition evaluates to true, statement_l is executed. Otherwise, statement_2 is executed.

statement_1 and statement_2 can be any statement, including further nested if statements.

FALSY VALUES

The following values evaluate to false (Falsy values):

  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string (” “)

All other values-including all objects-evaluate to true when passed to a conditional statement.

SWITCH STATEMENT

A switch statement allows a program to evaluate an expression and attempt to match the expression’s value to a case label.

If a match is found, the program executes the associated statement.

SWITCH STATEMENT

* * *

Switch (expression){

case label_1:

statements _1

[break;]

case label_2:

statements_2

[break;]

…

default:

statements_def

[break;]

}

BREAK STATEMENT

The optional break statement ensures that the program breaks out of switch once the matched statement is executed.

Then continues execution at the statement following the switch.

If break is omitted, the program continues execution inside the switch statement (and will evaluate the next case, and so on).

Leave a Reply

Your email address will not be published. Required fields are marked *