Sie sind auf Seite 1von 49

What is JavaScript

JavaScript is a loosely-typed client side scripting language that executes in the user's
browser.

JavaScript implements ECMAScript standards, which includes core features based on


ECMA-262 specification

JavaScript History:

In early 1995, Brendan Eich from Netscape, took charge of design and implementation of
a new language for non-java programmers to give access of newly added Java support in
Netscape navigator.

The dynamic nature of the language led to it being named "LiveScript" but was quickly
renamed to "JavaScript"

JavaScript Engine:

JavaScript engine in the browser interprets, compiles and executes JavaScript code which
is in a web page.

Advantages of JavaScript:

1. JavaScript is easy to learn.


2. It executes on client's browser, so eliminates server side processing.
3. It executes on any OS.
4. JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc.
5. Performance of web page increases due to client side execution.
6. JavaScript code can be minified to decrease loading time from server.

Setup Development Environment for JavaScript:

In order to work with JavaScript, you need to install the following tools:

1. Browser
2. Editor

1
Browser:

You can install any browser as per your preference e.g. Internet Explorer,Chrome,
FireFox, Safari, Opera etc. JavaScript works on any web browser on any OS.

Editor:

You can write JavaScript code using a simple editor like Notepad. However, you can also
install any open source or licensed IDE in order to get IntelliSense support for JavaScript
and syntax error/warning highlighter e.g. Visual Studio, Aptana, Eclipse etc.

Prefer an editor which has built-in features of IntelliSense support and syntax error
highlighter for speedy development.

Online Editor:

You can also use online editor to learn JavaScript e.g. plnkr.co, jsfiddle.net or jsbin.com.

Points to remember:

JavaScript code must be written within <script> tag.

External JavaScript file (.js) can be referenced using <script


src="/PathToScriptFile.js"></script> where src attribute is used to specify the full
path of .js file.

Html5 standard does not required type="text/javascript" attribute, whereas prior


html standards requires type attribute.

The <script> tag can be added into <head> or <body> tag.

JavaScript is a case sensitive scripting language. It means functions, variables and


keywords are case sensitive.

String is a text in JavaScript. A text content must be enclosed in double or single


quotation marks.

2
JavaScript statements are separated by a semicolon. However, it is not mandatory
to end every statement with a semicolon but it is recommended.

JavaScript ignores multiple spaces and tabs. The following statements are same.
Example: JavaScript ignores whitespaces

var one =1;


var one = 1;
var one = 1;

A comment is a single or multiple lines, which give some information about the
current program. Comments are not for execution.Write single line comment after
double slashes // or write multiple lines of comments between/* and */
Keywords are reserved words in JavaScript, which cannot be used as variable
names or function names.
The following table lists some of the keywords used in JavaScript.

Keywords
var function if
else do while
for switch break
continue return try
catch finally debugger
case class this
default false true
in instanceOf typeOf
new null throw
void width delete

Display Popup Message:


JavaScript provides different built-in functions to display popup messages for different
purposes e.g. to display a simple message or display a message and take user's
confirmation on it or display a popup to take a user's input value.

Alert Messagebox:

Use alert( ) function to display a popup message to the user. This popup will have OK
button to close the popup.
3
Example: alert messagebox

alert("This is alert box!"); // display string message

alert(100); // display number

alert(true); // display boolean

The alert function can display message of any data type e.g. string, number, boolean etc.
There is no need to convert a message to string type.

Confirm Messagebox:

Sometimes you need to take the user's confirmation to proceed. For example, you want to
take user's confirmation before saving updated data or deleting existing data. In this
scenario, use JavaScript built-in function confirm( ). The confirm( ) function displays a
popup message to the user with two buttons, OK and Cancel. You can check which
button the user has clicked and proceed accordingly.

The following example demonstrates how to display a confirm box and then checks
which button the user has clicked.

Example: confirm messagebox

var userPreference;

