Javascript Es 6 Typescript
Javascript Es 6 Typescript
Module Overview
This module explains about the aspect of web development and its use for full stack development
Module Objective
At the end of this module, students should be able to demonstrate appropriate knowledge, and show
an understanding of the following:
• Web Technology
• HTTP Protocol
• URN
• Web Services
• Web applications
• Full Stack development
• Use of Python, Django Ruby on Rails in full stack development
Introduction to JavaScript
What is JavaScript
JavaScript is a programming language that executes on the browser. It turns static HTML web pages into
interactive web pages by dynamically updating content, validating form data, controlling multimedia,
animate images, and almost everything else on the web pages.
JavaScript is the third most important web technology after HTML and CSS. JavaScript can be used to create
web and mobile applications, build web servers, create games, etc.
JavaScript Example
JavaScript can be used in various activities like data validation, displaying popup messages, handling events
of HTML elements, modifying CSS, etc. The following sample form uses JavaScript to validate data and change
the color of the form.
JavaScript History
In early 1995, Brendan Eich from Netscape designed and implemented a new language for non -java
programmers to give newly added Java support in Netscape navigator. It was initially named Mocha, then
LiveScript, and finally JavaScript.
Nowadays, JavaScript can execute not only on browsers but also on the server or any device with a JavaScript
Engine. For example, Node.js is a framework based on JavaScript that executes on the server.
As you now know, JavaScript was primarily developed to execute on browsers. There are many different
browsers from different companies. So, there was a need to standardize the execution of the JavaScript code
to achieve the same functionality in all the browsers.
Ecma International is a non-profit organization that creates standards for technologies. ECMA International
publishes the specification for scripting languages is called 'ECMAScript'. ECMAScript specification defined
in ECMA-262 for creating a general-purpose scripting language.
There are different editions of ECMAScript. Most browsers have implemented ECMA-262 5.1 edition.
• ECMA-262 5.1 edition, June 2011
• ECMA-262, 6th edition, June 2015
• ECMA-262, 7th edition, June 2016
• ECMA-262, 8th edition, June 2017
• ECMA-262, 9th edition, June 2018
• ECMA-262, 10th edition, June 2019
JavaScript Engine
JavaScript engine interprets, compiles, and executes JavaScript code. It also does memory management, JIT
compilation, type system, etc. Different browsers use different JavaScript engines, as listed in the below
table.
Browser JavaScript Engine
Edge Chromium with Blink and V8 engines
Chrome V8
FireFox Spider Monkey
Safari Nitro
Browser
Mostly, you will have a browser already installed on your PC, Microsoft Edge on the Windows platform, and
Safari on Mac OS.
You can also install the following browser as per your preference:
• jsfiddle.net
• jsbin.com
• playcode.io
Learn where to write JavaScript code in a web page in the next section.
In the above example, a <script></script> tag contains the JavaScript alert('Hello, how are you?') that display
a message box.
HTML v4 requires the type attribute 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.
HTML v5 page does not require the type attribute because the default script language is 'text/javascript' in
a <script> tag.
An HTML page can contain multiple <script> tags in the <head> or <body> tag. The browser executes all the
script tags, starting from the first script tag from the beginning.
Scripts without async, defer or type="module" attributes, as well as inline scripts, are fetched and executed
immediately, before the browser continues to parse the page. Consider the following page with multiple
script tags.
Above, the first <script> tag containing alert('Executing JavaScript 1') will be executed first, then
alert('Executing JavaScript 2') will be executed, and then alert('Executing JavaScript 3') will be executed.
The browser loads all the scripts included in the <head> tag before loading and rendering the <body> tag
elements. So, always include JavaScript files/code in the <head> that are going to be used while rendering
the UI. All other scripts should be placed before the ending </body> tag. This way, you can increase the page
loading speed.
Above, the <script src="/MyJavaScriptFile.js"> points to the external JavaScript file using the
src="/MyJavaScriptFile.js" attribute where the value of the src attribute is the path or url from which a file
needs to be loaded in the browser. Note that you can load the files from your domain as well as other
domains.
Global Attributes
The <script> can contain the following global attributes:
Attribute Usage
async <script async> executes the script asynchronously along with the rest of the page.
defer <script defer> executes the script after the document is parsed and before
firing DOMContentLoaded event.
src <script src="uri\path to resource"> specifies the URI/path of an external script file;
type <script type="text\javascript"> specifies the type of the containing script e.g.
text\javascript, text\html, text\plain, application\json, application\pdf, etc.
JavaScript Syntax
Learn some important characteristics of JavaScript syntax in this section.
As mentioned in the previous chapter, JavaScript code can be written inside HTML Script Tags or in a
separate file with .js extension.
Write JavaScript Code
<script>
//Write javascript code here...
</script>
Character Set
JavaScript uses the unicode character set, so allows almost all characters, punctuations, and symbols.
Case Sensitive
JavaScript is a case-sensitive scripting language. So, name of functions, variables and keywords are case
sensitive. For example, myfunction and MyFunction are different, Name is not equal to nAme, etc.
JavaScript Variables
Variable means anything that can vary. In JavaScript, a variable stores the data value that can be changed
later on.
Use the reserved keyword var to declare a variable in JavaScript.
Syntax:
var <variable-name>;
var <variable-name> = <value>;
A variable must have a unique name. The following declares a variable.
Example: Variable Declaration
varmsg; // declaring a variable without assigning a value
Above, the var msg; is a variable declaration. It does not have any value yet. The default value of variables
that do not have any value is undefined. You can assign a value to a variable using the = operator when you
declare it or after the declaration and before accessing it.
In the above example, the msg variable is declared first and then assigned a string value in the next
statement. The num variable is declared and initialized with a numeric value in the same statement. Finally,
the hundred variable is declared and initialized with another variable's value.
Javascript Operators
JavaScript includes operators same as other languages. An operator performs some operation on single or
multiple operands (data value) and produces a result. For example, in 1 + 2, the + sign is an operator and 1
is left side operand and 2 is right side operand. The + operator performs the addition of two numeric values
and returns a result.
Syntax:
<Left operand> operator <right operand>
<Left operand> operator
JavaScript includes following categories of operators.
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Assignment Operators
• Conditional Operators
• Ternary Operator
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between numeric operands.
Operator Description
+ Adds two numeric operands.
- Subtract right operand from left operand
* Multiply two numeric operands.
/ Divide left operand by right operand.
% Modulus operator. Returns remainder of two operands.
++ Increment operator. Increase operand value by one.
-- Decrement operator. Decrease value by one.
The following example demonstrates how arithmetic operators perform different tasks on operands.
Example: Arithmetic Operation
The ++ and -- operators are unary operators. It works with either left or right operand only. When used with
the left operand, e.g., x++, it will increase the value of x when the program control goes to the next
statement. In the same way, when it is used with the right operand, e.g., ++x, it will increase the value of x
there only. Therefore, x++ is called post-increment, and ++x is called pre-increment.
Example: Post and Pre Increment/Decrement
var x = 5;
x++; //post-increment, x will be 5 here and 6 in the next line
++x; //pre-increment, x will be 7 here
x--; //post-decrement, x will be 7 here and 6 in the next line
--x; //pre-decrement, x will be 5 here
String Concatenation
The + operator performs concatenation operation when one of the operands is of string type. The following
example demonstrates string concatenation even if one of the operands is a string.
Example: + Operator with String
Comparison Operators
JavaScript provides comparison operators that compare two operands and return a boolean value true or
false.
Operators Description
== Compares the equality of two operands without considering type.
Logical Operators
In JavaScript, the logical operators are used to combine two or more conditions. JavaScript provides the
following logical operators.
&& && is known as AND operator. It checks whether two operands are non-zero or not (0, false,
undefined, null or "" are considered as zero). It returns 1 if they are non-zero; otherwise, returns
0.
|| || is known as OR operator. It checks whether any one of the two operands is non-zero or not (0,
false, undefined, null or "" is considered as zero). It returns 1 if any one of of them is non-zero;
otherwise, returns 0.
! ! is known as NOT operator. It reverses the boolean result of the operand (or
condition). !false returns true, and !true returns false.
Ternary Operator
JavaScript provides a special operator called ternary operator:? that assigns a value to a variable based on
some condition. This is the short form of the if else condition. Syntax:
<condition> ?<value1> :<value2>;
The ternary operator starts with conditional expression followed by the? Operator. The second part (after ?
and before :) will be executed if the condition turns out to be true. Suppose, the condition returns false, then
the third part (after :) will be executed.
In the above example, different types of values are assigned to the same variable to demonstrate loosely
typed characteristics of JavaScript. Different values 1, 'one', 1.1, true are examples of different data types.
JavaScript includes primitive and non-primitive data types as per latest ECMAScript 5.1.
JavaScript Array
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
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];
Example: Array Literal
The following example shows how to define and initialize an array using array literal syntax.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Array</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
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];
document.getElementById("p1").innerHTML = stringArray;
document.getElementById("p2").innerHTML = numericArray;
document.getElementById("p3").innerHTML = decimalArray;
document.getElementById("p4").innerHTML = booleanArray;
document.getElementById("p5").innerHTML = mixedArray;
</script>
Array Constructor
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 blow syntax, an array can be initialized using new keyword, in the same way as an
object.
Example: Array Constructor
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Array Object</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script>
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");
document.getElementById("p1").innerHTML = stringArray;
document.getElementById("p2").innerHTML = numericArray;
document.getElementById("p3").innerHTML = mixedArray;
</script>
</body>
JavaScript Objects
JavaScript Objects
Here you will learn objects, object literals, Object() constructor function, and access object in JavaScript.
You learned about primitive and structured data types in JavaScript. An object is a non -primitive, structured
data type in JavaScript. Objects are same as variables in JavaScript, the only difference is that an object holds
multiple values in terms of properties and methods. In JavaScript, an object can be created in two ways:
1) Using Object Literal/Initializer Syntax
2) Using the Object() Constructor function with the new keyword. Objects created using any of these
methods are the same. The following example demonstrates creating objects using both ways.
Above, p1 and p2 are the names of objects. Objects can be declared same as variables using var or let
keywords. The p1 object is created using the object literal syntax (a short form of creating objects) with a
property named name. The p2 object is created by calling the Object() constructor function with the new
keyword. The p2.name = "Steve"; attach a property name to p2 object with a string value "Steve".
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Object</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var person = new Object();
// Attach properties and methods to person object
person.firstName = "Edu";
person["lastName"] = "Bridge";
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Object</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var person = {
firstName: "Edu",
lastName: "Bridge",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
document.getElementById("p1").innerHTML = person.firstName;
In the above example, the person.firstName access the firstName property of a person object. The person
["firstName"] is another way of accessing a property. An object's methods can be called using () operator
e.g. person.getFullName(). JavaScript engine will return the function definition if accessed method without
the parenthesis.
JavaScript Functions
JavaScript Functions
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.
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.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function</h1>
ShowMessage();
</script>
</body>
</html>
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 Parameter
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.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>
<script>
function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}
ShowMessage("Gaurav", "hajela");
ShowMessage("Ashwaini", "Yadav");
ShowMessage(100, 200);
</script>
</body>
</html>
Function Arguments Object
All the functions in JavaScript can use arguments object by default. An arguments object includes value of
each parameter.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript arguments object</h1>
<script>
function ShowMessage(firstName, lastName) {
alert("Hello " + arguments[0] + " " + arguments[1]);
}
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);
</script>
</body>
</html>
An arguments object is still valid even if function does not include any parameters.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript arguments object</h1>
<script>
function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);
}
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);
</script>
</body>
</html>
<script>
function multiple(x) {
function fn(y)
{
return x * y;
return fn;
}
document.getElementById("p1").innerHTML = triple(2);
document.getElementById("p2").innerHTML = triple(3);
</script>
</body>
</html>
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.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Function expression</h1>
<p id="p1"></p>
<p id="p2"></p>
<script>
var add = function sum(val1, val2) {
return val1 + val2;
};
document.getElementById("p1").innerHTML = add(10,20);
document.getElementById("p2").innerHTML = sum(10,20); // not valid
</script>
</body>
</html>
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
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
<!DOCTYPE html>
<html>
<body>
<h1>Demo: if condition</h1>
<script>
if( 1 > 0)
{
alert("1 is greater than 0");
if( 1 < 0)
{
alert("1 is less than 0");
}
</script>
</body>
</html>
In the above example, the first if statement contains 1 > 0 as conditional expression, The conditional
expression 1 > 0 will be evaluated to true, so an alert message "1 is greater than 0" will be displayed, whereas
conditional expression in second if statement will be evaluated to false, so "1 is less than 0" alert message
will not be displayed.
The same way, you can use variables in conditional expression.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: if condition</h1>
<script>
var mySal = 1000;
var yourSal = 500;
#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.
<!DOCTYPE html>
<html>
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..
}
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
}
<script>
var mySal = 500;
var yourSal = 1000;
</script>
</body>
</html>
JavaScript allows multiple else if statements also
<!DOCTYPE html>
<html>
<body>
<h1>Demo: if-else condition</h1>
<script>
var mySal = 500;
var yourSal = 1000;
</script>
</body>
</html>
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 { }.
JavaScript Switch
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
}
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.
<script>
switch (a) {
case 1:
alert('case 1 executed');
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");
}
</script>
</body>
</html>
In the above example, switch statement contains a literal value as expression. So, t he 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.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: switch statement</h1>
<script>
var a = 3;
switch (a/3) {
case 1:
alert("case 1 executed");
break;
</script>
</body>
</html>
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.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: switch with string type</h1>
<script>
var str = "bill";
switch (str)
{
case "steve":
alert("This is Steve");
case "bill":
alert("This is Bill");
break;
case "john":
alert("This is John");
<!DOCTYPE html>
<html>
<body>
<h1>Demo: combined switch cases</h1>
<script>
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");
}
</script>
</body>
</html>
Points to Remember:
The switch is a conditional statement like if statement.
1. A switch statement includes literal value or is expression based
JavaScript Loop
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.
The for loop can also be used to get the values for an array.
for (; ;) {
if (i >= 5)
break;
console.log(arr[i]);
i++;
}
Output:
10 11 12 13 14
Learn about while loop in the next section.
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.
Syntax:
while(condition expression)
{
/* code to be executed
till the specified condition is true */
}
Example: while loop
var i =0;
while(i < 5)
{
console.log(i);
i++;
}
Output:
01234
Make sure condition expression is appropriate and include increment or decrement counter
variables inside the while block to avoid infinite loop.
As you can see in the above example, while loop will execute the code block till i < 5 condition turns
out to be false. Initialization statement for a counter variable must be specified before starting while
loop and increment of counter must be inside while block.
do while
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;
alert(i);
i++;
} while(i < 5)
Output:
01234
The following example shows that do-while loop will execute a code block even if the condition turns out to
be false in the first iteration.
do{
alert(i);
i++;
} while(i > 1)
Output:
0
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.
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.
OOPs in JavaScript
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() {
this.firstName = "unknown";
this.lastName = "unknown";
}
alert(person1.getFullName());
alert(person2.getFullName());
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. person1.getFullName().
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.
Example: Constructor
function Person(FirstName, LastName, Age) {
this.firstName = FirstName || "unknown";
this.lastName = LastName || "unknown";
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.
Properties with Getters and Setters
As you learned in the previous section, Object.defineProperty() 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";
Object.defineProperties(this, {
"FirstName": {
get: function () {
return _firstName;
},
set: function (value) {
_firstName = value;
}
}
});
};
In the above example, the Person() function creates a FirstName property by using Object.defineProperties()
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.
Read-only Property
Do not specify set function in order to create read-only property as shown below.
Object.defineProperties(this, {
"FirstName": {
get: function () {
return _firstName;
}
}
});
};
var person1 = new Person("Steve");
//person1.FirstName = "Steve"; -- will not work
alert(person1.FirstName );
Object.defineProperties(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 }
}
});
this.getFullName = function () {
return this.FirstName + " " + this.LastName;
}
};
var person1 = new Person();
person1.FirstName = "John";
person1.LastName = "Bond";
alert(person1.getFullName());
Consider the following example of objects created using object literal and constructor function.
// Constructor function
function Student(){
this.name = "John";
this.gender = "Male";
this.sayHi = function(){
alert('Hi');
}
}
var student1 = new Student();
console.log(student1.name);
console.log(student1.gender);
student1.sayHi();
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.
Note:
Any javascript function using which object is created is called constructor function.
Use Object.keys() method to retrieve all the properties name for the specified object as a string array.
Object.keys(student1);
Output:
["title", "name", "gender", "sayHi"]
Use for-in loop to retrieve all the properties of an object as shown below.
Output:
title name gender sayHi
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
Object.getOwnPropertyDescriptor() method.
Syntax:
Object.getOwnPropertyDescriptor(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.
function Student(){
this.name = "John";
this.gender = "Male";
this.sayHi = function(){
alert('Hi');
}
}
console.log(Object.getOwnPropertyDescriptor(person,'firstName'));
console.log(Object.getOwnPropertyDescriptor(student1,'name'));
console.log(Object.getOwnPropertyDescriptor(student1,'sayHi'));
Output:
Object {value: "Steve", writable: true, enumerable: true, configurable: true}
Object {value: "John", writable: true, enumerable: true, configurable: true}
Object {value: function, writable: true, enumerable: true, configurable: true}
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
Object.keys() method.
Object.defineProperty()
The Object.defineProperty() method defines a new property on the specified object or modifies an existing
property or property descriptor.
Syntax:
Object.defineProperty(object, 'property name', descriptor)
The following example demonstrates modifying property descriptor.
function Student(){
this.name = "Steve";
this.gender = "Male";
Object.defineProperty(student1,'name', { writable:false} );
try
{
student1.name = "James";
console.log(student1.name);
}
catch(ex)
{
console.log(ex.message);
}
The above example, it modifies writable attribute of name property of student1 object using
Object.defineProperty(). 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 Object.defineProperty() method can also be used to modify configurable attribute of a property which
restrict changing any property descriptor attributes further.
function Student(){
this.name = "Steve";
this.gender = "Male";
}
var student1 = new Student();
try
{
Object.defineProperty(student1,'name',{writable:false}); // change writable attribute
}
catch(ex)
{
console.log(ex.message);
}
In the above example, Object.defineProperty(student1,'name',{configurable:false}); sets configurable
attribute to false which make student1 object non configurable after that.
Object.defineProperty(student1,'name',{writable:false}); sets writable to false which will throw an exceptio n
in strict mode because we already set configurable to false.
console.log(student1.title);
console.log(student1.name);
Output:
Mr.
John
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(this.myVar); // 100
}
• Global Scope
• Object's Method
• call() or apply() method
• bind() method
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.
function WhoIsThis() {
var myVar = 200;
'this' points to global window object even if it is used in an inner function. Consider the following example.
function SomeFunction() {
function WhoIsThis() {
var myVar = 200;
WhoIsThis();
}
SomeFunction();
So, if 'this' is used inside any global function and called without dot notation or using window. then this will
refer to global object which is default window object.
function WhoIsThis() {
this.myVar = 200;
}
var obj1 = new WhoIsThis();
alert(obj1.myVar); // 200
alert(obj2.myVar); // 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 p roperty of
both the instances and each will have a separate copy of myVar.
function WhoIsThis() {
this.myVar = 200;
this.display = function(){
var myVar = 300;
obj.display();
this behaves the same way when object created using object literal, as shown below.
var obj = {
myVar : 300,
whoIsThis: function(){
var myVar = 200;
alert(myVar); // 200
alert(this.myVar); // 300
}
};
obj.whoIsThis();
WhoIsThis();
WhoIsThis.call();
WhoIsThis.apply();
In the above example, WhoIsThis(), WhoIsThis.call() and WhoIsThis.apply() 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
function WhoIsThis() {
alert(this.myVar);
}
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 WhoIsThis.call(obj1). In the same way, this
will point to obj2 when a function got called like WhoIsThis.apply(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.
Example: bind()
var myVar = 100;
function SomeFunction(callback)
{
var myVar = 200;
callback();
};
var obj = {
myVar: 300,
WhoIsThis : function() {
alert("'this' points to " + this + ", myVar = " + this.myVar);
}
};
SomeFunction(obj.WhoIsThis);
SomeFunction(obj.WhoIsThis.bind(obj));
In the above example, when you pass obj.WhoIsThis as a parameter to the SomeFunction() then this points
to global window object insted of obj, because obj.WhoIsThis() 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(obj.WhoIsThis.bind(obj)) will set this to obj by specifying obj.WhoIsThis.bind(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.
• bind()
• call() and apply()
• Object method
• 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
Thus, use these simple rules in order to know which object the 'this' refers to inside any function.
function MyFunc() {
this.x = 100;
}
Second, it set's invisible 'prototype' property (or attribute) of this empty object to myFunc's pro totype
property. As you can see in the above example, we have assigned new property 'y' using MyFunc.prototype.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 thi s 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.
return 200;
}
return { a: 123 };
}
Inheritance in JavaScript
Inheritance is an important concept in object oriented programming. In the classical inher itance, 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.
Person.prototype.getFullName = function () {
return this.FirstName + " " + this.LastName;
}
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)
{
Person.call(this, firstName, lastName);
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) {
this.FirstName = firstName || "unknown";
this.LastName = lastName || "unknown";
}
Person.prototype.getFullName = function () {
return this.FirstName + " " + this.LastName;
}
function Student(firstName, lastName, schoolName, grade)
{
Person.call(this, firstName, lastName);
Read/Write - Here, we use setter methods to write the data and getter methods read that data.
Read Only - In this case, we use getter methods only.
Write Only - In this case, we use setter methods only.
Encapsulation Example
<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)
{
this.name=name;
}
getMarks()
{
return this.marks;
}
setMarks(marks)
{
this.marks=marks;
}
var stud=new Student();
stud.setName("John");
stud.setMarks(80);
document.writeln(stud.getName()+" "+stud.getMarks());
</script>
Activity
1. Design signup form to validate username, password, and phone numbers etc using Java script.
2. Write a JavaScript program to determine whether a given year is a leap year in the Gregorian calendar.
3. Write a JavaScript program to convert temperatures to and from celsius, Fahrenheit.
4. Write a JavaScript to design a simple calculator to perform the following operations: sum, product,
difference and quotient
5. Write a JavaScript that calculates the squares and cubes of the numbers from 0 to 10 and outputs HTML
text that displays the resulting values in an HTML table format.