Javascript Notes
Javascript Notes
JavaScript is a loosely-typed client side scripting language that executes in the user's
browser.
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:
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:
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
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
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
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.
var userPreference;
} else {
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
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>;
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'.
JavaScript allows variable declaration without var keyword. You must assign a value
when you declare a 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.
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..
Points to Remember :
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:
Syntax:
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
Arithmetic Operators:
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.
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.
Example: + operator
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.
a == c; // returns true
a == x; // returns true
a != b; // 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;
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:
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.
var a = 10, b = 5;
12
Points to Remember :
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.
1. String
2. Number
3. Boolean
4. Null
5. Undefined
1. Object
2. Date
3. Array
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
If you want to include same quotes in a string value as surrounding quotes then use
backward slash (\) before quotation mark inside string value.
str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o
str.length // 11
JavaScript includes if-else conditional statements to control the program flow, similar to
other programming languages.
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.
Example: if condition
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
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
17
var mySal = 500;
var yourSal = 1000;
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:
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.
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.
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.
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
}
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");
}
JavaScript includes for loop like Java or C#. Use for loop to execute code repeatedly.
Syntax:
21
for (var i = 0; i < 5; i++)
{
console.log(i);
}
Output:
01234
The for loop can also be used to get the values for an array.
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.
for (; ;) {
22
if (i >= 5)
break;
console.log(arr[i]);
i++;
}
Output:
10 11 12 13 14
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)
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 :
Points to Remember :
Points to Remember :
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.
"use strict";
Function in JavaScript:
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.
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.
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.
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.
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]);
}
function ShowMessage() {
ShowMessage("Steve", "Jobs");
Return Value:
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.
function multiple(x) {
function fn(y)
{
return x * y;
}
return fn;
}
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.
Anonymous Function:
showMessage();
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.
function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}
return SayHello();
}
ShowMessage("Steve");
31
Closure in JavaScript:
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();
}
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() {
function InnerFunction() {
alert(outerVariable);
}
32
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc(); // 100
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;
}
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.
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.
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
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:
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.
<script>
function modifyUserName()
{
userName = "Steve";
};
36
function showUserName()
{
alert(userName);
};
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.
<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.
<script>
function createUserName()
{
var userName = "Bill";
}
function showUserName()
{
alert(userName);
}
createUserName();
showUserName(); // throws error: userName is not defined
</script>
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
function ShowUserName()
{
var userName = "Steve";
alert(userName); // "Steve"
}
ShowUserName();
alert(userName); // Bill
JavaScript does not allow block level scope inside { }. For example, variables defined in
if block can be accessed outside if block, inside a function.
Function NoBlockLevelScope(){
if (1 > 0)
{
var myVar = 22;
alert(myVar);
}
NoBlockLevelScope();
39
Points to Remember :
Hoisting:
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;
var x;
40
JavaScript Hoisting
Example: Hoisting
x = 1;
y = x;
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.
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.
41
alert(Sum(5, 5)); // 10
Please note that JavaScript compiler does not move function expression.
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:
The following example shows how to define and initialize an array using array literal
syntax.
43
var stringArray = ["one", "two", "three"];
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.
Syntax:
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.
44
numericArray[0] = 1;
numericArray[1] = 2;
numericArray[2] = 3;
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.
stringArray["one"] = "one";
stringArray["two"] = "two";
stringArray["three"] = "three";
stringArray["four"] = "four";
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.
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.
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
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.
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
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.
if (myVar)
alert("myVar is not null');
else
alert("myVar is null" );
undefined:
Example: undefined
var myVar;
alert(myVar); // undefined
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
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
Sum(5);
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 :
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