if (confirm("Do you want to save changes?") == true) {

userPreference = "Data saved successfully!";

} else {

userPreference = "Save Cancelled!";

Prompt Messagebox:

Sometimes you may need to take the user's input to do further actions in a web page. For
example, you want to calculate EMI based on users' preferred tenure of loan. For this
kind of scenario, use JavaScript built-in function prompt( ).

4
Prompt function takes two string parameters. First parameter is the message to be
displayed and second parameter is the default value which will be in input text when the
message is displayed.

Syntax:
prompt([string message], [string defaultValue]);
Example: prompt messagebox

var tenure = prompt("Please enter preferred tenure in years", "15");

if (tenure != null) {
alert("You have entered " + tenure + " years" );
}

As you can see in the above example, we have specified a message as first parameter and
default value "15" as second parameter. The prompt function returns a user entered value.
If user has not entered anything then it returns null. So it is recommended to check null
before proceeding.

Note : The alert, confirm and prompt functions are global functions. So it can be called
using window object like window.alert( ), window.confirm( ) and window.prompt( ).

1. Popup message can be shown using global functions - alert(), confirm() and
prompt().
2. alert() function displays popup message with 'Ok' button.
3. confirm() function display popup message with 'Ok' and 'Cancel' buttons. Use
confirm() function to take user's confirmation to proceed.
4. prompt() function enables you to take user's input with 'Ok' and 'Cancel' buttons.
prompt() function returns value entered by the user. It returns null if the user does
not provide any input value.

Variable:

Variable means anything that can vary. JavaScript includes variables which hold the data
value and it can be changed anytime.

JavaScript uses reserved keyword var to declare a variable. A variable must have a
unique name. You can assign a value to a variable using equal to (=) operator when you
declare it or before using it.

5
Syntax:

var <variable-name>;

var <variable-name> = <value>;

Example: Variable declaration & initialization

var one = 1; // variable stores numeric value

var two = 'two'; // variable stores string value

var three; // declared a variable without assigning a value

In the above example, we have declared three variables using var keyword: one, two and
three. We have assigned values to variables one and two at the same time when we
declared it, whereas variable three is declared but does not hold any value yet, so it's
value will be 'undefined'.

Declare variables in single line:

Multiple variables can also be declared in a single line separated by comma.

Example: Multiple variables in single line

var one = 1, two = 'two', three;

Declare variable without var keyword:

JavaScript allows variable declaration without var keyword. You must assign a value
when you declare a variable without var keyword.

Example: Variable without var keyword

one = 1;

two = 'two';

6
It is Not Recommended to declare a variable without var keyword. It can accidently
overwrite an existing global variable.

JavaScript allows multiple white spaces and line breaks when you declare a variable with
var keyword.

Example: Whitespace and line breaks

var
one
=

1,
two
=
"two"

C# or Java has strongly typed variables. It means variable must be declared with a
particular data type, which tells what type of data the variable will hold.

JavaScript variables are loosely-typed which means it does not require a data type to be
declared. You can assign any type of literal values to a variable e.g. string, integer, float,
boolean etc..

Example: Loosely Typed variables

var one =1; // numeric value

one = 'one'; // string value

one= 1.1; // decimal value

one = true; // Boolean value

one = null; // null value

Points to Remember :

1. Variable stores a single data value that can be changed later.

7
2. Variables can be defined using var keyword. Variables defined without var
keyword become global variables.
3. Variables must be initialized before using.
4. Multiple variables can be defined in a single line. e.g. var one = 1, two = 2, three =
"three";
5. Variables in JavaScript are loosely-typed variables. It can store value of any data
type through out it's life time.

Javascript Operators:

JavaScript includes operators as in other languages. An operator performs some operation


on single or multiple operands (data value) and produces a result. For example 1 + 2,
where + sign is an operator and 1 is left operand and 2 is right operand. + operator adds
two numeric values and produces a result which is 3 in this case.

Syntax:

<Left operand> operator <right operand>

<Left operand> operator

JavaScript includes following categories of operators.

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators

Arithmetic Operators:

Arithmetic operators are used to perform mathematical operations between numeric


operands.

Operator Description
+ Adds two numeric operands.
- Subtract right operand from left operand
* Multiply two numeric operands.
/ Divide left operand by right operand.
% Modulus operator. Returns remainder of two operands.
++ Increment operator. Increase operand value by one.
-- Decrement operator. Decrease value by one.

8
The following example demonstrates how arithmetic operators perform different tasks on
operands.

Example: Arithmetic Operator

var x = 5, y = 10, z = 15;

x + y; //returns 15

y - x; //returns 5

x * y; //returns 50

y / x; //returns 2

x % 2; //returns 1

x++; //returns 6

x--; //returns 4

+ operator performs concatenation operation when one of the operands is of string type.

The following example shows how + operator performs operation on operands of


different data types.

Example: + operator

var a = 5, b = "Hello ", c = "World!", d = 10;

a + b; // "5Hello "

b + c; // "Hello World!"

a + d; // 15

Comparison Operators:

JavaScript language includes operators that compare two operands and return Boolean
value true or false.
9
Operators Description
== Compares the equality of two operands without considering type.
=== Compares equality of two operands with type.
!= Compares inequality of two operands.
> Checks whether left side value is greater than right side value. If yes then
returns true otherwise false.
< Checks whether left operand is less than right operand. If yes then returns
true otherwise false.
>= Checks whether left operand is greater than or equal to right operand. If yes
then returns true otherwise false.
<= Checks whether left operand is less than or equal to right operand. If yes
then returns true otherwise false.

The following example demonstrates how comparison operators perform different tasks.

Example: Comparison Operators

var a = 5, b = 10, c = "5";


var x = a;

a == c; // returns true

a === c; // returns false

a == x; // returns true

a != b; // returns true

a > b; // returns false

a < b; // returns true

a >= b; // returns true

a <= b; // returns true

a >= c; // returns true

a <= c; // returns true

Logical Operators:

10
Logical operators are used to combine two or more conditions. JavaScript includes
following logical operators.

Operator Description
&& && is known as AND operator. It checks whether two operands are non-zero
(0, false, undefined, null or "" are considered as zero), if yes then returns 1
otherwise 0.
|| || is known as OR operator. It checks whether any one of the two operands is
non-zero (0, false, undefined, null or "" is considered as zero).
! ! is known as NOT operator. It reverses the boolean result of the operand (or
condition)
Example: Logical Operators

var a = 5, b = 10;

(a != b) && (a < b); // returns true

(a > b) || (a == b); // returns false

(a < b) || (a == b); // returns true

!(a < b); // returns false

!(a > b); // returns true

Assignment Operators:

JavaScript includes assignment operators to assign values to variables with less key
strokes.

Assignment Description
operators
= Assigns right operand value to left operand.
+= Sums up left and right operand values and assign the result to the
left operand.
-= Subtract right operand value from left operand value and assign the
result to the left operand.
*= Multiply left and right operand values and assign the result to the
left operand.
/= Divide left operand value by right operand value and assign the
result to the left operand.

11
%= Get the modulus of left operand divide by right operand and assign
resulted modulus to the left operand.
Example: Assignment operators

var x = 5, y = 10;

x = y; //x would be 10

x += 1; //x would be 11

x -= 1; //x would be 10

x *= 5; //x would be 50

x /= 5; //x would be 10

x %= 2; //x would be 0

Ternary Operator:

JavaScript includes special operator called ternary operator :? that assigns a value to a
variable based on some condition. This is like short form of if-else condition.

Syntax:

<condition> ? <value1> : <value2>;

Ternary operator starts with conditional expression followed by ? operator. Second part (
after ? and before : operator) will be executed if condition turns out to be true. If
condition becomes false then third part (after :) will be executed.

Example: Ternary operator

var a = 10, b = 5;

var c = a > b? a : b; // value of c would be 10


var d = a > b? b : a; // value of d would be 5

12
Points to Remember :

1. JavaScript includes operators that perform some operation on single or multiple


operands (data value) and produce a result.
2. JavaScript includes various categories of operators: Arithmetic operators,
Comparison operators, Logical operators, Assignment operators, Conditional
operators.
3. Ternary operator ?: is a conditional operator.

JavaScript Data Types:

JavaScript includes data types similar to other programming languages like Java or C#.
Data type indicates characteristics of data. It tells the compiler whether the data value is
numeric, alphabetic, date etc., so that it can perform the appropriate operation.

JavaScript includes primitive and non-primitive data types as per latest ECMAScript 5.1.

Primitive Data Types:

1. String
2. Number
3. Boolean
4. Null
5. Undefined

Non-primitive Data Type:

1. Object
2. Date
3. Array

Include quotation marks inside string:

Use quotation marks inside string value that does not match the quotation marks
surrounding the string value. For example, use single quotation marks if the whole string
is enclosed with double quotation marks and visa-versa.

13
Example: Quotes in string

var str1 = "This is 'simple' string";

var str2 = 'This is "simple" string';

If you want to include same quotes in a string value as surrounding quotes then use
backward slash (\) before quotation mark inside string value.

Example: Quotes in string

var str1 = "This is \"simple\" string";

var str2 = 'This is \'simple\' string';

Multiple strings can be concatenated using + operator.

A string can be treated as character array.

var str = 'Hello World';

str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o

str.length // 11

if-else condition in JavaScript:

JavaScript includes if-else conditional statements to control the program flow, similar to
other programming languages.

JavaScript includes following forms of if-else conditions:

1. if condition
2. if-else condition

14
3. else if condition

if condition:

Use if conditional statement if you want to execute something based on some condition.

Syntax:

if(condition expression)
{
// code to be executed if condition is true
}
Example: if condition

if( 1 > 0)
{
alert("1 is greater than 0");
}

if( 1 < 0)
{
alert("1 is less than 0");
}

In the above example, the first if statement contains 1 > 0 as conditional expression. The
conditional expression 1 > 0 will be evaluated to true, so an alert message "1 is greater
than 0" will be displayed, whereas conditional expression in second if statement will be
evaluated to false, so "1 is less than 0" alert message will not be displayed.

The same way, you can use variables in conditional expression.

Example: if condition

var mySal = 1000;


var yourSal = 500;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}

