[Go to site: main page, start]

0% found this document useful (0 votes)
8 views151 pages

JavaScript Basics and Setup Guide

Uploaded by

hamidzoilala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views151 pages

JavaScript Basics and Setup Guide

Uploaded by

hamidzoilala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Smart in City

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.

Browser JavaScript Engine


Internet Explorer v9.0+ Chakra
Chrome V8
FireFox JagerMonkey
Opera v 14+ V8
Safari JavaScriptCore (Nitro)

Comparison with Server-side Languages


JavaScript is different when compared to server side languages like Java and
C#.
The following table lists the differences.

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.

Setup Development Environment for JavaScript


In order to work with JavaScript, you need to install the following tools:
Browser & Editor
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. [Link], [Link] or [Link]

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

//write JavaScript here...

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

Example: Script tag in HTML 4.x:

<script type="text/javascript">

//write JavaScript here...

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

Script Tag into <head> Tag


You can include script tag into head tag as shown below.
Example: Script tag into <head> 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>

<p>This is JavaScript sample.</p>

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

Script at the end of <body>


Scripts can also be added at the end of body tag. This way you can be sure that
all the web page resources are loaded and it is safe to interact with DOM.
Example: Script at the end of <body> tag:
<!DOCTYPE html>

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

<!--Some HTML here.. -->

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

"Hello World" //JavaScript string in double quotes

'Hello World' //JavaScript string in single quotes

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

Display Popup Message Box


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

Alert 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

alert(100); // display number

alert(true); // display boolean

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

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

Example: Confirm Box


var userPreference;

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


userPreference = "Data saved successfully!";
} else {
userPreference = "Save Cancelled!";
}

[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]);

Example: prompt Box


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

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

Example: Variable Declaration & Initialization


var // variable stores numeric value

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

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

In the above example, we have declared three variables using var keyword: one,
two and three. We have assigned values to variables one and two at the same
time when we declared it, whereas variable three is declared but does not hold
any value yet, so it's value will be 'undefined'.
Declare Variables in 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;

Declare a Variable without var Keyword


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

[Link]
hikmat.kazimi12@[Link]
15
+93(0)789097059
Smart in City
TECHNOLOGIES

Example: Variable without var Keyword


>

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.

White Spaces and Line Breaks in JavaScript


JavaScript allows multiple white spaces and line breaks when you declare a
variable with var keyword.
Example: Whitespace and Line Breaks
var
one
=

1,
two
=
"two"

Please note that semicolon is optional.

