Welcome! If you like our Blog so please Follow this blog and also +1 this blog here---->

Monday, 17 September 2012

Javascript Tutorial 6: JavaScript Operators and If...Else

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

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 y
+Additionx=y+275
-Subtractionx=y-235
*Multiplicationx=y*2105
/Divisionx=y/22.55
%Modulus (division remainder)x=y%215
++Incrementx=++y66
x=y++56
--Decrementx=--y44
x=y--54


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 AsResult
=x=y x=5
+=x+=yx=x+yx=15
-=x-=yx=x-yx=5
*=x*=yx=x*yx=50
/=x/=yx=x/yx=2
%=x%=yx=x%yx=0


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
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
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


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
The rule is: If you add a number and a string, the result will be a string!

JavaScript If...Else

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:
OperatorDescriptionComparingReturns
==is equal tox==8false
x==5true
===is exactly equal to (value and type)x==="5"false
x===5true
!=is not equalx!=8true
!==is not equal (neither value or type)x!=="5"true
x!==5false
>is greater thanx>8false
<is less thanx<8true
>=is greater than or equal tox>=8false
<=is less than or equal tox<=8true


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";
:if>

Javascript Tutorial 5: JavaScript Data Types and Objects

JavaScript Data Types

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

JavaScript Strings

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:

Example

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:

Example

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:

Example

var answer='It\'s alright';
var answer="He is called \"Johnny\"";
You can access each characters in a string with [position]:

Example

var character=carname[7];
String indexes are zero-based, which means the first character is [0], the second is [1], and so on.

JavaScript Numbers

JavaScript has only one type of number.
Numbers can be with, or without decimals:

Example

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:

Example

var y=123e5;    // 12300000
var z=123e-5;   // 0.00123
JavaScript arithmetic is not 100% accurate:

Example

var x=0.2+0.1;


JavaScript Booleans

Booleans can have only two values: true or false.
var x=true
var y=false
Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.

JavaScript Arrays

The following code creates an Array called cars:
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"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

JavaScript Objects

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. Your declaration can span multiple lines:
var person={
firstname : "John",
lastname  : "Doe",
id        :  5566
};
You can address the object properties in two ways:

Example

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;

JavaScript Data Types

Almost everything in JavaScript is an Object: String, Number, Array, Function....
In addition, JavaScript allows you to define your own objects.

JavaScript Objects

JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.

Objects Properties

Properties are the values associated with an object.
The syntax for accessing the property of an object is:
objectName.propertyName
This example uses the length property of the String object to find the length of a string:
var message="Hello World!";
var x=message.length;
The value of x, after execution of the code above will be:
12

Real Life Illustration

A person is an object.
The persons' properties include name, height, weight, age, skin tone, eye color, etc.
All persons have these properties, but the values of those properties differ from person to person.

Objects Have Methods

Methods are the actions that can be performed on objects.
You can call a method with the following syntax:
objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!

Real Life Illustrated

A person is an object.
The persons' methods could be eat(), sleep(), work(), play(), etc.
All persons have these methods.

Creating JavaScript Objects

With JavaScript you can define and create your own objects.
There are 2 different ways to create a new object:
  • 1. Define and create a direct instance of an object.
  • 2. Use a function to define an object, then create new object instances.

Creating a Direct Instance

This example creates a new instance of an object, and adds four properties to it:
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
Alternative syntax (using object literals):

Example

personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};


Using an Object Constructor

This example uses a function to construct the object:

Example

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand.

Adding Methods to JavaScript Objects

Methods are just functions attached to objects.
Defining methods to an object is done inside the constructor function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
The changeName() function assigns the value of name to the person's lastname property.

Now You Can Try:

myMother.changeName("Doe");
JavaScript knows which person you are talking about by "substituting" this with myMother.

Creating JavaScript Object Instances

Once you have a object constructor, you can create new instances of the object, like this:
var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");


Adding Properties to JavaScript Objects

You can add new properties to an existing object by simply giving it a value.
Assume that the personObj already exists - you can give it new properties named firstname, lastname, age, and eyecolor as follows:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";

x=personObj.firstname;
The value of x, after execution of the code above will be:
John
:if>

Javascript Tutorial 4: JavaScript Variables and Functions

JavaScript Variables

Variables are "containers" for storing information:

JavaScript Data Types

var answer1="He is called 'Johnny'";
var answer2='He is called "Johnny"';var pi=3.14;

var x=123;
var y=123e5;
var z=123e-5;
var cars=new Array("Saab","Volvo","BMW");
var person={firstname:"John", lastname:"Doe", id:5566};


Like School Algebra

Remember algebra from school?
x=5
y=6
z=x+y
Do you remember that letters (like x) can be used to hold a value (like 5), and that you can use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5).

JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.
Variable can have a short names, like x and y, or more descriptive names, like age, sum, or, totalvolume.
JavaScript variables can also be used to hold text values, like: name="John Doe".
Here are the rules for JavaScript variable names:
  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must begin with a letter, the $ character, or the underscore character

Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carname;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
carname="Volvo";
However, you can also assign a value to the variable when you declare it:
var carname="Volvo";
In the example below we create a variable called carname, assigns the value "Volvo" to it, and put the value inside the HTML paragraph with id="demo":

Example

<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;


JavaScript Data Types

There are many types of JavaScript variables, but for now, just think of two types: text and numbers.
When you assign a text value to a variable, put double or single quotes around the value.
When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.

One Statement, Many Variables

You can declare many variables in one statement. Just start the statement with var and separate the variables by comma:
var name="Doe", age=30, job="carpenter";
Your declaration can also span multiple lines:
var name="Doe",
age=30,
job="carpenter";


Value = undefined

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following statement:
var carname;


Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carname will still have the value "Volvo" after the execution of the following two statements:
var carname="Volvo";
var carname;


JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:

Example

y=5;
x=y+2;
You will learn more about JavaScript operators in a later chapter of this tutorial.

JavaScript Functions

A function can be executed by an event, like clicking a button.

JavaScript Functions

A function is a block of code that executes only when you tell it to execute.
It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function.
Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made.

How to Define a Function

Syntax

function functionname()
{
some code
}
The { and the } defines the start and end of the function.
Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.

JavaScript Function Example

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}

</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
The function is executed when the user clicks the button.
You will learn more about JavaScript events in the JS Events chapter.

Calling a Function with Arguments

When you call a function, you can pass along some values to it, these values are called argumentsor parameters.
These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc.

Example

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.
The function is flexible, you can call the function using different arguments, and different welcome messages will be given:

Example

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
The example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob, the Builder" depending on which button is clicked.

Functions With a Return Value

Sometimes you want your function to return a value back to where the call was made.
This is possible by using the return statement.
When using the return statement, the function will stop executing, and return the specified value.

Syntax

function myFunction()
{
var x=5;
return x;
}
The function above will return the value 5.
Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will continue executing code, where the function-call was made from.
The function-call will be replaced with the returnvalue:
var myVar=myFunction();
The variable myVar holds the value 5, which is what the function "myFunction()" returns.
You can also use the returnvalue without storing it as a variable:
document.getElementById("demo").innerHTML=myFunction();
The innerHTML of the "demo" element will be 5, which is what the function "myFunction()" returns.
You can make a returnvalue based on arguments passed into the function:

Example

Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);
The innerHTML of the "demo" element will be:
12

function myFunction(a,b)
{
if (a>b)
  {
  return;
  }
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a and b.

Local JavaScript Variables

A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from within that function. (the variable has local scope).
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.

Global JavaScript Variables

Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.

The Lifetime of JavaScript Variables

The lifetime JavaScript variables starts when they are declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.

Assigning Values to Undeclared JavaScript Variables

If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a  GLOBAL variable.
This statement:
carname="Volvo";
will declare the variable carname as a global variable , even if it is executed inside a function.

:if>

Javascript Tutorial 3: JavaScript Statement and Comments

JavaScript Statement

JavaScript is a sequence of statements to be executed by the browser.

JavaScript Statements

JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML element with id="demo":
document.getElementById("demo").innerHTML="Hello Dolly";


Semicolon ;

Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.
Using semicolons also makes it possible to write many statements on one line.

JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will manipulate two HTML elements:

Example

document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";


JavaScript Code Blocks

JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket, and end with a right curly bracket.
The purpose of a block is to make the sequence of statements execute together.
An good example of statements grouped together in blocks, are JavaScript functions.
This example will run a function that will manipulate two HTML elements:

Example

function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
You will learn more about functions in later chapters.

JavaScript is Case Sensitive

JavaScript is case sensitive.
Watch your capitalization closely when you write JavaScript statements:
A function getElementById is not the same as getElementbyID.

A variable named myVariable is not the same as MyVariable.

White Space

JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent:
var name="Hege";
var name = "Hege";


Break up a Code Line

You can break up a code line within a text string with a backslash. The example below will be displayed properly:
document.write("Hello \
World!");
However, you cannot break up a code line like this:
document.write \
("Hello World!");

JavaScript Comments

JavaScript comments can be used to make the code more readable.

JavaScript Comments

Comments will not be executed by JavaScript.
Comments can be added to explain the JavaScript, or to make the code more readable.
Single line comments start with //.
The following example uses single line comments to explain the code:

Example

// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";


JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.
The following example uses a multi line comment to explain the code:

Example

/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";


Using Comments to Prevent Execution

In the following example the comment is used to prevent the execution of one of the codelines (can be suitable for debugging):

Example

//document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
In the following example the comment is used to prevent the execution of a code block (can be suitable for debugging):

Example

/*
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
*/


Using Comments at the End of a Line

In the following example the comment is placed at the end of a code line:

Example

var x=5;    // declare x and assign 5 to it
var y=x+2;  // declare y and assign x+2 to it
:if>