15
Note : curly braces { } is not required when if block contains only a single line to
execute.

Use comparison operators carefully when writing conditional expression. For example,
== and === is different.

Example: if condition

if(1=="1")
{
alert("== operator does not consider types of operands");
}

if(1==="1")
{
alert("=== operator considers types of operands");
}

else condition:

Use else statement when you want to execute the code every time when if condition
evaluates to false.

The else statement must follow if or else if statement. Multiple else block is NOT
allowed.

Syntax:

if(condition expression)
{
//Execute this code..
}
else{
//Execute this code..
}
Example: else condition

var mySal = 500;


var yourSal = 1000;
16
if( mySal > yourSal)
{
alert("My Salary is greater than your salary");
}
else
{
alert("My Salary is less than or equal to your salary");
}

else-if condition:

Use "else if" condition when you want to apply second level condition after if statement.

Syntax:

if(condition expression)
{
//Execute this code block
}
else if(condition expression){
//Execute this code block
}
Example: else if condition

var mySal = 500;


var yourSal = 1000;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
else if(mySal < yourSal)
{
alert("My Salary is less than your salary");
}

JavaScript allows multiple else if statements also.

Example: Multiple if-else conditions

17
var mySal = 500;
var yourSal = 1000;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
else if(mySal < yourSal)
{
alert("My Salary is less than your salary");
}
else if(mySal == yourSal)
{
alert("My Salary is equal to your salary");
}