[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

// string value

// decimal value

// Boolean value

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

JavaScript includes following categories of operators.


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

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between
numeric operands.

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

[Link]
hikmat.kazimi12@[Link]
18
+93(0)789097059
Smart in City
TECHNOLOGIES

The following example demonstrates how arithmetic operators perform


different tasks on operands.
Example: Arithmetic Operator
var x = 5, y = 10, z = 15;

x + y; //returns 15

y - x; //returns 5

x * y; //returns 50

y / x; //returns 2

x % 2; //returns 1

x++; //returns 6

x--; //returns 4

+ operator performs concatenation operation when one of the operands is of


string type.
The following example shows how + operator performs operation on operands
of different data types.
Example: + operator
var a = 5, b = "Hello ", c = "World!", d = 10;

a + b; // "5Hello "

b + c; // "Hello World!"

a + d; // 15

[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 === c; // returns false

a == x; // returns true

a != b; // returns true

a > b; // returns false

a < b; // returns true

a >= b; // returns false

a <= b; // returns true

a >= c; // returns true

a <= c; // 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)

Example: Logical Operators


var a = 5, b = 10;

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

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

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

!(a < b); // returns false

!(a > b); // returns true

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

Example: Assignment operators


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

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

Ternary operator starts with conditional expression followed by ? operator.


Second part ( after ? and before : operator) will be executed if condition turns
out to be true. If condition becomes false then third part (after :) will be
executed.
Example: Ternary operator
var a = 10, b = 5;
var c = a > b? a : b; // value of c would be 10
var d = a > b? b : a; // value of d would be 5

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

JavaScript Data Types


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

Primitive Data Types


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

Non-primitive Data Type


1. Object
2. Date
3. Array
JavaScript is a dynamic or loosely-typed language because a variable can hold
value of any data type at any point of time.
Example: Loosely-typed JavaScript
var myVar = 100;
myVar = true;
myVar = null;
myVar = undefined;
myVar = "Hikmat";

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'

String value can be assigned to a variable using equal to (=) operator.

Example: String literal assigned to a variable


var str1 = "Hello World";

var str2 = 'Hello World';

A string can also be treated like zero index based character array.

Example: String as array


var str = 'Hello World';

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.

Example: Iterate String


var str = 'Hello World';

for(var i =0; i< [Link]; i++)


[Link](str[i]);

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

Include quotation marks inside string


Use quotation marks inside string value that does not match the quotation
marks surrounding the string value. For example, use single quotation marks if
the whole string is enclosed with double quotation marks and visa-versa.
Example: Quotes in string
var str1 = "This is 'simple' string";

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

If you want to include same quotes in a string value as surrounding quotes then
use backward slash (\) before quotation mark inside string value.
Example: Quotes in string
var str1 = "This is \"simple\" string";

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

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

Example: String object


var str1 = new String();
str1 = 'Hello World';

// or

var str2 = new String('Hello World');

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.

Example: String object comparison


var str1 = new String('Hello World');
var str2 = new String('Hello World');
var str3 = 'Hello World';
var str4 = str1;

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

JavaScript String Methods & Properties


JavaScript string (primitive or String object) includes default properties and
methods which you can use for different purposes.

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.

indexOf(SearchString, Position) Returns the index of first occurrence of specified String


starting from specified number index. Returns -1 if not
found.

lastIndexOf(SearchString, Returns the last occurrence index of specified SearchString,


Position) starting from specified position. Returns -1 if not found.

localeCompare(string,position) Compares two strings in the current locale.


match(RegExp) Search a string for a match using specified regular
expression. Returns a matching array.
replace(searchValue, Search specified string value and replace with specified
replaceValue) replace Value string and return new string. Regular
expression can also be used as searchValue.

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

slice(startNumber, endNumber) Extracts a section of a string based on specified starting


and ending index and returns a new string.
split(separatorString, Splits a String into an array of strings by separating the
limitNumber) string into substrings based on specified separator. Regular
expression can also be used as separator.

substr(start, length) Returns the characters in a string from specified starting


position through the specified number of characters
(length).

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.

toLocaleUpperCase() Converts a sting to upper case according to current locale.

toLowerCase() Returns lower case string value.


toString() Returns the value of String object.
toUpperCase() Returns upper case string value.
valueOf() Returns the primitive value of the specified string object.

[Link]
hikmat.kazimi12@[Link]
30
+93(0)789097059
Smart in City
TECHNOLOGIES

String Methods for Html


The following string methods convert the string as a HTML wrapper element.

Method Description
anchor() Creates an HTML anchor <a>element around string value.

big() Wraps string in <big> element.

blink() Wraps a string in <blink> tag.

bold() Wraps string in <b> tag to make it bold in HTML.

fixed() Wraps a string in <tt> tag.

fontcolor() Wraps a string in a <font color="color"> tag.

fontsize() Wraps a string in a <font size="size"> tag.

italics() Wraps a string in <i> tag.

link() Wraps a string in <a>tag where href attribute value is set to


specified string.

small() Wraps a string in a <small>tag.

strike() Wraps a string in a <strike> tag.

sub() Wraps a string in a <sub>tag

sup() Wraps a string in a <sup>tag

[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);

Caution: Be careful while working with the Number object because


comparison of Number objects using == operator compares Number objects and
not the values. Consider the following example.
Example: Number Object Comparison
var num1 = new Number(100);
var num2 = new Number(100);
var num3 = 100;
num1 == num2; // false - because num1 and num2 are two different
objects
num1 == num3; // true
num1 === num3;//false
typeof(num1); // object
typeof(num3); //number

[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).

Example: Number properties


alert(' Max Value: ' + Number.MAX_VALUE +
'\n Min Value:' + Number.MIN_VALUE +
'\n Negative Infinity:' + Number.NEGATIVE_INFINITY +
'\n Positive Infinity:' + Number.POSITIVE_INFINITY +
'\n NaN:' + [Link]
);

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

Example: var num = new Number(100);


[Link](); // returns '100'

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

The following example demonstrates how a Boolean value controls the


program flow using if condition.
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

Any type of comparison will return a Boolean result.


Example: Boolean

alert(1 > 2); // false

alert(10< 9); // false

alert(5 == 5); // true

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

var bool2 = new Boolean(0); // false

var bool3 = new Boolean(undefined); // false

var bool4 = new Boolean(null); // false

var bool5 = new Boolean(NaN); // false

var bool6 = new Boolean("some text"); // true

var bool7 = new Boolean(1); // true

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

Example: var result = (1 > 2); [Link]();


// returns "false"

toString() Returns a string of Boolean.

Example: var result = (1 > 2); [Link](); //


returns "false"

valueOf() Returns the value of the Boolean object.

Example: var result = (1 > 2); [Link](); //


returns false

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.

JavaScript objects and JSON objects are different.


In other programming languages like Java or C#, you need a class to create an
object of it. In JavaScript, an object is a standalone entity because there is no
class in JavaScript. However, you can achieve class like functionality using
functions. We will learn how to treat a function as a class in the advance
JavaScript section.
Let's learn how to create an object in JavaScript.
In JavaScript, an object can be created in two ways:
1. Object literal
2. Object constructor

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

The following example creates an object using object literal syntax.

Example: Create Object using Object Literal Syntax


var emptyObject = {}; // object with no properties or methods

var person = { firstName: "Hafiz" }; // object with single property

// object with single method


var message = {
showMessage: function (val) {
alert(val);
}
};

// object with properties & method


var person = {
firstName: "Hafiz",
lastName: "Basam",
age: 15,
getFullName: function () {
return [Link] + ' ' + [Link]
}
};

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

var person = { firstName: };

[Link]
hikmat.kazimi12@[Link]
39
+93(0)789097059
Smart in City
TECHNOLOGIES

Access JavaScript Object Properties & Methods


You can get or set values of an object's properties using dot notation or bracket.
However, you can call an object's method only using dot notation.
Example: Access JS Object
var person = {
firstName: "Khesraw",
lastName: "Rahbin",
age: 25,
getFullName: function () {
return [Link] + ' ' + [Link]
}
};

[Link]; // returns Khesraw


[Link]; // returns Rahbin

person["firstName"];// returns Khesraw


person["lastName"];// returns Rahbin

[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();

// Attach properties and methods to person object


[Link] = "Hikmat";
person["lastName"] = "Kazimi";
[Link] = 25;
[Link] = function () {
return [Link] + ' ' + [Link];
};

// access properties & methods


[Link]; // Hikmat
[Link]; // Kazimi
[Link](); // Hikmat Kazimi

Undefined Property or Method


JavaScript will return 'undefined' if you try to access properties or call methods
that do not exist.
If you are not sure whether an object has a particular property or not, then use
hasOwnProperty() method before accessing properties.
Example: hasOwnProperty()
var person = new Object();

[Link]; // returns undefined

if([Link]("firstName")){
[Link];
}

[Link]
hikmat.kazimi12@[Link]
41
+93(0)789097059
Smart in City
TECHNOLOGIES

Access Object Keys.


Use for..in loop to get the list of all properties and methods of an object.
Example: Access Object Keys
var person = new Object();

[Link] = "Hikmat";
person["lastName"] = "Kazimi";
[Link] = 25;
[Link] = function () {
return [Link] + ' ' + [Link];
};

for(var key in person){


alert(key);
};

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";
}

var person = { firstName : "Kazimi" };

changeFirstName(person)

[Link]; // returns Hikmat

[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" };

var anotherPerson = person;

[Link] = "Hikmat";

[Link]; //returns Hikmat

Nested JavaScript Objects


You can assign another object as a property of an object.
Example: Nested JS Objects
var person = {
firstName: "Hikmat",
lastName: "",
age: 25,
address: {
id: 1,
country:"AFG"
}
};

[Link]; // returns "AFG"

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. };

9. Object properties and methods can be accessed using dot notation or [ ]


bracket.
10. An object is passed by reference from one function to another.
11. An object can include another object as a property.

[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

Date(); //current date

//or

var currentDate = new Date(); //current date

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();

var dt = new Date(milliseconds);

var dt = new Date('date string');

var dt = new Date(year, month[, date, hour, minute, second,


millisecond]);

[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

var date2 = new Date(1000); // Thu Jan 01 1970 05:30:01

var date3 = new Date(5000); // Thu Jan 01 1970 05:30:05

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

Example: Create Date by Specifying Date String


var date1 = new Date("3 march 2015");

var date2 = new Date("3 February, 2015");

var date3 = new Date("3rd February, 2015"); // invalid date

var date4 = new Date("2015 3 February");

var date5 = new Date("3 2015 February ");

var date6 = new Date("February 3 2015");

var date7 = new Date("February 2015 3");

var date8 = new Date("2 3 2015");

var date9 = new Date("3 march 2015 20:21:44");

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");

var date2 = new Date("February-2015-3");

var date3 = new Date("February-2015-3");

var date4 = new Date("February,2015-3");

var date5 = new Date("February,2015,3");

var date6 = new Date("February*2015,3");

var date7 = new Date("February$2015$3");

var date8 = new Date("3-2-2015"); // MM-dd-YYYY

var date9 = new Date("3/2/2015"); // MM-dd-YYYY

[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 115, no of years after 1900

[Link]();// returns 2015

[Link]();// returns 3, starting 0 with jan

[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

Convert Date Format


Use different Date methods to convert a date from one format to another
format e.g. to Universal Time, GMT or local time format.
For example, use ToUTCString(), ToGMTString(), ToLocalDateString(),
ToTimeString() methods to convert date into respective formats.
Example: Date Conversion in Different Formats
var date = new Date('2015-02-10T10:12:50.5000z');

date; 'Default format:'

[Link]();'Tue Feb 10 2015'

[Link]();'2/10/2015'

[Link](); 'GMT format'

[Link](); '2015-02-10T10:12:50.500Z'

[Link]();'Local date Format '

[Link](); 'Locale time format '

[Link]('YYYY-MM-dd'); 'Tue Feb 10 2015 15:42:50'

[Link](); '15:42:50'

[Link](); 'UTC format '

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

var date = new Date([Link]("5/2/2015")); // Sat May 02 2015


00:00:00

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');

if (date1 > date2)


alert(date1 + ' is greater than ' + date2);
else (date1 < date2 )
alert(date1 + ' is less than ' + date2);

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

Date Methods Reference


The following table lists all the get methods of Date object.

Method Description
getDate() Returns numeric day (1 - 31) of the specified date.

getDay() Returns the day of the week (0 - 6) for the specified


date.

getFullYear() Returns four digit year of the specified date.

getHours() Returns the hour (0 - 23) in the specified date.

getMilliseconds() Returns the milliseconds (0 - 999) in the specified


date.

getMinutes() Returns the minutes (0 - 59) in the specified date.

getMonth() Returns the month (0 - 11) in the specified date.

getSeconds() Returns the seconds (0 - 59) in the specified date.

getTime() Returns the milliseconds as number since January 1,


1970, 00:00:00 UTC.

getTimezoneOffset() Returns the time zone offset in minutes for the


current locale.

getUTCDate() Returns the day (1 - 31) of the month of the specified


date as per UTC time zone.

getUTCDay() Returns the day (0 - 6) of the week of the specified


date as per UTC timezone.

getUTCFullYear() Returns the four digits year of the specified date as


per UTC time zone.

getUTCHours() Returns the hours (0 - 23) of the specified date as


per UTC time zone.

getUTCMilliseconds() Returns the milliseconds (0 - 999) of the specified


date as per UTC time zone.

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

getUTCMonth() Returns the month (0 - 11) of the specified date as


per UTC time zone.

getUTCSeconds() Returns the seconds (0 - 59) of the specified date as


per UTC time zone.

getYear() Returns the no of years of the specified date since


1990. This method is Deprecated

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.

setMilliseconds() Sets the milliseconds as number in the date object.

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

Returns the date segment from the specified date,


toDateString() excludes time.
toGMTString() Returns a date string in GMT time zone.

toLocaleDateString() Returns the date segment of the specified date using the current
locale.

toLocaleFormat() Returns a date string in default format.

toLocaleString() Returns a date string using a current locale format.

toLocaleTimeString() Returns the time segment of the specified Date as a string.

toString() Returns a string for the specified Date object.

toTimeString() Returns the time segment as a string from the specified date object.

toUTCString() Returns a string as per UTC time zone.

valueOf() Returns the primitive value of a 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"];

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

var decimalArray = [1.1, 1.2, 1.3];

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

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

[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();

var arrayName = new Array(Number length);

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


As you can see in the above syntax, an array can be initialized
using new keyword, in the same way as an object.
The following example shows how to define an array using Array constructor
syntax.
Example: Array Constructor Syntax
var stringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";

var numericArray = new Array(3);


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

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

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

[Link]
hikmat.kazimi12@[Link]
55
+93(0)789097059
Smart in City
TECHNOLOGIES

Example: Incorrect Array Index


var stringArray = new Array();

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

Accessing Array Elements


An array elements (values) can be accessed using index (key). Specify an index
in square bracket with array name to access the element at particular index.
Please note that index of an array starts from zero in JavaScript.
Example: Access Array Elements
var stringArray = new Array("one", "two", "three", "four");

stringArray[0]; // returns "one"


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

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


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

Array Properties
Array includes "length" property which returns number of elements in the array.
Use for loop to access all the elements of an array using length property.
Example: Access Array using for Loop
var stringArray = new Array("one", "two", "three", "four");

for (var i = 0; i < [Link] ; i++)


{
stringArray[i];
}

[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

Array Methods Reference


The following table lists all the Array methods.

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.

forEach() Executes a callback function for each elements of an array.

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.

sort() Sorts the elements of an array.

splice() Adds and/or removes elements from an array.

toString() Returns a string representing the array and its elements.

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 and undefined in JavaScript


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

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

alert(myVar); // null

In the above example, null is assigned to a variable myVar. It means we have


defined a variable but have not assigned any value yet, so value is absence.

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


If you try to find DOM element using [Link] for example,
and if element is found then it will return null. So it is recommended to check
for null before doing something with that element.
Example: null
var saveButton = [Link]("save");

if (saveButton !== null)


[Link]();

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.

[Link]
hikmat.kazimi12@[Link]
60
+93(0)789097059
Smart in City
TECHNOLOGIES

Example: null in conditional expression


var myVar = null;

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

undefined
Undefined is also a primitive value in JavaScript. A variable or an object has an
undefined value when no value is assigned before using it. So you can say that
undefined means lack of value or unknown value.
Example: undefined
var myVar;

alert(myVar); // undefined

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


In the above example, we have not assigned any value to a variable named
'myVar'. A variable 'myVar' lacks a value. So it is undefined.
You will get undefined value when you call a non-existent property or method
of an object.
Example: undefined
function Sum(val1, val2)
{
var result = val1 + val2;
}

var result = Sum(5, 5);


alert(result);// undefined

[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);

An undefined evaluates to false when used in conditional expression.


Example: undefined in Conditional Expression
var myVar;

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

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();

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.

[Link]
hikmat.kazimi12@[Link]
63
+93(0)789097059
Smart in City
TECHNOLOGIES

Example: Function Parameters


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

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", "Mr."); // display Hello Adeeb Kakar


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

The Arguments Object


All the functions in JavaScript can use arguments object by default. An
arguments object includes value of each parameter.
The arguments object is an array like object. You can access its values using index
similar to array. However, it does not support array methods.
Example: Arguments Object
function ShowMessage(firstName, lastName) {
alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("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"); // display Hello Adeeb Kakar

An arguments object can be iterated using for loop.


Example: Iterate all Arguments
function ShowMessage() {

for(var i = 0; i < [Link]; i++){


alert(arguments[i]);
}
}

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

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

function Multiply(val1, val2) {


[Link]( val1 * val2);
};

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

[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;
}

var triple = multiple(3);


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

Function Expression
JavaScript allows us to assign a function to a variable and then use that
variable as a function. It is called function expression.
Example: Function Expression
var add = function sum(val1, val2) {
return val1 + val2;
};

var result1 = add(10,20);


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

[Link]
hikmat.kazimi12@[Link]
66
+93(0)789097059
Smart in City
TECHNOLOGIES

Anonymous Function

Anonymous function is useful in passing callback function, creating


closure or Immediately invoked function expression.
JavaScript allows us to define a function without any name. This unnamed
function is called anonymous function. Anonymous function must be assigned
to a variable.
Example: Anonymous Function
var showMessage = function (){
alert("Hello World!");
};

showMessage();

var sayHello = function (firstName) {


alert("Hello " + firstName);
};

showMessage();

sayHello("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

JavaScript if else Condition


JavaScript includes if-else conditional statements to control the program flow,
similar to other programming languages.
JavaScript includes following forms of if-else conditions:
1. if condition
2. if-else condition
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.

[Link]
hikmat.kazimi12@[Link]
69
+93(0)789097059
Smart in City
TECHNOLOGIES

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


Example: if condition
var mySal = 1000;
var yourSal = 500;

if( mySal > yourSal)


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

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

Example: else condition


var mySal = 500;
var yourSal = 1000;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
else
{
alert("My Salary is less than or equal to your salary");
}

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

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
else if(mySal < yourSal)
{
alert("My Salary is less than your salary");
}
JavaScript allows multiple else if statements also.
Example: Multiple if else conditions
var mySal = 500;
var yourSal = 1000;

if( mySal > yourSal)


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

[Link]
hikmat.kazimi12@[Link]
72
+93(0)789097059
Smart in City
TECHNOLOGIES

We will learn about switch case in the next section.

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

Example: switch Statement


var a = 3;

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

In the above example, switch statement contains a literal value as expression.


So, the case that matches a literal value will be executed, case 3 in the above
example.
The switch statement can also include an expression. A case that matches the
result of an expression will be executed.
Example: switch Statement
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");
}

[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;
}

Multiple cases can be combined in a switch statement.


Example: Combined switch Cases
var a = 2;

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

[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

JavaScript for Loop


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

:
Syntax:
for(initializer; condition; iteration)
{
// Code to be executed
}
The for loop requires following three parts.
 Initializer: Initialize a counter variable to start with
 Condition: specify a condition that must evaluate to true for next
iteration
 Iteration: increase or decrease counter

Example: for loop


for (var i = 0; i < 5; i++)
{
[Link](i);
}

Output:
0 1 2 3 4

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


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

[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];

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


{
[Link](arr[i]);
}

Output:
10 11 12 13 14

Please note that it is not mandatory to specify an initializer, condition and


increment expression into bracket. You can specify initializer before starting for
loop. The condition and increment statements can be included inside the block.
Example: for loop
var arr = [10, 11, 12, 13, 14];
var i = 0;

for (; ;) {

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 */
}

Example: while loop


var i =0;

while(i < 5)
{
[Link](i);
i++;
}

Output:
0 1 2 3 4

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.

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

var userName = "Hafiz";

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

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

alert(userName); // display Hafiz

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>

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

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

Function parameters are considered as local variables.


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. Use try catch block for exception handling.

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

function Sum(val1, val2)


{
return val1 + val2;
}

eval("result = Sum(5, 5);");

alert(result);

eval can convert string to JSON object.


Example: eval with JSON Object
var str = '({"firstName":"Hafiz","lastName":"Basam"})';

var obj = eval(str);

[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

Error handling in JavaScript


JavaScript is a loosely-typed language. It does not give compile time. So some
times you will get a runtime error for accessing an undefined variable or calling
undefined function etc.

try catch block does not handle syntax errors.


JavaScript provides error-handling mechanism to catch runtime errors using try-
catch-finally block, similar to other languages like Java or C#.
Syntax:
try
{
// code that may throw an error
}
catch(ex)
{
// code to be executed if an error occurs
}
finally{
// code to be executed regardless of an error occurs or not
}
 try: wrap suspicious code that may throw an error in try block.
 catch: write code to do something in catch block when an error occurs.
The catch block can have parameters that will give you error information.
Generally catch block is used to log an error or display specific messages
to the user.
 finally: code in the finally block will always be executed regardless of
the occurrence of an error. The finally block can be used to complete the
remaining task or reset variables that might have changed before error
occurred in try block.
Let's look at simple error handling examples.

[Link]
hikmat.kazimi12@[Link]
90
+93(0)789097059
Smart in City
TECHNOLOGIES

Example: Error Handling in JS


try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
[Link]("errorMessage").innerHTML = ex;
}
In the above example, we are calling function Sum, which is not defined yet. So,
try block will throw an error which will be handled by catch block. Ex includes
error message that can be displayed.
The finally block executes regardless of whatever happens.
Example: finally Block
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
[Link]("errorMessage").innerHTML = ex;
}
finally{
[Link]("message").innerHTML = "finally block
executed";
}

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

JavaScript strict mode


JavaScript is a loosely typed (dynamic) scripting language. If you have worked
with server side languages like Java or C#, you must be familiar with the
strictness of the language. For example, you expect the compiler to give an error
if you have used a variable before defining it.
JavaScript allows strictness of code using "use strict" with ECMAScript 5 or later.
Write "use strict" at the top of JavaScript code or in a function.
Example: strict mode
"use strict";

var x = 1; // valid in strict mode


y = 1; // invalid in strict mode

The strict mode in JavaScript does not allow following things:


1. Use of undefined variables
2. Use of reserved keywords as variable or function name
3. Duplicate properties of an object
4. Duplicate parameters of function
5. Assign values to read-only properties
6. Modifying arguments object
7. Octal numeric literals
8. with statement
9. eval function to create a variable
Let look at an example of each of the above.
Use of undefined variables:
Example: strict mode
"use strict";

x = 1; // error

[Link]
hikmat.kazimi12@[Link]
93
+93(0)789097059
Smart in City
TECHNOLOGIES

Use of reserved keyword as name:


Example: strict mode
"use strict";

var for = 1; // error


var if = 1; // error

Duplicate property names of an object:


Example: strict mode
"use strict";

var myObj = { myProp: 100, myProp:"test strict mode" }; // error

Duplicate parameters:
Example: strict mode
"use strict";

function Sum(val, val){return val + val }; // error

Assign values to read-only property:


Example: strict mode
"use strict";

var arr = [1 ,2 ,3 ,4, 5];


[Link] = 10; // error

Modify arguments object:


Example: strict mode
"use strict";

function Sum(val1, val2){


arguments = 100; // error
}

[Link]
hikmat.kazimi12@[Link]
94
+93(0)789097059
Smart in City
TECHNOLOGIES

Octal literals:
Example: strict mode
"use strict";

var oct = 030; // error

with statement:

Example: strict mode


"use strict";

with (Math){
x = abs(200.234, 2); // error
};

Eval function to create a variable:

Example: strict mode


"use strict";

eval("var x = 1");// error

Strict mode can be applied to function level in order to implement strictness


only in that particular function.
Example: strict mode

x = 1; //valid

function sum(val1, val2){


"use strict";

result = val1 + val2; //error

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;

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

var x;

The following figure illustrates hoisting.

JavaScript Hoisting

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


Example: Hoisting
x = 1;
y = x;

alert('x = ' + x);


alert('y = ' + y);

var x;
var y;

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

Example: Hoisting not applicable for initialized variables


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

var x = 1;

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

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

Example: Function Hoisting


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

function Sum(val1, val2)


{
return val1 + val2;
}

Please note that JavaScript compiler does not move function expression.
Example: Hoisting on function expression

Add(5, 5); // error

var Add = function Sum(val1, val2)


{
return val1 + val2;
}

[Link]
hikmat.kazimi12@[Link]
97
+93(0)789097059
Smart in City
TECHNOLOGIES

Hoisting Functions Before Variables


JavaScript compiler moves a function's definition before variable declaration.
The following example proves it.
Example: Function Hoisting Before Variables
alert(UseMe);

var UseMe;

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

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


function moves before variables.

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

Advanced (Section) Java Script


Define Class in JavaScript
JavaScript ECMAScript 5, does not have class type. So it does not support full
object oriented programming concept as other languages like Java or C#.
However, you can create a function in such a way so that it will act as a class.
The following example demonstrates how a function can be used like a class in
JavaScript.
Example: Class in JavaScript
function Person() {
[Link] = "unknown";
[Link] = "unknown";
}

var person1 = new Person();


[Link] = "Hikmat";
[Link] = "Kazimi";

alert([Link] + " " + [Link]);

var person2 = new Person();


[Link] = "Khesraw";
[Link] = "Rahbin";

alert([Link] + " " + [Link] );

In the above example, a Person() function includes firstName, lastName &


age variables using this keyword. These variables will act like properties. As you
know, we can create an object of any function using new keyword, so person1
object is created with new keyword. So now, Person will act as a class and
person1 & person2 will be its objects (instances). Each object will hold their
values separately because all the variables are defined with this keyword which
binds them to particular object when we create an object using new keyword.
So this is how a function can be used like a class in the JavaScript.

[Link]
hikmat.kazimi12@[Link]
99
+93(0)789097059
Smart in City
TECHNOLOGIES

Add Methods in a Class


We can add a function expression as a member variable in a function in
JavaScript. This function expression will act like a method of class.

Example: Method in Class


function Person() {
[Link] = "unknown";
[Link] = "unknown";
[Link] = function(){
return [Link] + " " + [Link];
}
};

var person1 = new Person();


[Link] = "Khpalwak";
[Link] = "Shinwari";

alert([Link]());

var person2 = new Person();


[Link] = "Zakir";
[Link] = "Malikzai";

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];
}
};

var person1 = new Person("Hikmat","Kazimi",50);


alert([Link]());

var person2 = new Person("Zakir","Malikzai");


alert([Link]());

In the above example, the Person function includes three parameters


FirstName, LastName and Age. These parameters are used to set the values of a
respective property.

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

Properties with Getters and Setters


As you learned in the previous section, [Link]() method
can be used to define a property with getter & setter.
The following example shows how to create a property with getter & setter.
Example: Property
function Person() {
var _firstName = "unknown";

[Link](this, {
"FirstName": {
get: function () {
return _firstName;
},
set: function (value) {
_firstName = value;
}
}
});
};

var person1 = new Person();


[Link] = "Adeeb";
alert([Link] );

var person2 = new Person();


[Link] = "Hikmat";
alert([Link] );

In the above example, the Person() function creates a FirstName property by


using [Link]() method. The first argument is this, which binds
FirstName property to calling object. Second argument is an object that includes
list of properties to be created. We have specified FirstName property with get
& set function. You can then use this property using dot notation as shown
above.

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

Example: Read-only Property


function Person(firstName) {

var _firstName = firstName || "unknown";

[Link](this, {
"FirstName": {
get: function () {
return _firstName;
}
}
});
};
var person1 = new Person("Hikmat");
//[Link] = "Hikmat"; -- will not work
alert([Link] );

var person2 = new Person("Khesraw");


//[Link] = "Khesraw"; -- 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];
}
};

var person1 = new Person();


[Link] = "Hikmat";
[Link] = "Kazimi";

alert([Link]());

[Link]
hikmat.kazimi12@[Link]
104
+93(0)789097059
Smart in City
TECHNOLOGIES

JavaScript Object in Depth


You have already learned about JavaScript object in the JavaScript Basics
section. Here, you will learn about object in detail.
As you know, object in JavaScript can be created using object literal, object
constructor or constructor function. Object includes properties. Each property
can either be assigned a literal value or a function.
Consider the following example of objects created using object literal and
constructor function.

Example: JavaScript Object


// object literal
var person = {
firstName:'Hafiz',
lastName:'Basam'
};

// 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();

//enumerate properties of student1


for(var prop in student1){
[Link](prop);
}
Output:
title name gender sayHi

[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')

The getOwnPropertyDescriptor method returns a property descriptor for a


property that directly defined in the specified object but not inherited from
object's prototytpe.
The following example display property descriptor to the console.
Example: Property Descriptor
var person = {
firstName:'Adeeb',
lastName:'Kakar'
};

function Student(){
[Link] = "Khpalwak";
[Link] = "Male";
[Link] = function(){
alert('Hi');
}
}

var student1 = new Student();

[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

The following example demonstrates modifying property descriptor.


Example: Edit Property Descriptor
'use strict'

function Student(){
[Link] = "Hikmat";
[Link] = "Male";

var student1 = new Student();

[Link](student1,'name', { writable:false} );

try
{
[Link] = "Khesraw";
[Link]([Link]);
}
catch(ex)
{
[Link]([Link]);
}

The above example, it modifies writable attribute of name property


of student1 object using [Link](). So, name property
can not be changed. If you try to change the value of name property then it
would throw an exception in strict mode. In non-strict mode, it won't throw an
exception but it also won't change a value of name property either.
The same way, you can change enumerable property descriptor as shown below.

[Link]
hikmat.kazimi12@[Link]
109
+93(0)789097059
Smart in City
TECHNOLOGIES

Example: Edit Property Descriptor


function Student(){
[Link] = "Hikmat";
[Link] = "Male";
}

var student1 = new Student();

//enumerate properties of student1


for(var prop in student1){
[Link](prop);
}

//edit enumerable attributes of name property to false


[Link](student1,'name',{ enumerable:false });

[Link]('After setting enumerable to false:');

for(var prop in student1){


[Link](prop);
}

Output:
name
gender

After setting enumerable to false:


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

Example: Edit Property Descriptor


'use strict';

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]);
}

In the above example,


[Link](student1,'name',{configurable:false}); sets
configurable attribute to false which make student1 object non configurable
after
that. [Link](student1,'name',{writable:false}); sets
writable to false which will throw an exception in strict mode because we
already set configurable to false.

[Link]
hikmat.kazimi12@[Link]
111
+93(0)789097059
Smart in City
TECHNOLOGIES

Define New Property


The [Link]() method can also be used to define a new properties
with getters and setters on an object as shown below.
Example: Define New Property
function Student(){
[Link] = "Mr.";
[Link] = "Hikmat";
}

var student1 = new Student();

[Link](student1,'fullName',{
get:function(){
return [Link] + ' ' + [Link];
},
set:function(_fullName){
[Link] = _fullName.split(' ')[0];
[Link] = _fullName.split(' ')[1];
}
});

[Link] = "Mr. Hikmat";

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

WhoIsThis(); // inferred as [Link]()

var obj = new WhoIsThis();


alert([Link]);
</script>

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;

alert("myVar = " + myVar); // 200


alert("[Link] = " + [Link]); // 100
}

WhoIsThis(); // inferred as [Link]()


</script>

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

The following figure illustrates the above example.

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;

alert("myVar = " + myVar); // 200


alert("[Link] = " + [Link]); // 100
}

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.

this Inside Object's Method


As you have learned here, you can create an object of a function using new
keyword. So, when you create an object of a function using new keyword
then this will point to that particular object. Consider the following example.
Example: this keyword
var myVar = 100;

function WhoIsThis() {
[Link] = 200;
}
var obj1 = new WhoIsThis();

var obj2 = new WhoIsThis();


[Link] = 300;

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

Now look at the following example.


Example: this keyword
var myVar = 100;

function WhoIsThis() {
[Link] = 200;

[Link] = function(){
var myVar = 300;

alert("myVar = " + myVar); // 300


alert("[Link] = " + [Link]); // 200
};
}
var obj = new WhoIsThis();

[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

call() and apply()


In JavaScript, a function can be invoked using () operator as well as call() and
apply() method as shown below.
Example: Function call
function WhoIsThis() {
alert('Hi');
}

WhoIsThis();
[Link]();
[Link]();

In the above example, WhoIsThis(), [Link]() and [Link]()


executes a function in the same way.
The main purpose of call() and apply() is to set the context of this inside a
function irrespective whether that function is being called in the global scope or
as object's method.
You can pass an object as a first parameter in call() and apply() to which
the this inside a calling function should point to.
The following example demonstrates the call() & apply().
Example: call() & apply()
var myVar = 100;

function WhoIsThis() {

alert([Link]);
}

var obj1 = { myVar : 200 , whoIsThis: WhoIsThis };

var obj2 = { myVar : 300 , whoIsThis: WhoIsThis };

WhoIsThis(); // 'this' will point to window object

[Link](obj1); // 'this' will point to obj1

[Link](obj2); // 'this' will point to obj2

[Link]
hikmat.kazimi12@[Link]
118
+93(0)789097059
Smart in City
TECHNOLOGIES

[Link](window); // 'this' will point to window object

[Link](obj2); // 'this' will point to obj2

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

In the above example, when you pass [Link] as a parameter to the


SomeFunction() then this points to global window object insted of obj,
because [Link]() will be executed as a global function by JavaScript
engine. You can solve this problem by explicitly setting this value using bind()
method. Thus, SomeFunction([Link](obj)) will
set this to obj by specifying [Link](obj).

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

JavaScript new Keyword


We have seen in the Object section that an object can be created with new
keyword. Here, you will learn about the steps it performs while creating an
object.
function MyFunc() {
this.x = 100;
}

var obj1 = new MyFunc();


obj1.x;

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;

var obj1 = new MyFunc();


obj1.x; // 100
obj1.y; // 200

Let's understand what happens when you create an object (instance) of


MyFunc() using new keyword.
First of all, new keyword creates an empty object - { }.
Second, it set's invisible 'prototype' property (or attribute) of this empty object
to myFunc's prototype property. As you can see in the above example, we have
assigned new property 'y' using [Link].y. So, new empty object will
also have same prototype property as MyFunc which includes y property.
In third step, it binds all the properties and function declared with this keyword
to new empty object. Here, MyFunc includes only one property x which is
declared with this keyword. So new empty object will now include x property.
MyFunc also includes myVar variable which does not declared with this
keyword. So myVar will not be included in new object.
In the fourth and last step, it will return this newly created object. MyFunc does
not include return statement but compiler will implicitly insert 'return this' at
the end.
So thus, object of MyFunc will be returned using new keyword.
The following figure illustrates the above process.

[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;
}

var obj = new MyFunc();


alert(obj.x); // 100
If function returns non-primitive value (custom object) then new keyword does
not perform above 4 tasks.
Example: new keyword
function MyFunc() {
this.x = 100;

return { a: 123 };
}

var obj1 = new MyFunc();

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';
}

var studObj1 = new Student();


[Link] = 15;
alert([Link]); // 15

var studObj2 = new Student();


alert([Link]); // undefined

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

The prototype object is special type of enumerable object to which additional


properties can be attached to it which will be shared across all the instances of
it's constructor function.
So, use prototype property of a function in the above example in order to have
age properties across all the objects as shown below.
Example: prototype
function Student() {
[Link] = 'Hikmat';
[Link] = 'M';
}

[Link] = 15;

var studObj1 = new Student();


alert([Link]); // 15

var studObj2 = new Student();


alert([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';
}

var studObj = new Student();

[Link]([Link]); // object
[Link]([Link]); // undefined
[Link](studObj.__proto__); // object

[Link](typeof [Link]); // object


[Link](typeof studObj.__proto__); // object

[Link]([Link] === studObj.__proto__ ); // true

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';
}

var studObj = new Student();

[Link]= function(){
alert("Hi");
};

var studObj1 = new Student();


var proto = [Link](studObj1); // returns Student's
prototype object

alert([Link]); // returns Student function

[Link]
hikmat.kazimi12@[Link]
127
+93(0)789097059
Smart in City
TECHNOLOGIES

The prototype object includes following properties and methods.

Property Description
constructor Returns a function that created instance.

__proto__ This is invisible property of an object. It returns prototype object


of a function to which it links to.

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.

isPrototypeOf() Returns a boolean indication whether the specified


object is in the prototype chain of the object this
method is called upon.

propertyIsEnumerable() Returns a boolean that indicates whether the


specified property is enumerable or not.

toLocaleString() Returns string in local format.

toString() Returns string.

valueOf Returns the primitive value of the specified object.

Chrome and Firefox denotes object's prototype as __proto__ which is public


link whereas internally it reference as [[Prototype]]. Internet Explorer does not
include __proto__. Only IE 11 includes it.
The getPrototypeOf() method is standardize since ECMAScript 5 and is
available since IE 9.

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

var studObj1 = new Student();


alert('[Link] = ' + [Link]); // 15

var studObj2 = new Student();


alert('[Link] = ' + [Link]); // 15

[Link] = { age : 20 };

var studObj3 = new Student();


alert('[Link] = ' + [Link]); // 20

alert('[Link] = ' + [Link]); // 15


alert('[Link] = ' + [Link]); // 15

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");
};

var studObj = new Student();


[Link]();

[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] = schoolName || "unknown";


[Link] = grade || 0;
}
//[Link] = [Link];
[Link] = new Person();
[Link] = Student;

[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] = schoolName || "unknown";


[Link] = grade || 0;
}
//[Link] = [Link];
[Link] = new Person();
[Link] = Student;

