Monday, August 27, 2012

JavaScript If...Else Statements


Conditional statements are used to perform different actions based on different conditions.

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:
  • if statement - use this statement to execute some code only if a specified condition is true
  • if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
  • if...else if....else statement - use this statement to select one of many blocks of code to be executed
  • switch statement - use this statement to select one of many blocks of code to be executed

If Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax

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

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!

Example

Make a "Good day" greeting if the time if less than 20:00:
if (time<20)
  {
  x="Good day";
  }
The result of x will be:
Good day

Try it yourself »

Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified condition is true.

If...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.

Syntax

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

Example

If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting
if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
The result of x will be:
Good day

Try it yourself »

If...else if...else Statement

Use the if....else if...else statement to select one of several blocks of code to be executed.

Syntax

if (condition1)
  {
  code to be executed if condition1 is true
  }
else if (condition2)
  {
  code to be executed if condition2 is true
  }
else
  {
  code to be executed if neither condition1 nor condition2 is true
  }

Example

If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting:
if (time<10)
  {
  x="Good morning";
  }
else if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
The result of x will be:
Good day

Try it yourself »

More Examples

Random link

This example will write a link to either W3Schools or to the World Wildlife Foundation (WWF). By using a random number, there is a 50% chance for each of the links.

JavaScript Comparison and Logical Operators


Comparison and Logical operators are used to test for true or false.

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

Given that x=5, the table below explains the comparison operators:

OperatorDescriptionComparingReturnsTry it
==is equal tox==8falseTry it »
x==5trueTry it »
===is exactly equal to (value and type)x==="5"falseTry it »
x===5trueTry it »
!=is not equalx!=8trueTry it »
!==is not equal (neither value or type)x!=="5"trueTry it »
x!==5falseTry it »
>is greater thanx>8falseTry it »
<is less thanx<8trueTry it »
>=is greater than or equal tox>=8falseTry it »
<=is less than or equal tox<=8trueTry it »


How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action depending on the result:

if (age<18) x="Too young";

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:

OperatorDescriptionExample
&&and(x < 10 && y > 1) is true
||or(x==5 || y==5) is false
!not!(x==y) is true


Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename=(condition)?value1:value2 

Example

Example

If the variable age is a value below 18, the value of the variable voteable will be "Too young, otherwise the value of voteable will be "Old enough":
voteable=(age<18)?"Too young":"Old enough";

Try it yourself »

JavaScript Operators


= is used to assign values.
+ is used to add values.

The assignment operator = is used to assign values to JavaScript variables.

The arithmetic operator + is used to add values together.

Example

Assign values to variables and add them together:
y=5;
z=2;
x=y+z;
The result of x will be:
7

Try it yourself »

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:

OperatorDescriptionExampleResult of xResult of yTry it
+Additionx=y+275Try it »
-Subtractionx=y-235Try it »
*Multiplicationx=y*2105Try it »
/Divisionx=y/22.55Try it »
%Modulus (division remainder)x=y%215Try it »
++Incrementx=++y66Try it »
x=y++56Try it »
--Decrementx=--y44Try it »
x=y--54Try it »


JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:

OperatorExampleSame AsResultTry it
=x=y x=5Try it »
+=x+=yx=x+yx=15Try it »
-=x-=yx=x-yx=5Try it »
*=x*=yx=x*yx=50Try it »
/=x/=yx=x/yx=2Try it »
%=x%=yx=x%yx=0Try it »


The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

Example

To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a verynice day

Try it yourself »

To add a space between the two strings, insert a space into one of the strings:

Example

txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a very nice day

Try it yourself »

or insert a space into the expression:

Example

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
The result of txt3 will be:
What a very nice day

Try it yourself »


Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

Example

x=5+5;
y="5"+5;
z="Hello"+5;
The result of x,y, and z will be:
10
55
Hello5

Try it yourself »

The rule is: If you add a number and a string, the result will be a string!

JavaScript Data Types


String, Number, Boolean, Array, Object, Null, Undefined.

JavaScript String

A string is a variable which stores a series of characters like "John Doe".

A string can be any text inside quotes. You can use simple or double quotes:

var carname="Volvo XC60";
var carname='Volvo XC60';

You can use quotes inside a string as long as they don't match the quotes surrounding the string:

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

Or you can put quotes inside a string by using the \ escape character:

var answer='It\'s alright';


JavaScript Number

JavaScript has only one type of number.

Numbers can be with or without decimals:

var pi=3.14;
var x=34;

The maximum number of decimals is 17.

Extra large or extra small numbers can be written with scientific notation:

var y=123e5;    // 12300000
var z=123e-5;   // 0.00123


JavaScript Boolean

Booleans can have only two values: true or false.

var x=true
var y=false


JavaScript Array

The following code creates an Array object called myCars:

var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";

or (condensed array):

var cars=new Array("Saab","Volvo","BMW");

or (literal array):

var cars=["Saab","Volvo","BMW"];


JavaScript Object

An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas:

var person={firstname:"John", lastname:"Doe", id:5566};

The object (person) in the example above has 3 properties: fistname, lastname, and id.
Spaces and line breaks are not important:

var person={
firstname : "John",
lastname  : "Doe",
id        :  5566
};

You can address the object properties in two ways:

name=person.lastname;name=person["lastname"];


Null or Undefined

Non-existing is the value of a variable with no value.

Variables can be emptied by setting the value to null;

cars=null;
person=null;


Declaring Variable Types

When you declare a new variable, you can declare its type using the "new" keyword:

var carname=new String;
var x=      new Number;
var y=      new Boolean;
var cars=   new Array;
var person= new Object;

lampAll variables in JavaScript are objects. When you declare a variable you create a new object.