We will learn about switch case in the next section.

switch statement in JavaScript:

The switch is a conditional statement like if statement. Switch is useful when you want to
execute one of the multiple code blocks based on the return value of a specified
expression.

Syntax:

switch(expression or literal value){


case 1:
//code to be executed
break;
case 2:
//code to be executed
break;
case n:
//code to be executed
break;
default:
//default code to be executed
//if none of the above case executed
}

18
Use break keyword to stop the execution and exit from the switch. Also, you
can write multiple statements in a case without using curly braces { }.

As per the above syntax, switch statement contains an expression or literal value. An
expression will return a value when evaluated. The switch can includes multiple cases
where each case represents a particular value. Code under particular case will be executed
when case value is equal to the return value of switch expression. If none of the cases
match with switch expression value then the default case will be executed.

Example: switch statement

var a = 3;

switch (a) {
case 1:
alert('case 1 executed');
break;
case 2:
alert("case 2 executed");
break;
case 3:
alert("case 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}

In the above example, switch statement contains a literal value as expression. So, the case
that matches a literal value will be executed, case 3 in the above example.

The switch statement can also include an expression. A case that matches the result of an
expression will be executed.

Example: switch statement

19
var a = 3;

switch (a/3) {
case 1:
alert("case 1 executed");
break;
case 2:
alert("case 2 executed");
break;
case 3:
alert("case 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}

In the above example, switch statement includes an expression a/3, which will return 1
(because a = 3). So, case 1 will be executed in the above example.

The switch can also contain string type expression.

Example: switch with string type

var str = "bill";

switch (str)
{
case "steve":
alert("This is Steve");
case "bill":
alert("This is Bill");
break;
case "john":
alert("This is John");
break;
default:
alert("Unknown Person");
break;

20
}

Multiple cases can be combined in a switch statement.

Example: combined switch cases

var a = 2;

switch (a) {
case 1:
case 2:
case 3:
alert("case 1, 2, 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}

for loop in JavaScript:

JavaScript includes for loop like Java or C#. Use for loop to execute code repeatedly.

Syntax:

for(initializer; condition; iteration)


{
// Code to be executed
}

The for loop requires following three parts.

Initializer: Initialize a counter variable to start with


Condition: specify a condition that must evaluate to true for next iteration
Iteration: increase or decrease counter

Example: for loop

21
for (var i = 0; i < 5; i++)
{
console.log(i);
}

Output:

01234

In the above example, var i = 0 is an initializer statement where we declare a variable i


with value 0. The second part, i < 5 is a condition where it checks whether i is less than 5
or not. The third part, i++ is iteration statement where we use ++ operator to increase the
value of i to 1. All these three parts are separated by semicolon ;.

The for loop can also be used to get the values for an array.

Example: for loop to access array

var arr = [10, 11, 12, 13, 14];

for (var i = 0; i < 5; i++)


{
console.log(arr[i]);
}

Output:

10 11 12 13 14

Please note that it is not mandatory to specify an initializer, condition and increment
expression into bracket. You can specify initializer before starting for loop. The condition
and increment statements can be included inside the block.

Example: for loop

var arr = [10, 11, 12, 13, 14];


var i = 0;

for (; ;) {

22
if (i >= 5)
break;

console.log(arr[i]);

i++;
}

Output:

10 11 12 13 14

Learn about while loop in the next section.

while loop:

JavaScript includes while loop to execute code repeatedly till it satisfies a specified
condition. Unlike for loop, while loop only requires condition expression.

Syntax:

while(condition expression)
{
/* code to be executed
till the specified condition is true */
}
Example: while loop

var i =0;

while(i < 5)
{
console.log(i);
i++;
}

Output:

01234

23
Make sure condition expression is appropriate and include increment or
decrement counter variables inside the while block to avoid infinite loop.

As you can see in the above example, while loop will execute the code block till i < 5
condition turns out to be false. Initialization statement for a counter variable must be
specified before starting while loop and increment of counter must be inside while block.

Do-while loop:

JavaScript includes another flavour of while loop, that is do-while loop. The do-while
loop is similar to while loop the only difference is it evaluates condition expression after
the execution of code block. So do-while loop will execute the code block at least once.

Syntax:

do{

//code to be executed

}while(condition expression)

Example: do-while loop

var i = 0;

do{

alert(i);
i++;

} while(i < 5)

Output:

01234

The following example shows that do-while loop will execute a code block even if the
condition turns out to be false in the first iteration.

24
Example: do-while loop

var i =0;

do{

alert(i);
i++;

} while(i > 1)

Output:

Points to Remember :

1. JavaScript while loop & do-while loop execute the code block repeatedly till
conditional expression returns true.
2. do-while loop executes the code at least once even if condition returns false.

Points to Remember :

1. JavaScript for loop is used to execute code repeatedly.


2. for loop includes three parts: initialization, condition and iteration.
e.g.for(initializer; condition; iteration){ ... }
3. The code block can be wrapped with { } brackets.
4. An initializer can be specified before starting for loop. The condition and
increment statements can be included inside the block.

Points to Remember :

1. The switch is a conditional statement like if statement.


2. A switch statement includes literal value or is expression based
3. A switch statement includes multiple cases that include code blocks to execute.
4. A break keyword is used to stop the execution of case block.
25
5. A switch case can be combined to execute same code block for multiple cases.

Points to Remember :

1. Use if-else conditional statements to control the program flow.


2. JavaScript includes three forms of if condition: if condition, if else condition and
else if condition.
3. The if condition must have conditional expression in brackets () followed by
single statement or code block wrapped with { }.
4. 'else if' statement must be placed after if condition. It can be used multiple times.
5. 'else' condition must be placed only once at the end. It must come after if or else if
statement.

strict mode:

JavaScript is a loosely typed (dynamic) scripting language. If you have worked with
server side languages like Java or C#, you must be familiar with the strictness of the
language. For example, you expect the compiler to give an error if you have used a
variable before defining it.

JavaScript allows strictness of code using "use strict" with ECMAScript 5 or later. Write
"use strict" at the top of JavaScript code or in a function.

Example: strict mode

"use strict";

var x = 1; // valid in strict mode


y = 1; // invalid in strict mode

Function in JavaScript:

JavaScript provides functions similar to most of the scripting and programming


languages.

In JavaScript, a function allows you to define a block of code, give it a name and then
execute it as many times as you want.

26
A JavaScript function can be defined using function keyword.

Syntax:

//defining a function
function <function-name>()
{
// code to be executed
};

//calling a function
<function-name>();

The following example shows how to define and call a function in JavaScript.

Example: Define and call function

function ShowMessage() {
alert("Hello World!");
}

ShowMessage();

In the above example, we have defined a function named ShowMessage that displays a
popup message "Hello World!". This function can be execute using () operator e.g.
ShowMessage().

Function Parameters:

A function can have one or more parameters, which will be supplied by the calling code
and can be used inside a function. JavaScript is a dynamic type scripting language, so a
function parameter can have value of any data type.

Example: Function parameters

function ShowMessage(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs");

27
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);

You can pass less or more arguments while calling a function. If you pass less arguments
then rest of the parameters will be undefined. If you pass more arguments then additional
arguments will be ignored.

Example: Function parameters

function ShowMessage(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs", "Mr."); // display Hello Steve Jobs


ShowMessage("Bill"); // display Hello Bill undefined
ShowMessage(); // display Hello undefined undefined

The arguments Object:

All the functions in JavaScript can use arguments object by default. An arguments object
includes value of each parameter.

The arguments object is an array like object. You can access its values using index
similar to array. However, it does not support array methods.

Example: arguments object

function ShowMessage(firstName, lastName) {


alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Steve", "Jobs");

ShowMessage("Bill", "Gates");

ShowMessage(100, 200);

An arguments object is still valid even if function does not include any parameters.

28
Example: arguments object

function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Steve", "Jobs"); // display Hello Steve Jobs

An arguments object can be iterated using for loop.

Example: Iterate all arguments

function ShowMessage() {

for(var i = 0; i < arguments.length; i++){


alert(arguments[i]);
}
}

ShowMessage("Steve", "Jobs");

Return Value:

A function can return zero or one value using return keyword.

Example: Return value from function

function Sum(val1, val2) {


return val1 + val2;
};

var result = Sum(10,20); // returns 30

function Multiply(val1, val2) {


console.log( val1 * val2);
};

result = Multiply(10,20); // undefined

29
In the above example, a function named Sum adds val1 & val2 and return it. So the
calling code can get the return value and assign it to a variable. The second function
Multiply does not return any value, so result variable will be undefined.

A function can return another function in JavaScript.

Example: function returning a function

function multiple(x) {

function fn(y)
{
return x * y;
}

return fn;
}

var triple = multiple(3);


triple(2); // returns 6
triple(3); // returns 9

Function Expression:

JavaScript allows us to assign a function to a variable and then use that variable as a
function. It is called function expression.

Example: Function expression

var add = function sum(val1, val2) {


return val1 + val2;
};

var result1 = add(10,20);


var result2 = sum(10,20); // not valid

Anonymous Function:

Anonymous function is useful in passing callback function, creating closure or


Immediately invoked function expression.
30
JavaScript allows us to define a function without any name. This unnamed function is
called anonymous function. Anonymous function must be assigned to a variable.

Example: Anonymous Function

var showMessage = function (){


alert("Hello World!");
};

showMessage();

var sayHello = function (firstName) {


alert("Hello " + firstName);
};

showMessage();

sayHello("Bill");

Nested Function:

In JavaScript, a function can have one or more inner functions. These nested functions
are in the scope of outer function. Inner function can access variables and parameters of
outer function. However, outer function cannot access variables defined inside inner
functions.

Example: Nested Function

function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}

return SayHello();
}

ShowMessage("Steve");

31
Closure in JavaScript:

Closure is one of important concept in JavaScript. It is widely discussed and still


confused concept. Let's understand what the closure is.

First of all, let's see the definition of the Closure given by Douglas Crockford:
crockford.com/javascript/private.html

Closure means that an inner function always has access to the vars and parameters of its
outer function, even after the outer function has returned.

You have learned that we can create nested functions in JavaScript. Inner function can
access variables and parameters of an outer function (however, cannot access arguments
object of outer function). Consider the following example.

function OuterFunction() {

var outerVariable = 1;

function InnerFunction() {
alert(outerVariable);
}

InnerFunction();
}

In the above example, InnerFunction() can access outerVariable.

Now, as per the definition above, InnerFunction() can access outerVariable even if it will
be executed separately. Concider the following example.

Example: Closure

function OuterFunction() {

var outerVariable = 100;

function InnerFunction() {
alert(outerVariable);
}

32
return InnerFunction;
}
var innerFunc = OuterFunction();

innerFunc(); // 100

In the above example, return InnerFunction; returns InnerFunction from OuterFunction


when you call OuterFunction(). A variable innerFunc reference the InnerFunction() only,
not the OuterFunction(). So now, when you call innerFunc(), it can still access
outerVariable which is declared in OuterFunction(). This is called Closure.

A function can return another function in JavaScript. A function which is


assigned to a variable is called function expression.

One important characteristic of closure is that outer variables can keep their states
between multiple calls. Remember, inner function does not keep the separate copy of
outer variables but it reference outer variables, that means value of the outer variables
will be changed if you change it using inner function.

Example: Closure

function Counter() {
var counter = 0;

function IncreaseCounter() {
return counter += 1;
};

return IncreaseCounter;
}

var counter = Counter();


alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
alert(counter()); // 4

33
In the above example, outer function Counter returns the reference of inner function
IncreaseCounter(). IncreaseCounter increases the outer variable counter to one. So calling
inner function multiple time will increase the counter to one each time.

Closure is valid in multiple levels of inner functions.

Example: Closure

function Counter() {

var counter = 0;

setTimeout( function () {
var innerCounter = 0;
counter += 1;
alert("counter = " + counter);

setTimeout( function () {
counter += 1;
innerCounter += 1;
alert("counter = " + counter + ", innerCounter = " + innerCounter)
}, 500);

}, 1000);
};

Counter();

As per the closure definition, if inner function access the variables of outer function then
only it is called closure.

The following is not a closure.

var Counter = (function () {


var i = 0;
return { counter : i += 1 };
})();

When to use Closure?

34
Closure is useful in hiding implementation detail in JavaScript. In other words, it can be
useful to create private variables or functions.

The following example shows how to create private functions & variable.

Example: Closure

var counter = (function() {


var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();

alert(counter.value()); // 0
counter.increment();
counter.increment();
alert(counter.value()); // 2
counter.decrement();
alert(counter.value()); // 1

In the above example, increment(), decrement() and value() becomes public function
because they are included in the return object, whereas changeBy() function becomes
private function because it is not returned and only used internally by increment() and
decrement().

Points to Remember :

1. JavaScript a function allows you to define a block of code, give it a name and then
execute it as many times as you want.

35
2. A function can be defined using function keyword and can be executed using ()
operator.
3. A function can include one or more parameters. It is optional to specify function
parameter values while executing it.
4. JavaScript is a loosely-typed language. A function parameter can hold value of
any data type.
5. You can specify less or more arguments while calling function.
6. All the functions can access arguments object by default instead of parameter
names.
7. A function can return a literal value or another function.
8. A function can be assigned to a variable with different name.
9. JavaScript allows you to create anonymous functions that must be assigned to a
variable.

Scope in JavaScript:

Scope in JavaScript defines accessibility of variables, objects and functions.

There are two types of scope in JavaScript.

1. Global scope
2. Local scope

Global scope:

Variables declared outside of any function become global variables. Global variables can
be accessed and modified from any function.

Example: Global variable

<script>

var userName = "Bill";

function modifyUserName()
{
userName = "Steve";
};

36
function showUserName()
{
alert(userName);
};

alert(userName); // display Bill

modifyUserName();
showUserName();// display Steve

</script>

In the above example, the variable userName becomes a global variable because it is
declared outside of any function. A modifyUserName() function modifies userName as
userName is a global variable and can be accessed inside any function. The same way,
showUserName() function displays current value of userName variable. Changing value
of global variable in any function will reflect throughout the program.

Note: variables declared inside a function without var keyword also become global
variables.

Example: Global variable

<script>

function createUserName()
{
userName = "Bill";
}

function modifyUserName()
{
if(userName)
userName = "Steve";
};

function showUserName()
{
alert(userName);
}

createUserName();

37
showUserName(); // Bill

modifyUserName();
showUserName(); // Steve

</script>

In the above example, variable userName is declared without var keyword inside
createUserName(), so it becomes global variable automatically after calling
createUserName() for the first time.

Note : A userName variable will become global variable only after createUserName() is
called at least once. Calling showUserName() before createUserName() will throw an
exception "userName is not defined".

Local scope:

Variables declared inside any function with var keyword are called local variables. Local
variables cannot be accessed or modified outside the function declaration.

Example: Local scope

<script>

function createUserName()
{
var userName = "Bill";
}

function showUserName()
{
alert(userName);
}

createUserName();
showUserName(); // throws error: userName is not defined

</script>

Function parameters are considered as local variables.

38
In the above example, userName is local to createUserName() function. It cannot be
accessed in showUserName() function or any other functions. It will throw an error if you
try to access a variable which is not in the local or global scope.

If local variable and global variable have same name then changing value of one variable
does not affect on the value of another variable.

Example: Scope

var userName = "Bill";

function ShowUserName()
{
var userName = "Steve";

alert(userName); // "Steve"
}

ShowUserName();

alert(userName); // Bill

No Block level scope:

JavaScript does not allow block level scope inside { }. For example, variables defined in
if block can be accessed outside if block, inside a function.

Example: No block level scope

Function NoBlockLevelScope(){

if (1 > 0)
{
var myVar = 22;

alert(myVar);
}

NoBlockLevelScope();
39
Points to Remember :

1. JavaScript has global scope and local scope.


2. Variables declared and initialized outside any function become global variables.
3. Variables declared and initialized inside function becomes local variables to that
function.
4. Variables declared without var keyword inside any function becomes global
variables automatically.
5. Global variables can be accessed and modified anywhere in the program.
6. Local variables cannot be accessed outside the function declaration.
7. Global variable and local variable can have same name without affecting each
other.
8. JavaScript does not allow block level scope inside { } brackets.

Hoisting:

Hoisting is a concept in JavaScript, not a feature. In other scripting or server side


languages, variables or functions must be declared before using it.

In JavaScript, variable and function names can be used before declaring it. The
JavaScript compiler moves all the declarations of variables and functions at the top so
that there will not be any error. This is called hoisting.

Example: Hoisting

x = 1;

alert('x = ' + x); // display x = 1

var x;

The following figure illustrates hoisting.

40
JavaScript Hoisting

Also, a variable can be assigned to another variable as shown below.

Example: Hoisting

x = 1;
y = x;

alert('x = ' + x);


alert('y = ' + y);

var x;
var y;

Hoisting is only possible with declaration but not the initialization. JavaScript will not
move variables that are declared and initialized in a single line.

Example: Hoisting not applicable for initialized variables

alert('x = ' + x); // display x = undefined

var x = 1;

As you can see in the above example, value of x will be undefined because var x = 1 is
not hoisted.

Hoisting of function:

JavaScript compiler moves the function definition at the top in the same way as variable
declaration.

Example: Function Hoisting

41
alert(Sum(5, 5)); // 10

function Sum(val1, val2)


{
return val1 + val2;
}

Please note that JavaScript compiler does not move function expression.

Example: Hoisting not applicable on function expression

Add(5, 5); // error

var Add = function Sum(val1, val2)


{
return val1 + val2;
}

Hoisting Functions Before Variables:

JavaScript compiler moves a function's definition before variable declaration. The


following example proves it.

Example: Function Hoisting before variables

alert(UseMe);

var UseMe;

function UseMe()
{
alert("UseMe function called");
}

As per above example, it will display UseMe function definition. So the function moves
before variables.

42
Points to Remember :

1. JavaScript compiler moves variables and function declaration to the top and this is
called hoisting.
2. Only variable declarations move to the top, not the initialization.
3. Functions definition moves first before variables.

JavaScript Array:

We have learned that a variable can hold only one value, for example var i = 1, we can
assign only one literal value to i. We cannot assign multiple literal values to a variable i.
To overcome this problem, JavaScript provides an array.

An array is a special type of variable, which can store multiple values using special
syntax. Every value is associated with numeric index starting with 0. The following
figure illustrates how an array stores values.

JavaScript Array

Array Initialization:

An array in JavaScript can be defined and initialized in two ways, array literal and Array
constructor syntax.

Array Literal:

Array literal syntax is simple. It takes a list of values separated by a comma and enclosed
in square brackets.

Syntax:

var <array-name> = [element0, element1, element2,... elementN];

The following example shows how to define and initialize an array using array literal
syntax.

Example: Declare and initialize an array

43
var stringArray = ["one", "two", "three"];

var numericArray = [1, 2, 3, 4];

var decimalArray = [1.1, 1.2, 1.3];

var booleanArray = [true, false, false, true];

var mixedArray = [1, "two", "three", 4];

JavaScript array can store multiple element of different data types. It is not required to
store value of same data type in an array.

Array Constructor:

You can initialize an array with Array constructor syntax using new keyword.

The Array constructor has following three forms.

Syntax:

var arrayName = new Array();

var arrayName = new Array(Number length);

var arrayName = new Array(element1, element2, element3,... elementN);

As you can see in the above syntax, an array can be initialized using new keyword, in the
same way as an object.

The following example shows how to define an array using Array constructor syntax.

Example: Array constructor syntax

var stringArray = new Array();


stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";

var numericArray = new Array(3);

44
numericArray[0] = 1;
numericArray[1] = 2;
numericArray[2] = 3;

var mixedArray = new Array(1, "two", 3, "four");

Please note that array can only have numeric index (key). Index cannot be of string or
any other data type. The following syntax is incorrect.

Example: Incorrect array index of string type

var stringArray = new Array();

stringArray["one"] = "one";
stringArray["two"] = "two";
stringArray["three"] = "three";
stringArray["four"] = "four";

Accessing Array Elements:

An array elements (values) can be accessed using index (key). Specify an index in square
bracket with array name to access the element at particular index. Please note that index
of an array starts from zero in JavaScript.

Example: Access Array Elements

var stringArray = new Array("one", "two", "three", "four");

stringArray[0]; // returns "one"


stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3]; // returns "four"

var numericArray = [1, 2, 3, 4];


numericArray[0]; // returns 1
numericArray[1]; // returns 2
numericArray[2]; // returns 3
numericArray[3]; // returns 4

45
Array Properties:

Array includes "length" property which returns number of elements in the array.

Use for loop to access all the elements of an array using length property.

Example: Access Array using for loop

var stringArray = new Array("one", "two", "three", "four");

for (var i = 0; i < stringArray.length ; i++)


{
stringArray[i];
}

null and undefined in JavaScript:

As we have seen in the variable section that we can assign any primitive or non-primitive
type of value to a variable. JavaScript includes two additional primitive type values - null
and undefined, that can be assigned to a variable that has special meaning.

null:

You can assign null to a variable to denote that currently that variable does not have any
value but it will have later on. A null means absence of a value.

Example: null

var myVar = null;

alert(myVar); // null

In the above example, null is assigned to a variable myVar. It means we have defined a
variable but have not assigned any value yet, so value is absence.

null is of object type e.g. typeof null will return "object"

46
If you try to find DOM element using document.getElelementByID for example, and if
element is found then it will return null. So it is recommended to check for null before
doing something with that element.

Example: null

var saveButton = document.getElementById("save");

if (saveButton !== null)


saveButton.submit();

A null value evaluates to false in conditional expression. So you don't have to use
comparison operators like === or !== to check for null values.

Example: null in conditional expression

var myVar = null;

if (myVar)
alert("myVar is not null');
else
alert("myVar is null" );

undefined:

Undefined is also a primitive value in JavaScript. A variable or an object has an


undefined value when no value is assigned before using it. So you can say that undefined
means lack of value or unknown value.

Example: undefined

var myVar;

alert(myVar); // undefined

undefined is a token. typeof undefined will return undefined not an object.

In the above example, we have not assigned any value to a variable named 'myVar'. A
variable 'myVar' lacks a value. So it is undefined.
47
You will get undefined value when you call a non-existent property or method of an
object.

Example: undefined

function Sum(val1, val2)


{
var result = val1 + val2;
}

var result = Sum(5, 5);


alert(result);// undefined

In the above example, a function Sum does not return any result but still we try to assign
its resulted value to a variable. So in this case, result will be undefined.

If you pass less arguments in function call then, that parameter will have undefined value.

Example: undefined

function Sum(val1, val2)


{
return val1 + val2; // val2 is undefined
}

Sum(5);

An undefined evaluates to false when used in conditional expression.

Example: undefined in conditional expression

var myVar;

if (myVar)
alert("myVar evaluates to true");
else
alert("myVar evaluates to false");

48
null and undefined is one of the main reasons to produce a runtime error in the JavaScript
application. This happens if you don't check the value of unknown return variables before
using it. If you are not sure that a variable will always have some value, the best practice
is to check the value of variables for null or undefined before using them.

Points to Remember :

1. null and undefined are primitive values in JavaScript.


2. A null value means absence.
3. An undefined value means lack of value.
4. A null or undefined value evalutes to false in conditional expression.

Points to Remember :

1. An array is a special type of variable that stores multiple values using a special
syntax.
2. An array can be created using array literal or Array constructor syntax.
3. Array literal syntax: var stringArray = ["one", "two", "three"];
4. Array constructor syntax:var numericArray = new Array(3);
5. A single array can store values of different data types.
6. An array elements (values) can be accessed using zero based index (key). e.g.
array[0].
7. An array index must be numeric.
8. Array includes length property and various methods to operate on array objects.

49

Das könnte Ihnen auch gefallen