var std = new Student("Hikmat","Kazimi", "XYZ", 10);

alert([Link]()); // Hikmat Kazimi


alert(std instanceof Student); // true
alert(std instanceof Person); // true

Thus we can implement inheritance in JavaScript.

[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();
}

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


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

[Link]
hikmat.kazimi12@[Link]
133
+93(0)789097059
Smart in City
TECHNOLOGIES

Example: Closure
function OuterFunction() {

var outerVariable = 100;

function InnerFunction() {
alert(outerVariable);
}

return InnerFunction;
}
var innerFunc = OuterFunction();

innerFunc(); // 100

In the above example, return InnerFunction; returns InnerFunction from


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

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


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

[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;
}

var counter = Counter();


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

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 };
})();

When to use Closure?


Closure is useful in hiding implementation detail in JavaScript. In other words, it
can be useful to create private variables or functions.
The following example shows how to create private functions & variable.
Example: Closure
var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();

alert([Link]()); // 0
[Link]();
[Link]();
alert([Link]()); // 2
[Link]();
alert([Link]()); // 1

[Link]
hikmat.kazimi12@[Link]
136
+93(0)789097059
Smart in City
TECHNOLOGIES

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().

Immediately Invoked Function Expression - IIFE


Immediately Invoked Function Expression (IIFE) is one of the most popular
design patterns in JavaScript. It pronounces like iify. IIFE has been used since
long by JavaScript community but it had misleading term "self-executing
anonymous function". Ben Alman gave it appropriate name "Immediately
Invoked Function Expression"
As you know that a function in JavaScript creates the local scope. So, you can
define variables and function inside a function which cannot be access outside
of that function. However, sometime you accidently pollute the global variables
or functions by unknowingly giving same name to variables & functions as global
variable & function names. For example, there are multiple .js files in your
application written by multiple developers over a period of time. Single
JavaScript file includes many functions and so these multiple .js files will result
in large number of functions. There is a good chance of having same name of
function exists in different .js files written by multiple developer and if these files
included in a single web page then it will pollute the global scope by having two
or more function or variables with the same name. Consider following example
of two different JavaScript file included in single page.

