JavaScript Basics and Setup Guide
JavaScript Basics and Setup Guide
TECHNOLOGIES
JavaScript Tutorial
Welcome to JavaScript tutorials section. JavaScript is a loosely-typed client side
scripting language that executes in the user's web browser. A web page without
JavaScript is unimaginable today. There are many open source application
development frameworks based on JavaScript.
These tutorials will help you learn JavaScript step by step starting from the basics
to an advanced level. These tutorials are broken down into sections where each
section contains a number of related topics that are packed with easy to
understand explanations, real-world examples, tips, notes and useful
references.
Each tutorial includes practical examples. You can edit and see the result real
time with your Code Editor.
What is JavaScript
JavaScript is a loosely-typed client side scripting language that executes in the
user's browser. JavaScript interact with html elements (DOM elements) in order
to make interactive web user interface.
JavaScript implements ECMAScript standards, which includes core features
based on ECMA-262 specification as well as other features which are not based
on ECMAScript standards.
[Link]
hikmat.kazimi12@[Link]
1
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript Example
JavaScript can be used in various activities like data validation, display popup
messages, handling different events of DOM elements, modifying style of DOM
elements etc. The following sample form uses JavaScript to validate data and
change color of form.
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.
Eich eventually decided that a loosely-typed scripting language suited the
environment and audience, web designers and developers who needed to be
able to tie into page elements (such as forms, or frames, or images) without a
bytecode compiler or knowledge of object-oriented software design. The
dynamic nature of the language led to it being named "LiveScript" but was
quickly renamed to "JavaScript" Know more about JavaScript history.
[Link]
hikmat.kazimi12@[Link]
2
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript Engine
JavaScript engine in the browser interprets, compiles and executes JavaScript
code which is in a web page. It does memory management, JIT compilation, type
system etc. Each browser includes different JavaScript engines.
C# Java JavaScript
Strongly-Typed Strongly-Typed Loosely-Typed
Static Static Dynamic
Classical Inheritance Classical Inheritance Prototypal
Classes Classes Functions
Constructors Constructors Functions
Methods Methods Functions
[Link]
hikmat.kazimi12@[Link]
3
+93(0)789097059
Smart in City
TECHNOLOGIES
Advantages of JavaScript
JavaScript is easy to learn.
It executes on client's browser, so eliminates server side processing.
It executes on any OS.
JavaScript can be used with any type of web page e.g. PHP, [Link],
Perl etc.
Performance of web page increases due to client side execution.
JavaScript code can be minified to decrease loading time from server.
Many JavaScript based application frameworks are available in the
market to create Single page web applications e.g. ExtJS, AngularJS,
KnockoutJS etc.
[Link]
hikmat.kazimi12@[Link]
4
+93(0)789097059
Smart in City
TECHNOLOGIES
Script Tag
Any type of client side script can be written inside <script> tag in html. The script
tag identifies a block of script code in the html page. It also loads a script file
with src attribute.
The JavaScript code can also be embedded in <script> tag as shown below.
Example: <script> tag
<script>
</script>
Html 4.x requires type attribute in script tag. The type attribute is used to
identify the language of script code embedded within script tag. This is specified
as MIME type e.g. text/javascript, text/ecmascript, text/vbscript etc. So, for the
JavaScript code, specify type="text/javascript" in the script tag in html 4.x page.
<script type="text/javascript">
</script>
Html 5 page does not require type attribute in the <script> tag, because in
HTML 5 the default script language is JavaScript
[Link]
hikmat.kazimi12@[Link]
5
+93(0)789097059
Smart in City
TECHNOLOGIES
Script File
If you don't want to write JavaScript between script tag in a web page, then you
can also write JavaScript code in a separate file with .js extension and include it
in a web page using <script> tag and reference the file via src attribute.
<script src="/[Link]"></script>
The script tag can appear any number of times in the <head> or <body> tag.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JavaScript Demo</title>
<script>
//write JavaScript code here.
</script>
<script src="/[Link]"></<script> @* External
JavaScript file *@
</head>
<body>
<h1> JavaScript Tutorials</h1>
</body>
</html>
[Link]
hikmat.kazimi12@[Link]
6
+93(0)789097059
Smart in City
TECHNOLOGIES
The browser loads all the scripts in head tag before loading and rendering body
html. It is recommended to include scripts before ending body tag if scripts are
not required while window is loading.
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JavaScript Demo</title>
</head>
<body>
<h1> JavaScript Tutorials by Hikmat Kazimi</h1>
<p>This is JavaScript sample. </p>
<script>
//write JavaScript code here..
</script>
<script src="/[Link]"></<script> @* External JavaScript file *@
</body>
</html>
Thus, you can write JavaScript in script tag at appropriate places in a web page.
[Link]
hikmat.kazimi12@[Link]
7
+93(0)789097059
Smart in City
TECHNOLOGIES
Points to Remember :
1. JavaScript code must be written within <script> tag.
2. External JavaScript file (.js) can be referenced using
<script src="/[Link]"></script> where src attribute is used
to specify the full path of .js file.
3. Html5 standard does not required type="text/javascript" attribute, whereas prior
html standards require type attribute.
4. The <script> tag can be added into <head> or <body> tag.
5. The script included into <head> tag may not be able to access DOM elements
because <head> loads before <body>. Write script before ending of </body> tag
if script code needs to access DOM elements.
[Link]
hikmat.kazimi12@[Link]
8
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript Overview
Learn some important characteristics of JavaScript syntax in this section.
Character Set
JavaScript uses the Unicode character set and so allows almost all characters,
punctuations, and symbols.
Case Sensitive
JavaScript is a case sensitive scripting language. It means functions, variables
and keywords are case sensitive. For example, VAR is different from var, John is
not equal to john.
String
String is a text in JavaScript. A text content must be enclosed in double or single
quotation marks.
Example: string
<script>
</script>
Number
JavaScript allows you to work with any kind of numbers like integer, float,
hexadecimal etc. Number must NOT be wrapped in quotation marks.
Integer: 1000
Float: 10.2
[Link]
hikmat.kazimi12@[Link]
9
+93(0)789097059
Smart in City
TECHNOLOGIES
Boolean
As in other languages, JavaScript also includes true or false as a boolean value.
Semicolon
JavaScript statements are separated by a semicolon. However, it is not
mandatory to end every statement with a semicolon but it is recommended.
For example, JavaScript considers three different statements for following:
two=2; three=3;
White space
JavaScript ignores multiple spaces and tabs.
The following statements are same.
Example: JavaScript ignores whitespaces
var >var >var >
Comments
A comment is a single or multiple lines, which give some information about the
current program. Comments are not for execution.
Write comment after double slashes // or write multiple lines of comments
between/* and */
Example: code comment
var // this is a single line comment
/* this
is multi line
comment*/
var two = 2;
var three = 3;
[Link]
hikmat.kazimi12@[Link]
10
+93(0)789097059
Smart in City
TECHNOLOGIES
Keywords
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
Points to Remember:
1. JavaScript uses unicode characterset.
2. JavaScript is case sensitive.
3. JavaScript string must be enclosed in double quotation mark (") or single quotation
mark (').
4. JavaScript Number can store integer, float, hexadecimal value without enclosing
it in quotation marks.
5. JavaScript boolean value stores true or false.
6. Every statement in JavaScript can be separated using semicolon (;). It is not
mandatory but recommended to use semicolon at the end of each statement.
7. JavaScript ignores multiple white spaces.
8. A multi line comment can be wrapped between /* and */. Single line comment
can start with //.
9. JavaScript keywords are reserved words. Do not use them as variable or function
names.
[Link]
hikmat.kazimi12@[Link]
11
+93(0)789097059
Smart in City
TECHNOLOGIES
Alert Box
Use alert() function to display a popup message to the user. This popup will
have OK button to close the popup.
Example: Alert Box
alert("This is alert box!"); // display string message
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 Box
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.
[Link]
hikmat.kazimi12@[Link]
12
+93(0)789097059
Smart in City
TECHNOLOGIES
Prompt Box
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().
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]);
if (age != null) {
alert("You have entered " + age + " 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 [Link](), [Link]() and
[Link]().
[Link]
hikmat.kazimi12@[Link]
13
+93(0)789097059
Smart in City
TECHNOLOGIES
Points to Remember:
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.
[Link]
hikmat.kazimi12@[Link]
14
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript 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.
Syntax:
var <variable-name>;
var <variable-name> = <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 a Single Line
Multiple variables can also be declared in a single line separated by comma.
Example: Multiple Variables in a Single Line
var two = 'two', three;
[Link]
hikmat.kazimi12@[Link]
15
+93(0)789097059
Smart in City
TECHNOLOGIES
two = 'two';
Note:
It is Not Recommended to declare a variable without var keyword. It can
accidently overwrite an existing global variable.
Scope of the variables declared without var keyword become global irrespective
of where it is declared. Global variables can be accessed from anywhere in the
web page. Visit Scope for more information.
1,
two
=
"two"
[Link]
hikmat.kazimi12@[Link]
16
+93(0)789097059
Smart in City
TECHNOLOGIES
Loosely-typed Variables
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 // numeric value
Points to Remember:
Variable stores a single data value that can be changed later.
Variables can be defined using var keyword. Variables defined
without var keyword become global variables.
Variables must be initialized before using.
Multiple variables can be defined in a single line. e.g. var two =
2, three = "three";
Variables in JavaScript are loosely-typed variables. It can store value of
any data type through out it's life time.
[Link]
hikmat.kazimi12@[Link]
17
+93(0)789097059
Smart in City
TECHNOLOGIES
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
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.
[Link]
hikmat.kazimi12@[Link]
18
+93(0)789097059
Smart in City
TECHNOLOGIES
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
a + b; // "5Hello "
b + c; // "Hello World!"
a + d; // 15
[Link]
hikmat.kazimi12@[Link]
19
+93(0)789097059
Smart in City
TECHNOLOGIES
Comparison Operators
JavaScript language includes operators that compare two operands and return
Boolean value true or false.
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 == x; // returns true
a != b; // returns true
[Link]
hikmat.kazimi12@[Link]
20
+93(0)789097059
Smart in City
TECHNOLOGIES
Logical Operators
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)
[Link]
hikmat.kazimi12@[Link]
21
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
%= Get the modulus of left operand divide by right operand and
assign resulted modulus to the left operand.
x = y; //x would be 10
x += 1; //x would be 6
x -= 1; //x would be 4
x *= 5; //x would be 25
x /= 5; //x would be 1
x %= 2; //x would be 1
[Link]
hikmat.kazimi12@[Link]
22
+93(0)789097059
Smart in City
TECHNOLOGIES
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>;
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.
[Link]
hikmat.kazimi12@[Link]
23
+93(0)789097059
Smart in City
TECHNOLOGIES
alert(myVar); // Hikmat
In the above example, myVar will hold last assigned value to it that is string
"Hikmat".
[Link]
hikmat.kazimi12@[Link]
24
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript - String
String is a primitive data type in JavaScript. A string is textual content. It must be
enclosed in single or double quotation marks.
Example: String literal
"Hello World"
'Hello World'
A string can also be treated like zero index based character array.
str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o
[Link] // 11
[Link]
hikmat.kazimi12@[Link]
25
+93(0)789097059
Smart in City
TECHNOLOGIES
Since, string is character index, it can be accessed using for loop and for-of loop.
for(var ch of str)
[Link](ch);
Concatenation
A string is immutable in JavaScript, it can be concatenated using plus (+)
operator in JavaScript.
Example: String concatenation
var str = 'Hello ' + "World " + 'from ' + 'Smart in City ';
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";
[Link]
hikmat.kazimi12@[Link]
26
+93(0)789097059
Smart in City
TECHNOLOGIES
String object
Above, we assigned a string literal to a variable. JavaScript allows you to create
a String object using the new keyword, as shown below.
// or
In the above example, JavaScript returns String object instead of primitive string
type. It is recommended to use primitive string instead of String object.
Caution:
Be careful while working with String object because comparison of string objects
using == operator compares String objects and not the values. Consider the
following example.
str1 == str2; // false - because str1 and str2 are two different
objects
str1 == str3; // true
str1 === str4; // true
typeof(str1); // object
typeof(str3); //string
[Link]
hikmat.kazimi12@[Link]
27
+93(0)789097059
Smart in City
TECHNOLOGIES
Points to Remember:
1. JavaScript string must be enclosed in double or single quotes (" " or ' ').
2. String can be assigned to a variable using = operator.
3. Multiple strings can be concatenated using + operator.
4. A string can be treated as character array.
5. Use back slash (\) to include quotation marks inside string.
6. String objects can be created using new keyword.
e.g. var str = new String();
7. String methods are used to perform different task on strings.
[Link]
hikmat.kazimi12@[Link]
28
+93(0)789097059
Smart in City
TECHNOLOGIES
String Properties
Property Description
length Returns the length of the string.
String Methods
Method Description
charAt(position) Returns the character at the specified position (in
Number).
charCodeAt(position) Returns a number indicating the Unicode value of the
character at the given position (in Number).
concat([string,,]) Joins specified string literal values (specify multiple strings
separated by comma) and returns a new string.
[Link]
hikmat.kazimi12@[Link]
29
+93(0)789097059
Smart in City
TECHNOLOGIES
Method Description
search(RegExp) Search for a match based on specified regular expression.
substring(start, end) Returns the characters in a string between start and end
indexes.
toLocaleLowerCase() Converts a string to lower case according to current locale.
[Link]
hikmat.kazimi12@[Link]
30
+93(0)789097059
Smart in City
TECHNOLOGIES
Method Description
anchor() Creates an HTML anchor <a>element around string value.
[Link]
hikmat.kazimi12@[Link]
31
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript - Number
The Number is a primitive data type in JavaScript. Number type represents
integer, float, hexadecimal, octal or exponential value. First character in a
Number type must be an integer value and it must not be enclosed in quotation
marks.
Example: Number in JavaScript
var int = 100;
var float = 100.5;
var hex = 0xfff;
var exponential = 2.56e3;
var octal = 030;
Number object
JavaScript also provides Number object which can be used
with new keyword.
var hex = new Number(0xfff);
[Link]
hikmat.kazimi12@[Link]
32
+93(0)789097059
Smart in City
TECHNOLOGIES
Number Properties
The Number type includes some default properties. JavaScript treats primitive
values as object, so all the properties and methods are applicable to both
primitive number values and number objects.
The following table lists all the properties of Number type.
Property Description
MAX_VALUE Returns the maximum number value supported in
JavaScript
MIN_VALUE Returns the smallest number value supported in JavaScript
NEGATIVE_INFINITY Returns negative infinity (-Infinity)
NaN Represents a value that is not a number.
POSITIVE_INFINITY Represents positive infinity (Infinity).
[Link]
hikmat.kazimi12@[Link]
33
+93(0)789097059
Smart in City
TECHNOLOGIES
Number Methods
The following table lists all the methods of Number type
Method Description
toExponential(fractionDigits) Returns exponential value as a string.
Example:
var num = 100; [Link](2); //
returns '1.00e+2'
toFixed(fractionDigits) Returns string of decimal value of a number based on
specified fractionDigits.
Example:
var num = 100; [Link](2); // returns
'100.00'
toLocaleString() Returns a number as a string value according to a browser's
locale settings.
Example:
var num = 100; [Link](); //
returns '100'
toPrecision(precisionNumber) Returns number as a string with specified total digits.
Example:
var num = 100; [Link](4); // returns
'100.0'
toString() Returns the string representation of the number value.
Example:
var num = 100; [Link](); // returns
'100'
valueOf() Returns the value of Number object.
[Link]
hikmat.kazimi12@[Link]
34
+93(0)789097059
Smart in City
TECHNOLOGIES
Points to Remember:
1. JavaScript Number can store various numeric values like integer, float,
hexadecimal, decimal, exponential and octal values.
2. Number object can be created using new keyword.
e.g. var num = new Number(100);
3. Number type includes default properties - MAX_VALUE, MIN_VALUE,
NEGATIVE_INFINITY, NaN and POSITIVE_INFINITY.
4. Number methods are used to perform different tasks on numbers.
JavaScript Boolean
Boolean is a primitive data type in JavaScript. Boolean can have only two
values, true or false. It is useful in controlling program flow using conditional
statements like if..else, switch, while, do..while.
Example: Boolean
var YES = true;
var NO = false;
if(YES)
{
alert("This code block will be executed");
}
if(NO)
{
alert("This code block will not be executed");
}
[Link]
hikmat.kazimi12@[Link]
35
+93(0)789097059
Smart in City
TECHNOLOGIES
Boolean object
JavaScript includes Boolean object to represent true or false. It can be
initialized using new keyword.
Example: Boolean object
var bool = new Boolean(true);
alert(bool); // true
JavaScript treats empty string (""), 0, undefined and null as false. Everything
else is true.
Example: Boolean
var bool1 = new Boolean(""); // false
[Link]
hikmat.kazimi12@[Link]
36
+93(0)789097059
Smart in City
TECHNOLOGIES
Boolean Methods
Primitive or Boolean object includes following methods.
Method Description
toLocaleString() Returns string of boolean value in local browser environment.
Points to Remember:
1. JavaScript Boolean data type can store one of two values, true or false.
2. Boolean objects can be created using new keyword.
e.g. var YES = new Boolean(true);
3. JavaScript treats an empty string (""), 0, undefined and null as false.
Everything else is true.
4. Boolean methods are used to perform different tasks on Boolean values.
[Link]
hikmat.kazimi12@[Link]
37
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript Object
Object is a non-primitive data type in JavaScript. It is like any other variable, the
only difference is that an object holds multiple values in terms of properties and
methods. Properties can hold values of primitive data types and methods are
functions.
Object Literal
The object literal is a simple way of creating an object using { } brackets. You can
include key-value pair in { }, where key would be property or method name and
value will be value of property of any data type or a function. Use comma (,) to
separate multiple key-value pairs.
Syntax:
var <object-name> = { key1: value1, key2: value2,... keyN: valueN};
[Link]
hikmat.kazimi12@[Link]
38
+93(0)789097059
Smart in City
TECHNOLOGIES
You must specify key-value pair in object for properties or methods. Only
property or method name without value is not valid. The following syntax is
invalid.
Example: Wrong Syntax
var person = { firstName };
[Link]
hikmat.kazimi12@[Link]
39
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link]();
Note:
An object's methods can be called using () operator e.g. [Link]().
Without (), it will return function definition.
[Link]
hikmat.kazimi12@[Link]
40
+93(0)789097059
Smart in City
TECHNOLOGIES
Object Constructor
The second way to create an object is with Object Constructor
using new keyword. You can attach properties and methods using dot notation.
Optionally, you can also create properties using [ ] brackets and specifying
property name as string.
Example: Object Constructor
var person = new Object();
if([Link]("firstName")){
[Link];
}
[Link]
hikmat.kazimi12@[Link]
41
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link] = "Hikmat";
person["lastName"] = "Kazimi";
[Link] = 25;
[Link] = function () {
return [Link] + ' ' + [Link];
};
Pass by Reference
Object in JavaScript passes by reference from one function to another.
Example: JS Object Passes by Reference
function changeFirstName(per)
{
[Link] = "Hikmat";
}
changeFirstName(person)
[Link]
hikmat.kazimi12@[Link]
42
+93(0)789097059
Smart in City
TECHNOLOGIES
If, two objects point to the same object then the change made in one object
will reflect in another object.
Example: Object Reference
var person = { firstName : "Hikmat" };
[Link] = "Hikmat";
Points to Remember:
1. JavaScript object is a standalone entity that holds multiple values in terms
of properties and methods.
2. Object property stores a literal value and method represents function.
3. An object can be created using object literal or object constructor syntax.
4. Object literal:
[Link]
hikmat.kazimi12@[Link]
43
+93(0)789097059
Smart in City
TECHNOLOGIES
1. var person = {
2. firstName: "Hikmat",
3. lastName: "Kazimi",
4. age: 25,
5. getFullName: function () {
6. return [Link] + ' ' + [Link]
7. }
8. };
Object constructor:
1. var person = new Object();
2.
3. [Link] = "Hikmat";
4. person["lastName"] = "Kazimi";
5. [Link] = 25;
6. [Link] = function () {
7. return [Link] + ' ' + [Link];
8. };
[Link]
hikmat.kazimi12@[Link]
44
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript - Date
JavaScript provides Date object to work with date & time including days,
months, years, hours, minutes, seconds and milliseconds.
The following example shows how to display current date and time using Date
object in JavaScript.
Example: Current Local Date
//or
As you can see in the above example, we can display current date and time
either by calling Date as function or creating an object with new keyword.
In order to work with date other than current date and time, we must create a
date object by specifying different parameters in the Date constructor.
:
Syntax:
var dt = new Date();
[Link]
hikmat.kazimi12@[Link]
45
+93(0)789097059
Smart in City
TECHNOLOGIES
As per the above syntax, the following parameters can be specified in Date
constructor.
1. No Parameter: Date object will be set to current date & time if no
parameter is specified in the constructor.
2. Milliseconds: Milliseconds can be specified as numeric parameter. The
date object will calculate date & time by adding specified numeric
milliseconds from mid night of 1/1/1970
3. Date string: String parameter will be treated as a date and will be parsed
using [Link] method.
Overload of Date constructor includes following seven numeric parameters.
year: Numeric value to represent year of a date.
month: Numeric value to represent month of a date. Starts with 0 for
January till 11 for December
date: Numeric value to represent day of a date (optional).
hour: Numeric value to represent hour of a day (optional).
minute: Numeric value to represent minute of a time segment (optional).
second: Numeric value to represent second of a time segment (optional).
millisecond: Numeric value to represent millisecond of a time
segment(optional). Specify numeric milliseconds in the constructor to get
the date and time elapsed from 1/1/1970.
In the following example, date object is created by passing milliseconds in Date
constructor. So date will be calculated based on milliseconds elapsed from
1/1/1970.
Example: Create Date by Specifying Milliseconds
var date1 = new Date(0); // Thu Jan 01 1970 05:30:00
Specify any valid date as a string to create new date object for the specified
date. The following example shows various formats of date string which you
can specify in a Date constructor.
[Link]
hikmat.kazimi12@[Link]
46
+93(0)789097059
Smart in City
TECHNOLOGIES
You can use any valid separator in date string to differentiate date segments.
Example: Create Date using Different Date Separator
var date1 = new Date("February 2015-3");
[Link]
hikmat.kazimi12@[Link]
47
+93(0)789097059
Smart in City
TECHNOLOGIES
Specify seven numeric values to create a date object with specified year, month
and optionally date, hours, minutes, seconds and milliseconds.
Example: Date
var dt = new Date(2014, 2, 3, 10, 30, 50, 800); // Mon Feb 03 2014
10:30:50
Date Methods
The JavaScript Date object includes various methods to operate on it. Use
different methods to get different segments of date like day, year, month, hour,
seconds or milliseconds in either local time or UTC time.
Example: Date Methods
var date = new Date('4-1-2015');
[Link]();// returns 3
[Link]();// returns 31
Date Formats
JavaScript supports ISO 8601 date format by default
- YYYY-MM-DDTHH:mm:[Link]
Example: ISO Date Format
var dt = new Date('2015-02-10T10:12:50.5000z');
[Link]
hikmat.kazimi12@[Link]
48
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link]();'2/10/2015'
[Link](); '2015-02-10T10:12:50.500Z'
[Link](); '15:42:50'
To get date string in formats other than the ones listed above, you need to
manually form the date string using different Date methods. The following
example converts date string to DD-MM-YYYY format.
Example: Get Date Segments
var date = new Date('4-1-2015'); // M-D-YYYY
var d = [Link]();
var m = [Link]() + 1;
var y = [Link]();
var dateString = (d <= 9 ? '0' + d : d) + '-' + (m <= 9 ? '0' + m : m) + '-
' + y;
[Link]
hikmat.kazimi12@[Link]
49
+93(0)789097059
Smart in City
TECHNOLOGIES
Note:
Use third party JavaScript Date library like [Link] or [Link],
if you want to work with Dates extensively.
Parse Date
Use [Link]() method to convert valid date string into milliseconds since
midnight of 1/1/1970.
Example: [Link]()
[Link]("5/2/2015"); // 1430505000000
Compare Dates
Use comparison operators to compare two date objects.
Example: Date Comparison
var date1 = new Date('4-1-2015');
var date2 = new Date('4-2-2015');
Points to Remember:
1. Get current date using Date() or new Date().
2. Date object can be created using new keyword. e.g. var date = new Date();
3. Date can be created by specifying milliseconds, date string or year and
month in Date constructor.
4. Date can be created by specifying date string in different formats using
different separators.
5. Date methods are used to perform different tasks on date objects.
[Link]
hikmat.kazimi12@[Link]
50
+93(0)789097059
Smart in City
TECHNOLOGIES
Method Description
getDate() Returns numeric day (1 - 31) of the specified date.
[Link]
hikmat.kazimi12@[Link]
51
+93(0)789097059
Smart in City
TECHNOLOGIES
Method Description
getUTCMinutes() Returns the minutes (0 - 59) of the specified date as
per UTC time zone.
The following table lists all the set methods of Date object.
Method Description
setDate() Sets the day as number in the date object.
setFullYear() Sets the four digit full year as number in the date object. Optionally
set month and date.
setHours() Sets the hours as number in the date object. Optionally set minutes,
seconds and milliseconds.
setMinutes() Sets the minutes as number in the date object. Optionally set
seconds & milliseconds.
setMonth() Sets the month as number in the date object. Optionally set date.
setSeconds() Sets the seconds as number in the date object. Optionally set
milliseconds.
setTime() Sets the time as number in the Date object since January 1, 1970,
00:00:00 UTC.
setUTCDate() Sets the day in the date object as per UTC time zone.
setUTCFullYear() Sets the full year in the date object as per UTC time zone
setUTCHours() Sets the hour in the date object as per UTC time zone
[Link]
hikmat.kazimi12@[Link]
52
+93(0)789097059
Smart in City
TECHNOLOGIES
Method Description
setUTCMilliseconds() Sets the milliseconds in the date object as per UTC time zone
setUTCMinutes() Sets the minutes in the date object as per UTC time zone
setUTCMonth() Sets the month in the date object as per UTC time zone
setUTCSeconds() Sets the seconds in the date object as per UTC time zone
setYear() Sets the year in the date object. This method is Deprecated
toLocaleDateString() Returns the date segment of the specified date using the current
locale.
toTimeString() Returns the time segment as a string from the specified date object.
[Link]
hikmat.kazimi12@[Link]
53
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
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 JS Array
var stringArray = ["one", "two", "three"];
[Link]
hikmat.kazimi12@[Link]
54
+93(0)789097059
Smart in City
TECHNOLOGIES
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();
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.
[Link]
hikmat.kazimi12@[Link]
55
+93(0)789097059
Smart in City
TECHNOLOGIES
stringArray["one"] = "one";
stringArray["two"] = "two";
stringArray["three"] = "three";
stringArray["four"] = "four";
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");
[Link]
hikmat.kazimi12@[Link]
56
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
[Link]
hikmat.kazimi12@[Link]
57
+93(0)789097059
Smart in City
TECHNOLOGIES
Method Description
concat() Returns new array by combining values of an array that is specified as
parameter with existing array values.
every() Returns true or false if every element in the specified array satisfies a
condition specified in the callback function. Returns false even if single
element does not satisfy the condition.
filter() Returns a new array with all the elements that satisfy a condition specified in
the callback function.
indexOf() Returns the index of the first occurrence of the specified element in the
array, or -1 if it is not found.
join() Returns string of all the elements separated by the specified separator
lastIndexOf() Returns the index of the last occurrence of the specified element in the
array, or -1 if it is not found.
map() Creates a new array with the results of calling a provided function on every
element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements at the end of an array and returns the new
length of the array.
reduce() Pass two elements simultaneously in the callback function (till it reaches the
last element) and returns a single value.
reduceRight() Pass two elements simultaneously in the callback function from right-to-left
(till it reaches the last element) and returns a single value.
reverse() Reverses the elements of an array. Element at last index will be first and
element at 0 index will be last.
shift() Removes the first element from an array and returns that element.
[Link]
hikmat.kazimi12@[Link]
58
+93(0)789097059
Smart in City
TECHNOLOGIES
Method Description
slice() Returns a new array with specified start to end elements.
some() Returns true if at least one element in this array satisfies the condition in the
callback function.
unshift() Adds one or more elements to the front of an array and returns the new
length of the array.
[Link]
hikmat.kazimi12@[Link]
59
+93(0)789097059
Smart in City
TECHNOLOGIES
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
[Link]
hikmat.kazimi12@[Link]
60
+93(0)789097059
Smart in City
TECHNOLOGIES
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
[Link]
hikmat.kazimi12@[Link]
61
+93(0)789097059
Smart in City
TECHNOLOGIES
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);
if (myVar)
alert("myVar evaluates to true");
else
alert("myVar evaluates to false");
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.
[Link]
hikmat.kazimi12@[Link]
62
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript Function
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.
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 a Function
function ShowMessage() {
alert("Hello World!");
}
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.
[Link]
hikmat.kazimi12@[Link]
63
+93(0)789097059
Smart in City
TECHNOLOGIES
ShowMessage("Adeeb", "Kakar");
ShowMessage("Hikmat", "Kazimi");
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("Adeeb", "Kakar");
ShowMessage("Hikmat", "Kazimi");
ShowMessage(100, 200);
[Link]
hikmat.kazimi12@[Link]
64
+93(0)789097059
Smart in City
TECHNOLOGIES
An arguments object is still valid even if function does not include any
parameters.
Example: Arguments Object
function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);
}
ShowMessage("Adeeb", "Kakar");
Return Value
A function can return zero or one value using return keyword.
Example: Return value From a Function
function Sum(val1, val2) {
return val1 + val2;
};
[Link]
hikmat.kazimi12@[Link]
65
+93(0)789097059
Smart in City
TECHNOLOGIES
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;
}
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;
};
[Link]
hikmat.kazimi12@[Link]
66
+93(0)789097059
Smart in City
TECHNOLOGIES
Anonymous Function
showMessage();
showMessage();
sayHello("Hikmat");
Nested Functions
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 Functions
function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}
[Link]
hikmat.kazimi12@[Link]
67
+93(0)789097059
Smart in City
TECHNOLOGIES
return SayHello();
}
ShowMessage("Adeeb");
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.
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.
[Link]
hikmat.kazimi12@[Link]
68
+93(0)789097059
Smart in City
TECHNOLOGIES
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");
}
[Link]
hikmat.kazimi12@[Link]
69
+93(0)789097059
Smart in City
TECHNOLOGIES
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");
}
[Link]
hikmat.kazimi12@[Link]
70
+93(0)789097059
Smart in City
TECHNOLOGIES
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..
}
[Link]
hikmat.kazimi12@[Link]
71
+93(0)789097059
Smart in City
TECHNOLOGIES
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;
[Link]
hikmat.kazimi12@[Link]
72
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
[Link]
hikmat.kazimi12@[Link]
73
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript switch
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
}
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.
[Link]
hikmat.kazimi12@[Link]
74
+93(0)789097059
Smart in City
TECHNOLOGIES
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");
}
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");
}
[Link]
hikmat.kazimi12@[Link]
75
+93(0)789097059
Smart in City
TECHNOLOGIES
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 Case
var str = "hikmat";
switch (str)
{
case "khesraw":
alert("This is khesraw");
case "hikmat":
alert("This is hikmat");
break;
case "khpalwak":
alert("This is khpalwak");
break;
default:
alert("Unknown Person");
break;
}
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");
}
[Link]
hikmat.kazimi12@[Link]
76
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
5. A switch case can be combined to execute same code block for multiple
cases.
[Link]
hikmat.kazimi12@[Link]
77
+93(0)789097059
Smart in City
TECHNOLOGIES
:
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
Output:
0 1 2 3 4
[Link]
hikmat.kazimi12@[Link]
78
+93(0)789097059
Smart in City
TECHNOLOGIES
The for loop can also be used to get the values for an array.
Example: for loop
var arr = [10, 11, 12, 13, 14];
Output:
10 11 12 13 14
for (; ;) {
if (i >= 5)
break;
[Link](arr[i]);
i++;
}
Output:
10 11 12 13 14
[Link]
hikmat.kazimi12@[Link]
79
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
[Link]
hikmat.kazimi12@[Link]
80
+93(0)789097059
Smart in City
TECHNOLOGIES
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 */
}
while(i < 5)
{
[Link](i);
i++;
}
Output:
0 1 2 3 4
[Link]
hikmat.kazimi12@[Link]
81
+93(0)789097059
Smart in City
TECHNOLOGIES
do while
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:
0 1 2 3 4
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.
Example: do-while loop
var i =0;
do{
alert(i);
i++;
} while(i > 1)
Output:
0
[Link]
hikmat.kazimi12@[Link]
82
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
[Link]
hikmat.kazimi12@[Link]
83
+93(0)789097059
Smart in City
TECHNOLOGIES
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>
function modifyUserName() {
userName = "Hikmat";
};
function showUserName() {
alert(userName);
};
modifyUserName();
showUserName();// display Hikmat
</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.
[Link]
hikmat.kazimi12@[Link]
84
+93(0)789097059
Smart in City
TECHNOLOGIES
Please note that variables declared inside a function without var keyword also
become global variables.
Example: Global Variable
<script>
function createUserName() {
userName = "Hafiz";
}
function modifyUserName() {
if(userName)
userName = "Hikmat";
};
function showUserName() {
alert(userName);
}
createUserName();
showUserName(); // Hafiz
modifyUserName();
showUserName(); // Hikmat
</script>
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".
[Link]
hikmat.kazimi12@[Link]
85
+93(0)789097059
Smart in City
TECHNOLOGIES
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 = "Hafiz";
}
function showUserName() {
alert(userName);
}
createUserName();
showUserName(); // throws error: userName is not defined
</script>
[Link]
hikmat.kazimi12@[Link]
86
+93(0)789097059
Smart in City
TECHNOLOGIES
Some tips..
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 = "Hafiz";
function ShowUserName()
{
var userName = "Hikmat";
alert(userName); // "Hikmat"
}
ShowUserName();
alert(userName); // Hafiz
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();
[Link]
hikmat.kazimi12@[Link]
87
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
[Link]
hikmat.kazimi12@[Link]
88
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript eval
eval() is a global function in JavaScript that evaluates a specified string as
JavaScript code and executes it.
Example: eval
eval("alert('this is executed by eval()')");
The eval() function can also call the function and get the result as shown below.
Example: eval
var result;
alert(result);
[Link]; // Bill
Recommendation
It is not recommended to use eval() because it is slow, not secure, and makes
code unreadable and maintainable.
[Link]
hikmat.kazimi12@[Link]
89
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link]
hikmat.kazimi12@[Link]
90
+93(0)789097059
Smart in City
TECHNOLOGIES
throw
Use throw keyword to raise a custom error.
Example: throw Error
try
{
throw "Error occurred";
}
catch(ex)
{
alert(ex);
}
[Link]
hikmat.kazimi12@[Link]
91
+93(0)789097059
Smart in City
TECHNOLOGIES
You can use JavaScript object for more information about an error.
Example: throw error with error info
try
{
throw {
number: 101,
message: "Error occurred"
};
}
catch (ex) {
alert([Link] + "- " + [Link]);
}
[Link]
hikmat.kazimi12@[Link]
92
+93(0)789097059
Smart in City
TECHNOLOGIES
x = 1; // error
[Link]
hikmat.kazimi12@[Link]
93
+93(0)789097059
Smart in City
TECHNOLOGIES
Duplicate parameters:
Example: strict mode
"use strict";
[Link]
hikmat.kazimi12@[Link]
94
+93(0)789097059
Smart in City
TECHNOLOGIES
Octal literals:
Example: strict mode
"use strict";
with statement:
with (Math){
x = abs(200.234, 2); // error
};
x = 1; //valid
return result;
}
[Link]
hikmat.kazimi12@[Link]
95
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript 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;
var x;
JavaScript Hoisting
var x;
var y;
[Link]
hikmat.kazimi12@[Link]
96
+93(0)789097059
Smart in City
TECHNOLOGIES
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.
Please note that JavaScript compiler does not move function expression.
Example: Hoisting on function expression
[Link]
hikmat.kazimi12@[Link]
97
+93(0)789097059
Smart in City
TECHNOLOGIES
var UseMe;
function UseMe()
{
alert("UseMe function called");
}
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.
[Link]
hikmat.kazimi12@[Link]
98
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link]
hikmat.kazimi12@[Link]
99
+93(0)789097059
Smart in City
TECHNOLOGIES
alert([Link]());
alert([Link]());
In the above example, the Person function includes function expression that is
assigned to a member variable getFullName. So now, getFullName() will act like
a method of the Person class. It can be called using dot notation e.g.
[Link]().
Constructor
In the other programming languages like Java or C#, a class can have one or more
constructors. In JavaScript, a function can have one or more parameters. So, a
function with one or more parameters can be used like a constructor where you
can pass parameter values at the time or creating an object with new keyword.
[Link]
hikmat.kazimi12@[Link]
100
+93(0)789097059
Smart in City
TECHNOLOGIES
Example: Constructor
function Person(FirstName, LastName, Age) {
[Link] = FirstName || "unknown";
[Link] = LastName || "unknown";
[Link] = Age || 25;
[Link] = function () {
return [Link] + " " + [Link];
}
};
Note:
Please notice that parameter assigned to a property, if parameter value is not
passed while creating an object using new then they will be undefined.
[Link]
hikmat.kazimi12@[Link]
101
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link](this, {
"FirstName": {
get: function () {
return _firstName;
},
set: function (value) {
_firstName = value;
}
}
});
};
[Link]
hikmat.kazimi12@[Link]
102
+93(0)789097059
Smart in City
TECHNOLOGIES
Read-only Property
Do not specify set function in order to create read-only property as shown
below.
[Link](this, {
"FirstName": {
get: function () {
return _firstName;
}
}
});
};
var person1 = new Person("Hikmat");
//[Link] = "Hikmat"; -- will not work
alert([Link] );
[Link]
hikmat.kazimi12@[Link]
103
+93(0)789097059
Smart in City
TECHNOLOGIES
Multiple Properties
Specify more than one property in defineProperties() method as shown below.
Example: Multiple Properties
function Person(firstName, lastName, age) {
var _firstName = firstName || "unknown";
var _lastName = lastName || "unknown";
var _age = age || 25;
[Link](this, {
"FirstName": {
get: function () { return _firstName },
set: function (value) { _firstName = value }
},
"LastName": {
get: function () { return _lastName },
set: function (value) { _lastName = value }
},
"Age": {
get: function () { return _age },
set: function (value) { _age = value }
}
});
[Link] = function () {
return [Link] + " " + [Link];
}
};
alert([Link]());
[Link]
hikmat.kazimi12@[Link]
104
+93(0)789097059
Smart in City
TECHNOLOGIES
// Constructor function
function Student(){
[Link] = "Adeeb";
[Link] = "Male";
[Link] = function(){
alert('Hi');
}
}
var student1 = new Student();
[Link]([Link]);
[Link]([Link]);
[Link]();
In the above example, person object is created using object literal that
includes firstName and lastName properties and student1 object is
created using constructor function Student that includes name, gender and
sayHi properties where function is assigned to sayHi property.
[Link]
hikmat.kazimi12@[Link]
105
+93(0)789097059
Smart in City
TECHNOLOGIES
Note:
Any javascript function using which object is created is called constructor
function.
Use [Link]() method to retrieve all the properties name for the specified
object as a string array.
Example: Edit Property Descriptor
function Student(){
[Link] = "Mr.";
[Link] = "Adeeb";
[Link] = "Male";
[Link] = function(){
alert('Hi');
}
}
var student1 = new Student();
[Link](student1);
Output:
["title", "name", "gender", "sayHi"]
Use for-in loop to retrieve all the properties of an object as shown below.
Example: Enumerable Properties
function Student(){
[Link] = "Mr.";
[Link] = "Adeeb";
[Link] = "Male";
[Link] = function(){
alert('Hi');
}
}
var student1 = new Student();
[Link]
hikmat.kazimi12@[Link]
106
+93(0)789097059
Smart in City
TECHNOLOGIES
Property Descriptor
In JavaScript, each property of an object has property descriptor which describes
the nature of a property. Property descriptor for a particular object's property
can be retrieved using [Link]() method.
:
Syntax:
[Link](object, 'property name')
function Student(){
[Link] = "Khpalwak";
[Link] = "Male";
[Link] = function(){
alert('Hi');
}
}
[Link]([Link](person,'firstName'));
[Link]([Link](student1,'name'));
[Link]([Link](student1,'sayHi'));
Output:
Object {value: "Adeeb", writable: true, enumerable: true, configurable: true}
Object {value: "Khpalwak", writable: true, enumerable: true, configurable: true}
Object {value: function, writable: true, enumerable: true, configurable: true}
[Link]
hikmat.kazimi12@[Link]
107
+93(0)789097059
Smart in City
TECHNOLOGIES
As you can see in the above output, the property descriptor includes the
following 4 important attributes.
Attribute Description
value Contains an actual value of a property.
writable Indicates that whether a property is writable or read-only. If true than value can be
changed and if false then value cannot be changed and will throw an exception in
strict mode
enumerable Indicates whether a property would show up during the enumeration using for-in
loop or [Link]() method.
configurable Indicates whether a property descriptor for the specified property can be changed
or not. If true then any of this 4 attribute of a property can be changed using
[Link]() method.
[Link]()
The [Link]() method defines a new property on the specified
object or modifies an existing property or property descriptor.
:
Syntax:
[Link](object, 'property name', descriptor)
[Link]
hikmat.kazimi12@[Link]
108
+93(0)789097059
Smart in City
TECHNOLOGIES
function Student(){
[Link] = "Hikmat";
[Link] = "Male";
[Link](student1,'name', { writable:false} );
try
{
[Link] = "Khesraw";
[Link]([Link]);
}
catch(ex)
{
[Link]([Link]);
}
[Link]
hikmat.kazimi12@[Link]
109
+93(0)789097059
Smart in City
TECHNOLOGIES
Output:
name
gender
In the above example, it display all the properties using for-in loop. But, once
you change the enumerable attribute to false then it won't
display name property using for-in loop. As you can see in the output, after
setting enumerable attributes of name property to false, it will not be
enumerated using for-in loop or even [Link]() method.
The [Link]() method can also be used to modify configurable
attribute of a property which restrict changing any property descriptor
attributes further.
The following example demonstrates changing configurable attribute.
[Link]
hikmat.kazimi12@[Link]
110
+93(0)789097059
Smart in City
TECHNOLOGIES
function Student(){
[Link] = "Hikmat";
[Link] = "Male";
}
var student1 = new Student();
[Link](student1,'name',{configurable:false});// set
configurable to false
try
{
[Link](student1,'name',{writable:false}); //
change writable attribute
}
catch(ex)
{
[Link]([Link]);
}
[Link]
hikmat.kazimi12@[Link]
111
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link](student1,'fullName',{
get:function(){
return [Link] + ' ' + [Link];
},
set:function(_fullName){
[Link] = _fullName.split(' ')[0];
[Link] = _fullName.split(' ')[1];
}
});
[Link]([Link]);
[Link]([Link]);
Output:
Mr.
Hikmat
[Link]
hikmat.kazimi12@[Link]
112
+93(0)789097059
Smart in City
TECHNOLOGIES
this in JavaScript
The this keyword is one of the most widely used and yet confusing keyword in
JavaScript. Here, you will learn everything about this keyword.
this points to a particular object. Now, which is that object is depends on how
a function which includes 'this' keyword is being called.
Look at the following example and guess what the result would be?
<script>
var myVar = 100;
function WhoIsThis() {
var myVar = 200;
alert(myVar); // 200
alert([Link]); // 100
}
The following four rules applies to this in order to know which object is
referred by this keyword.
1. Global Scope
2. Object's Method
3. call() or apply() method
4. bind() method
[Link]
hikmat.kazimi12@[Link]
113
+93(0)789097059
Smart in City
TECHNOLOGIES
Global Scope
If a function which includes 'this' keyword, is called from the global scope
then this will point to the window object. Learn about global and local
scope here.
Example: this keyword
<script>
var myVar = 100;
function WhoIsThis() {
var myVar = 200;
In the above example, a function WhoIsThis() is being called from the global
scope. The global scope means in the context of window object. We can
optionally call it like [Link](). So in the above
example, this keyword in WhoIsThis() function will refer to window object.
So, [Link] will return 100. However, if you
access myVar without this then it will refer to local myVar variable defined
in WhoIsThis() function.
[Link]
hikmat.kazimi12@[Link]
114
+93(0)789097059
Smart in City
TECHNOLOGIES
this in JavaScript
Note:
In the strict mode, value of 'this' will be undefined in the global scope.
'this' points to global window object even if it is used in an inner function.
Consider the following example.
Example: this keyword inside inner function
var myVar = 100;
function SomeFunction() {
function WhoIsThis() {
var myVar = 200;
WhoIsThis();
}
SomeFunction();
[Link]
hikmat.kazimi12@[Link]
115
+93(0)789097059
Smart in City
TECHNOLOGIES
So, if 'this' is used inside any global function and called without dot notation or
using window. then this will refer to global object which is default window
object.
function WhoIsThis() {
[Link] = 200;
}
var obj1 = new WhoIsThis();
alert([Link]); // 200
alert([Link]); // 300
In the above example, this points to obj1 for obj1 instance and points
to obj2 for obj2 instance. In JavaScript, properties can be attached to an
object dynamically using dot notation. Thus, myVar will be a property of both
the instances and each will have a separate copy of myVar .
[Link]
hikmat.kazimi12@[Link]
116
+93(0)789097059
Smart in City
TECHNOLOGIES
function WhoIsThis() {
[Link] = 200;
[Link] = function(){
var myVar = 300;
[Link]();
In the above example, obj will have two properties myVar and display , where
display is a function expression. So, this inside display() method points
to obj when calling [Link]().
this behaves the same way when object created using object literal, as shown
below.
Example: this keyword
var myVar = 100;
var obj = {
myVar : 300,
whoIsThis: function(){
var myVar = 200;
alert(myVar); // 200
alert([Link]); // 300
}
};
[Link]();
[Link]
hikmat.kazimi12@[Link]
117
+93(0)789097059
Smart in City
TECHNOLOGIES
WhoIsThis();
[Link]();
[Link]();
function WhoIsThis() {
alert([Link]);
}
[Link]
hikmat.kazimi12@[Link]
118
+93(0)789097059
Smart in City
TECHNOLOGIES
As you can see in the above example, when the function WhoIsThis is called
using () operator (like WhoIsThis()) then this inside a function follows the rule-
refers to window object. However, when the WhoIsThis is called using call() and
apply() method then this refers to an object which is passed as a first
parameter irrespective of how the function is being called.
Therefore, this will point to obj1 when a function got called
as [Link](obj1). In the same way, this will point to obj2 when a
function got called like [Link](obj2)
bind()
The bind() method was introduced since ECMAScript 5. It can be used to set
the context of 'this' to a specified object when a function is invoked.
The bind() method is usually helpful in setting up the context of this for a callback
function. Consider the following example.
Example: bind()
var myVar = 100;
function SomeFunction(callback)
{
var myVar = 200;
callback();
};
var obj = {
myVar: 300,
WhoIsThis : function() {
alert("'this' points to " + this + ", myVar = " +
[Link]);
}
};
SomeFunction([Link]);
SomeFunction([Link](obj));
[Link]
hikmat.kazimi12@[Link]
119
+93(0)789097059
Smart in City
TECHNOLOGIES
Precedence
So these 4 rules applies to this keyword in order to determine which
object this refers to. The following is precedence of order.
1. bind()
2. call() and apply()
3. Object method
4. Global scope
So, first check whether a function is being called as callback function using
bind()? If not then check whether a function is being called using call() or apply()
with parmeter? If not then check whether a function is being called as an object
function? Otherise check whether a function is being called in the global scope
without dot notation or using window object.
Thus, use these simple rules in order to know which object the 'this' refers to
inside any function.
[Link]
hikmat.kazimi12@[Link]
120
+93(0)789097059
Smart in City
TECHNOLOGIES
The built-in primitive types in JavaScript are functions only e.g. Object,
Boolean, String, Number is built-in JavaScript functions. If you write Object in
browser's console window and press Enter then you will see the output
"function Object()".
In the above example, we have created an object of MyFunc using new keyword.
This MyFunc() is called a constructor function. The new keyword constructs and
returns an object (instance) of a constructor function.
The new keyword performs following four tasks:
1. It creates new empty object e.g. obj = { };
2. It sets new empty object's invisible 'prototype' property to be the
constructor function's visible and accessible 'prototype' property. (Every
function has visible 'prototype' property whereas every object includes
invisible 'prototype' property)
3. It binds property or function which is declared with this keyword to the
new object.
4. It returns newly created object unless the constructor function returns a
non-primitive value (custom JavaScript object). If constructor function
does not include return statement then compiler will insert 'return this;'
implicitly at the end of the function. If the constructor function returns a
primitive value then it will be ignored.
[Link]
hikmat.kazimi12@[Link]
121
+93(0)789097059
Smart in City
TECHNOLOGIES
Let's see how new keyword creates an object using following example.
Example: new keyword
function MyFunc() {
var myVar = 1;
this.x = 100;
}
[Link].y = 200;
[Link]
hikmat.kazimi12@[Link]
122
+93(0)789097059
Smart in City
TECHNOLOGIES
The new keyword ignores return statement that returns primitive value.
Example: new keyword
function MyFunc() {
this.x = 100;
return 200;
}
return { a: 123 };
}
alert(obj1.x); // undefined
Thus, new keyword builds an object of a function in JavaScript.
[Link]
hikmat.kazimi12@[Link]
123
+93(0)789097059
Smart in City
TECHNOLOGIES
Prototype in JavaScript
JavaScript is a dynamic language. You can attach new properties to an object at
any time as shown below.
Example: Attach property to object
function Student() {
[Link] = 'Hikmat';
[Link] = 'Male';
}
As you can see in the above example, age property is attached to studObj1
instance. However, studObj2 instance will not have age property because it is
defined only on studObj1 instance.
So what to do if we want to add new properties at later stage to a function which
will be shared across all the instances?
The answer is Prototype.
The prototype is an object that is associated with every functions and objects by
default in JavaScript, where function's prototype property is accessible and
modifiable and object's prototype property (aka attribute) is not visible.
Every function includes prototype object by default.
[Link]
hikmat.kazimi12@[Link]
124
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link] = 15;
Every object which is created using literal syntax or constructor syntax with the
new keyword, includes __proto__ property that points to prototype object of a
function that created this object.
[Link]
hikmat.kazimi12@[Link]
125
+93(0)789097059
Smart in City
TECHNOLOGIES
You can debug and see object's or function's prototype property in chrome or
firefox's developer tool. Consider the following example.
Example: prototype
function Student() {
[Link] = 'Hikmat';
[Link] = 'M';
}
[Link]([Link]); // object
[Link]([Link]); // undefined
[Link](studObj.__proto__); // object
As you can see in the above example, Function's prototype property can be
accessed using <function-name>. prototype. However, an object (instance)
does not expose prototype property, instead you can access it
using __proto__.
Note:
The prototype property is special type of enumerable object which cannot be
iterate using for..in or foreach loop.
[Link]
hikmat.kazimi12@[Link]
126
+93(0)789097059
Smart in City
TECHNOLOGIES
Object's Prototype
As mentioned before, object's prototype property is invisible.
Use [Link](obj) method instead of __proto__ to access
prototype object.
Example: Object's prototype
function Student() {
[Link] = 'Hikmat';
[Link] = 'M';
}
[Link]= function(){
alert("Hi");
};
[Link]
hikmat.kazimi12@[Link]
127
+93(0)789097059
Smart in City
TECHNOLOGIES
Property Description
constructor Returns a function that created instance.
Method Description
hasOwnProperty() Returns a boolean indicating whether an object
contains the specified property as a direct property
of that object and not inherited through the
prototype chain.
[Link]
hikmat.kazimi12@[Link]
128
+93(0)789097059
Smart in City
TECHNOLOGIES
Changing Prototype
As mentioned above, each object's prototype is linked to function's prototype
object. If you change function's prototype then only new objects will be linked
to changed prototype. All other existing objects will still link to old prototype of
function. The following example demonstrates this scenario.
Example: Changing Prototype
function Student() {
[Link] = 'Hikmat';
[Link] = 'M';
}
[Link] = 15;
[Link] = { age : 20 };
Use of Prototype
The prototype object is being used by JavaScript engine in two things, 1) to find
properties and methods of an object 2) to implement inheritance in JavaScript.
function Student() {
[Link] = 'Hikmat';
[Link] = 'M';
}
[Link] = function(){
alert("Hi");
};
[Link]
hikmat.kazimi12@[Link]
129
+93(0)789097059
Smart in City
TECHNOLOGIES
In the above example, toString() method is not defined in Student, so how and
from where it finds toString()?
Here, prototype comes into picture. First of all, JavaScript engine checks
whether toString() method is attached to studObj? (It is possible to attach a new
function to a instance in JavaScript). If it does not find there then it uses
studObj's __proto__ link which points to the prototype object of Student
function. If it still cannot find it there then it goes up in the heirarchy and check
prototype object of Object function because all the objects are derived from
Object in JavaScript, and look for toString() method. Thus, it finds toString()
method in the prototype object of Object function and so we can call
[Link]().
This way, prototype is useful in keeping only one copy of functions for all the
objects (instances).
The following figure illustrates the above scenario.
[Link]
hikmat.kazimi12@[Link]
130
+93(0)789097059
Smart in City
TECHNOLOGIES
Inheritance in JavaScript
Inheritance is an important concept in object oriented programming. In the
classical inheritance, methods from base class get copied into derived class.
In JavaScript, inheritance is supported by using prototype object. Some people
call it "Prototypal Inheriatance" and some people call it "Behaviour Delegation".
Let's see how we can achieve inheritance like functionality in JavaScript using
prototype object.
Let's start with the Person class which includes FirstName & LastName property
as shown below.
function Person(firstName, lastName) {
[Link] = firstName || "unknown";
[Link] = lastName || "unknown";
};
[Link] = function () {
return [Link] + " " + [Link];
}
In the above example, we have defined Person class (function) with FirstName
& LastName properties and also added getFullName method to
its prototype object.
Now, we want to create Student class that inherits from Person class so that we
don't have to redefine FirstName, LastName and getFullName() method in
Student class. The following is a Student class that inherits Person class.
Example: Inheritance
function Student(firstName, lastName, schoolName, grade)
{
[Link](this, firstName, lastName);
[Link]
hikmat.kazimi12@[Link]
131
+93(0)789097059
Smart in City
TECHNOLOGIES
Please note that we have set [Link] to newly created person object.
The new keyword creates an object of Person class and also assigns
[Link] to new object's prototype object and then finally assigns
newly created object to [Link] object. Optionally, you can also
assign [Link] to [Link] object.
Now, we can create an object of Student that uses properties and methods of
the Person as shown below.
Example: Inheritance
function Person(firstName, lastName) {
[Link] = firstName || "unknown";
[Link] = lastName || "unknown";
}
[Link] = function () {
return [Link] + " " + [Link];
}
function Student(firstName, lastName, schoolName, grade)
{
[Link](this, firstName, lastName);
[Link]
hikmat.kazimi12@[Link]
132
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript Closure
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: [Link]/javascript/[Link]
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();
}
[Link]
hikmat.kazimi12@[Link]
133
+93(0)789097059
Smart in City
TECHNOLOGIES
Example: Closure
function OuterFunction() {
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc(); // 100
[Link]
hikmat.kazimi12@[Link]
134
+93(0)789097059
Smart in City
TECHNOLOGIES
Example: Closure
function Counter() {
var counter = 0;
function IncreaseCounter() {
return counter += 1;
};
return IncreaseCounter;
}
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();
[Link]
hikmat.kazimi12@[Link]
135
+93(0)789097059
Smart in City
TECHNOLOGIES
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 };
})();
alert([Link]()); // 0
[Link]();
[Link]();
alert([Link]()); // 2
[Link]();
alert([Link]()); // 1
[Link]
hikmat.kazimi12@[Link]
136
+93(0)789097059
Smart in City
TECHNOLOGIES
[Link]
hikmat.kazimi12@[Link]
137
+93(0)789097059
Smart in City
TECHNOLOGIES
function display(name)
{
alert("[Link]: " + name);
}
display(userName);
Example: [Link]
var userName = "Khesraw";
function display(name)
{
alert("[Link]: " + name);
}
display(userName);
Now, if you include these JS files in your web page then guess what will
happen?
Example: Script tag in <head>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JavaScript Demo</title>
<script src="/[Link]"></<script>
<script src="/[Link]"></<script>
</head>
<body>
<h1> IIFE Demo</h1>
</body>
</html>
[Link]
hikmat.kazimi12@[Link]
138
+93(0)789097059
Smart in City
TECHNOLOGIES
If you run above example, you will find that every time it call display() function
in [Link] because [Link] included after [Link] in a web page.
So JavaScript considers last definition of a function if two functions have the
same name.
IEFE solves this problem by having its own scope and restricting functions and
variables to become global. The functions and variables declare inside IIFE will
not pollute global scope even they have same name as global variables &
functions. So let's see what is an IIFE is.
What is an IIFE?
As name suggest, IIFE is a function expression that automatically invokes after
completion of the definition. The parenthesis () plays important role in IIFE
pattern. In JavaScript, parenthesis cannot contain statements; it can only
contain an expression.
Example: Parenthesis ()
(var foo = 10 > 9); // syntax error
(var foo = "foo", bar = "bar"); // syntax error
(10 > 9); // valid
(alert("Hi")); // valid
[Link]
hikmat.kazimi12@[Link]
139
+93(0)789097059
Smart in City
TECHNOLOGIES
So, the above is called IIFE. You can write all the functions and variables inside
IIFE without worrying about polluting the global scope or conflict with other's
JavaScript code which have functions or variables with same name.
To solve the our above problem, wrap all the code in [Link] & [Link]
file in IIFE as shown below.
Example: IIFE
(function () {
var userName = "Hafiz";
function display(name)
{
alert("[Link]: " + name);
}
display(userName);
})();
So, even if [Link] & [Link] file includes functions and variables with
the same name, they won't conflict with each other and pollute the global scope.
Also, you can pass arguments in IIFE as shown below.
[Link]
hikmat.kazimi12@[Link]
140
+93(0)789097059
Smart in City
TECHNOLOGIES
Example: IIFE
var userName = "Adeeb";
(function (name) {
function display(name)
{
alert("[Link]: " + name);
}
display(name);
})(userName);
Advantages of IIFE:
1. Do not create unnecessary global variables and functions
2. Functions and variables defined in IIFE do not conflict with other functions
& variables even if they have same name.
3. Organize JavaScript code.
4. Make JavaScript code maintainable.
[Link]
hikmat.kazimi12@[Link]
141
+93(0)789097059
Smart in City
TECHNOLOGIES
JavaScript Test
Test your JavaScript knowledge with a quick test. It includes 20 questions and
each question includes 4 options. Select an appropriate answer out of 4 options.
Send this test to Hikmat.kazimi12@[Link] for your result.
Question#: 1
JavaScript is ECMAScript
False A
True B
May be C
Question#: 2
JavaScript written under which of the following tag?
<JavaScript> </JavaScript> A
<script> </script> B
<code> </code> C
<head> </head> D
[Link]
hikmat.kazimi12@[Link]
142
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 3
Variable in JavaScript declared with which of the following keyword?
new A
int B
string C
var D
Question#: 4
Which of the followings are primitive data types in JavaScript?
String A
Number B
Boolean C
[Link]
hikmat.kazimi12@[Link]
143
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 5
Which of the following is NOT a JavaScript object?
Question#: 6
Which of the following is NOT a correct way of declaring an array in
JavaScript?
[Link]
hikmat.kazimi12@[Link]
144
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 7
What is null in JavaScript?
Question#: 8
Which of the following is a valid JavaScript function?
function myFunc(){ }’ B
myFunc function(){ }; C
function myFunc = { }; D
[Link]
hikmat.kazimi12@[Link]
145
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 9
Which of the following object represent parameters of current function
inside any function?
Global A
arguments B
this C
Object D
Question#: 10
A function can be assigned to a variable in JavaScript.
True A
False B
Some time C
[Link]
hikmat.kazimi12@[Link]
146
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 11
Which of the following is an example of anonymous function in JavaScript?
function(){ }; B
Question#: 12
What will 1 == "1" return?
True A
False B
0 C
1 D
[Link]
hikmat.kazimi12@[Link]
147
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 13
What is eval() in JavaScript?
Question#: 14
How to handle error in JavaScript?
By using eval(). B
[Link]
hikmat.kazimi12@[Link]
148
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 15
How to apply strict mode in JavaScript?
“strict mode” A
“strict” B
“use strict” C
“apply strict” D
Question#: 16
A variable declared without var keyword inside a function will become
_______ variable.
local A
global B
block C
undefined D
[Link]
hikmat.kazimi12@[Link]
149
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 17
Which of the following is not a valid keyword in JavaScript?
function A
this B
module C
try D
Question#: 18
What will be the output of the following JavaScript code?
x = 1;
[Link]('x = ' + x);
var x;
x=1 A
error: x is undefined B
x = undefined C
x = null; D
[Link]
hikmat.kazimi12@[Link]
150
+93(0)789097059
Smart in City
TECHNOLOGIES
Question#: 19
What will be the output of the following JavaScript code?
for(var x = 1; x < 5; x++)
[Link](x);
11111 A
12345 B
1234 C
5555 D
Question#: 20
What will be the output of the following JavaScript code?
var x = 0
do{ [Link](x) }while(x > 0)
0 A
null B
1 C
No output D
[Link]
hikmat.kazimi12@[Link]
151
+93(0)789097059