Net-informations.com
SiteMap  | About    

JavaScript Conditional Statements

All programming languages provide flow control statements that allows you to control the order in which the code is executed. A conditional statement is a set of rules performed if a certain condition is met. These conditions are always comparing between variables and data.

Conditional statements in JavaScript are :

  1. if statement
  2. if-else statement
  3. if...else if...else statement
  4. ternary statement or ternary operator
  5. switch statement

JavaScript if statement

The statements gets executed only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored.

Syntax

Here "conditionExpression" is a boolean expression (returns either true or false). The if statement evaluates the conditionExpression inside parenthesis. If conditionExpression is evaluated to true (nonzero) , statements inside the body of if is executed. If statementBlock is evaluated to false (0) , statements inside the body of if is skipped.

example

output

JavaScript if-else statement

The else statement is to specify a block of code to be executed, if the condition in the if statement is false.

Javascript if else statements

Syntax

In the above syntax, the if statement evaluates the conditionExpression inside parenthesis. If the resulting value is true, the given statementBlock in the "if" block, are executed. If the expression is false, then the given statementBlock in the else block are executed. The else clause of an if...else statement is associated with the closest previous if statement in the same scope that does not have a corresponding else statement.

example

output

JavaScript if...else if...else statement

If you face more than two possible situations and you want to respond differently for each, then you can use an if...else if...else statement. It evaluates the content only if expression is true from several expressions.

Syntax

In the above syntax, it is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.

example

output

You got second grade!!

ternary statement or ternary operator

Instead of using if..else statement, you can use shorthand conditional expressions.

Syntax

example

Noraml if...else statement

Using Ternary Operator(?)

Switch Statements

Switch case statements are a substitute for long if statements that compare a variable to several integral values (if...else if...else). When you want to check a particular condition for a large number of possible values, switch statement is a more efficient alternative of if...else if...else statement.

Syntax

example

output









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.