[Link]
hikmat.kazimi12@[Link]
137
+93(0)789097059
Smart in City
TECHNOLOGIES

Consider the following example of [Link] and [Link] with same


variable & function name.
Example: [Link]
var userName = "Hikmat";

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

First of all, define a function expression.


Example: IIFE
var myIIFE = function () {
//write your js code here
};

Now, wrap it with parenthesis. However, parenthesis does not allow


declaration. So just remove declaration part and just write anonymous function
as below.
Example: IIFE
(function () {
//write your js code here
});

[Link]
hikmat.kazimi12@[Link]
139
+93(0)789097059
Smart in City
TECHNOLOGIES

Now, use () operator to call this anonymous function immediately after


completion of its definition.
Example: IIFE
(function () {

//write your js code here


})();

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

All of the above D

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

All of the above D

[Link]
hikmat.kazimi12@[Link]
143
+93(0)789097059
Smart in City
TECHNOLOGIES

Question#: 5
Which of the following is NOT a JavaScript object?

var obj = {}; A

var obj = { name: “Hikmat”}; B

var obj = { name = “Hikmat”}; C

var obj = new Object(); D

Question#: 6
Which of the following is NOT a correct way of declaring an array in
JavaScript?

var arr = [1, “two”, 3 , 4 ]; A

var arr = new Array(); B

var[] arr = new Number()[5]; C

None of the above D

[Link]
hikmat.kazimi12@[Link]
144
+93(0)789097059
Smart in City
TECHNOLOGIES

Question#: 7
What is null in JavaScript?

Null means empty string value. A

Null means absence of a value. B

Null means unknown value. C

Null means zero value. D

Question#: 8
Which of the following is a valid JavaScript function?

var myFunc = function myFunc{ }; A

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

None of the above D

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

var myFunc = function(){ }; A

function(){ }; B

var myFunc = (){ }; C

All of the above. D

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?

It executes specified string as JavaScript code.

It returns an object representing the parsed tree of the specified JavaScript


code.

It executes server side code in JavaScript.

It displays popup message.

Question#: 14
How to handle error in JavaScript?

By writing error proof code. A

By using eval(). B

By using if-else block. C

By using try, catch & finally block. D

[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

You might also like