Web Development

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 87

Web Development Training

Mr. Amit Goel


Assistant Professor
Department of Computer Applications
Front End Development
Module 3 - JavaScript
Agenda

 Introduction
 JavaScript Engine
 Alerts and Prompts
 Data Types
 Variables
 Strings

3
JavaScript

JavaScript was initially created to “make web pages alive”.

The programs in this language are called scripts. They can be written right in a
web page’s HTML and run automatically as the page loads.

Scripts are provided and executed as plain text. They don’t need special
preparation or compilation to run.

In this aspect, JavaScript is very different from another language called Java.

4
JavaScript
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled
programming language with first-class functions.

While it is most well-known as the scripting language for Web pages,


many non-browser environments also use it, such as Node.js, Apache
CouchDB and Adobe Acrobat.

JavaScript is a prototype-based, multi-paradigm, single-threaded,


dynamic language, supporting object-oriented, imperative, and
declarative (e.g. functional programming) styles.
- MDN WebDocs
JavaScript
 You don't have to download or install JavaScript to work on front-end
development using JavaScript.

 JavaScript comes bundled with your browser and is already running in


the browser on your computer, on your tablet, and on your smart-
phone.

 JavaScript can be enabled or disabled in the browser but most web


pages will either stop working or will not look any good.

 JavaScript is free to use for everyone.


Data Types
Data Types

JavaScript is a loosely typed and dynamic language. Variables in JavaScript


are not directly associated with any particular value type, and any variable
can be assigned (and re-assigned) values of all types.

let myVar = 5; // myVar is now a number

myVar = ‘Hello'; // myVar is now a string

myVar = true; // myVar is now a boolean


JavaScript types
The set of types in the JavaScript language consists of primitive values and
objects.

 Primitive values (immutable datum represented directly at the lowest level


of the language)
 Boolean type
 Null type
 Undefined type
 Number type
 BigInt type
 String type
 Symbol type

 Objects (collections of properties)


“boolean” and “null”
Type
boolean type
boolean represents a logical entity and can have two values: true and false.

null type
The null type has exactly one value: null. See null and Null for more details.

// myVar is known to exist now but it has no type or value:

var myVar = null;

myVar; //null
“undefined” Type
A variable that has not been assigned a value has the value undefined.

The meaning of undefined is “value is not assigned”.


If a variable is declared, but not assigned, then its value is undefined:
let age;
alert(age); // shows "undefined“

Technically, it is possible to explicitly assign undefined to a variable:

let age = 100;

// change the value to undefined


age = undefined;
alert(age); // "undefined"
Number Type

ECMAScript has two built-in numeric types: Number and BigInt.

The Number type is a double-precision 64-bit binary format IEEE 754 value
(numbers between -(2^53 − 1) and 2^53 − 1).

In addition to representing floating-point numbers, the number type has


three symbolic values: +Infinity, -Infinity, and NaN ("Not a Number").
Number Type
To check for the largest available value or smallest available value within ±Infinity,
you can use the constants Number.MAX_VALUE or Number.MIN_VALUE.

The number type has only one integer with two representations: 0 is represented
as both -0 and +0. (0 is an alias for +0.)

In practice, this has almost no impact. For example, +0 === -0 is true. However, you
are able to notice this when you divide by zero:

> 42 / +0 Infinity

> 42 / -0 -Infinity
BigInt Type

The BigInt type is a numeric primitive in JavaScript that can represent integers
with arbitrary precision. With BigInts, you can safely store and operate on large
integers even beyond the safe integer limit for Numbers.

A BigInt is created by appending n to the end of an integer or by calling the


constructor.
BigInt Type
You can obtain the largest safe value that can be incremented with Numbers by
using the constant Number.MAX_SAFE_INTEGER. With the introduction of BigInts,
you can operate with numbers beyond the Number.MAX_SAFE_INTEGER.

This example demonstrates, where incrementing the number.MAX_SAFE_INTEGER


returns the expected result:

 const x = 2n ** 53n;
9007199254740992n

 const y = x + 1n;
9007199254740993n
String Type
JavaScript's String type is used to represent textual data. Each element in the String occupies a
position in the String. The first element is at index 0, the next at index 1, and so on. The length of
a String is the number of elements in it.

Unlike some programming languages (such as C), JavaScript strings are immutable. This means
that once a string is created, it is not possible to modify it.

However, it is still possible to create another string based on an operation on the original string.
For example:

A substring of the original by picking individual letters or using String.substr().

A concatenation of two strings using the concatenation operator (+) or String.concat().


Symbol Type
Symbol is a built-in object whose constructor returns a symbol primitive —
also called a Symbol value or just a Symbol — that's guaranteed to be unique.

A Symbol is a unique and immutable primitive value and may be used as the
key of an Object property. In some programming languages, Symbols are
called "atoms".

The above code creates three new Symbols. Note that Symbol("foo")
does not coerce the string "foo" into a Symbol. It creates a new
Symbol each time.
Symbol Type

Every Symbol.for("key") call will always return the same Symbol


for a given value of "key".

When Symbol.for("key") is called, if a Symbol with the given key


can be found in the global Symbol registry, that Symbol is
returned.

Otherwise, a new Symbol is created, added to the global Symbol


registry under the given key, and returned.
Variables
Variables
There are 4 Ways to declare a JavaScript
variable:

 using var
 using let
 using const
 using nothing

A variable is a container for a value, like a number we might use in a


sum, or a string that we might use as part of a sentence.
Scope of var
Scope essentially means where these variables are available for use. var declarations
are globally scoped or function/locally scoped.

The scope is global when a var variable is declared outside a function. This means that
any variable that is declared with var outside a function block is available for use in the
whole window.

var is function scoped when it is declared within a function. This means that it is
available and can be accessed only within that function.
Example - Global Example - Local
var Declarations
var variables can be re-declared and updated.

This means that we can do this within the same scope and won't get
an error.

And we can also do this:


Hoisting of var
Hoisting is a JavaScript mechanism where variables and function
declarations are moved to the top of their scope before code execution.

This means that if we do this:

It is interpreted as this:
Problem with var
There's a weakness that comes with var. I'll use the example below to
explain:

So, since times > 3 returns true, greeter is redefined to "say Hello
instead". While this is not a problem if you knowingly want greeter to
be redefined, it becomes a problem when you do not realize that a
variable greeter has already been defined before.
Scope of let
let is now preferred for variable declaration. let is block scoped.

A block is a chunk of code bounded by { }. A block lives in curly braces.


Anything within curly braces is a block.

So a variable declared in a block with let is only available for use


within that block. Let us understand this with an example:
let Declaration
let can be updated but not re-declared.

Just like var, a variable declared with let can be updated within its scope.
Unlike var, a let variable cannot be re-declared within its scope. So while
this will work:

this will return an error:


Hoisting of let
However, if the same variable is defined in different scopes, there will be no
error:

Hoisting of let
Just like var, let declarations are hoisted to the top.

Unlike var which is initialized as undefined, the let keyword is not


initialized. So if you try to use a let variable before declaration,
you'll get a Reference Error.
Scope of const

Variables declared with the const maintain constant values. const


declarations share some similarities with let declarations.

const declarations are block scoped


Like let declarations, const declarations can only be accessed within the
block they were declared.
Scope of const
const cannot be updated or re-declared.

This means that the value of a variable declared with const remains the same
within its scope. It cannot be updated or re-declared. So if we declare a
variable with const, we can neither do this:
Scope of Const
Hoisting of const
Just like let, const declarations are hoisted to the top but are not
initialized.
So just in case you missed the differences, here they are:

 var declarations are globally scoped or function scoped while let and
const are block scoped.

 var variables can be updated and re-declared within its scope; let
variables can be updated but not re-declared; const variables can
neither be updated nor re-declared.

 They are all hoisted to the top of their scope. But while var variables
are initialized with undefined, let and const variables are not
initialized.

 While var and let can be declared without being initialized, const must
be initialized during declaration.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names


(age, sum, totalVolume).

The general rules for constructing names for variables (unique


identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this
tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names
String
and
String Manipulation
String Methods
The length property returns the length of a string:
let msg = “HelloWorld!";
let length = msg.length;
console.log(length);

Extracting Parts of a String

There are 3 methods for extracting a part of a string:

 slice (start, end)

 substring (start, end)

 substr (start, length)


Exercise

1. Accept a number from the user.


2. Write a program in javascript to reverse the number.

let num = 123456;

Expected Outcome:

654321
Numbers
Math Object

Math.property (Constants)

JavaScript provides 8 mathematical constants that can be accessed as Math


Object properties:

Math.E // returns Euler's number


Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of ½
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Library

Math Methods - Math.method (number)

JavaScript provides several methods on Math object that can be used to


work with numbers:

Math.round (x) Returns x rounded to its nearest integer

Math.ceil (x) Returns x rounded up to its nearest integer

Math.floor (x) Returns x rounded down to its nearest integer

Math.trunc (x) Returns the integer part of x (new in ES6)


Randomization

Randomization – Math.random()

Math.random() returns a random number between 0 (inclusive), and 1


(exclusive).

Math.random();
Exercise
Exercise

Create a Dice Game, where two players roll the dice at the same time and
whoever gets the higher score in dice roll is declared winner.

Hints:

1. Use the Math.random and restrict the value between 1 and 6 (both
included).
2. Use comparator operator
Operators
Operators
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Operators
Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Operators
Comparator Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Operators

Logical Operators
Operator Description
&& logical and
|| logical or
! logical not
Collection - Arrays
Arrays
An array is a special variable, which can hold more than one value:
const fruits= [“apple", “banana", “guava"];

First Way – Creating an array using array literal

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:
const array_name = [item1, item2, ...];

Second Way – Creating an array using Keyword new

The following example also creates an Array, and assigns values to it:

Example
const fruits= new Array(“apple", “banana", “guava");
Loops
Loops can execute a block of code a number of times.
JavaScript supports different kinds of loops:

for - loops through a block of code a number of times

for/in - loops through the properties of an object

for/of - loops through the values of an iterable object

while - loops through a block of code while a specified


condition is true

do/while - also loops through a block of code while a


specified condition is true
Conditionals
Conditional statements are used to perform different actions
based on different conditions.
Conditional Statements
In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified


condition is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition
is false
 Use switch to specify many alternative blocks of code to be
executed
Switch Statement
Switch Statement This is how it works:

switch(expression) {  The switch expression is evaluated once


case x:
// code block  The value of the expression is compared with the
break; values of each case
case y:
// code block  If there is a match, the associated block of code is
break; executed
default:
// code block  If there is no match, the default code block is
} executed

** Strict Comparison
Switch cases use strict comparison (===).
The values must be of the same type to match.
Objects
Objects
There are multiple ways in which objects can be created in Javascript.

Method 1

Object Constructor

The simplest way to create an empty object is using the Object constructor.
Currently this approach is not recommended.

var object = new Object();


JavaScript Objects Boolean and Null Type
Method 2

Object's create method:


The create method of Object creates a new object by passing the prototype object
as a parameter

var object = Object.create(null);


JavaScript Objects Boolean and Null Type
Method 3

Object literal syntax:

The object literal syntax (or object initializer), is a comma-separated set of name-
value pairs wrapped in curly braces.

var object = {
name: "Sudheer“,
age: 34
};

Object literal property values can be of any data type, including


array, function, and nested object.
JavaScript Objects Boolean and Null Type
Method 4

Function constructor:

Create any function and apply the new operator to create object instances,

function Person(name) {
this.name=name;
this.age=21;
}
var object = new Person("Sudheer");
function Person(){} Person.prototype.name = "Sudheer"; var object = new Person();

JavaScript Objects Boolean and Null Type


Method 5

Function constructor with prototype:

This is similar to function constructor but it uses prototype for their properties and
methods,

function Person() { }
Person.prototype.name = "Sudheer";
var object = new Person();
function Person(){} Person.prototype.name = "Sudheer"; var object = new Person();

JavaScript Objects Boolean and Null Type


Method 6

ES6 Class syntax:

ES6 introduces class feature to create the objects

class Person {
constructor(name) {
this.name = name;
}
}

var object = new Person("Sudheer");


JavaScript Objects Boolean and Null Type
Method 7

Singleton pattern:

A Singleton is an object which can only be instantiated one time. Repeated calls to
its constructor return the same instance and this way one can ensure that they
don't accidentally create multiple instances.

var object = new function(){


this.name = "Sudheer";
}
JavaScript Exercise Boolean and Null Type
Music Player App

Create the logic for your own Juke Box - Music Player App.

1. The app can have n number of songs (e.g. 10 songs).


2. It will randomly select and play any song from the list.

Expected Outcome

Print on console – “Now playing song - <song name>


Functions and Invocation Patterns
Boolean and Null Type
JavaScript Functions
JavaScript has been described as a Functional Oriented Language (this as opposed to Object Oriented
Language). The reason is because functions in JavaScript do more than just separate logic into execution units,
functions are first class citizens that also provide scope and the ability to create objects.

Declaring a Function
The syntax to declare a function is:

• A function is declared using the function keyword.

• The basic rules of naming a function are similar to naming a variable. It is


better to write a descriptive name for your function. For example, if a function is used
to add two numbers, you could name the function add or addNumbers.

• The body of function is written within {}.


Boolean and Null Type
JavaScript Functions
JavaScript has been described as a Functional Oriented Language (this as opposed to Object Oriented
Language). The reason is because functions in JavaScript do more than just separate logic into execution units,
functions are first class citizens that also provide scope and the ability to create objects.

Different invocation patterns can produce vastly different results. Let us understand the four patterns, how to
use them and what to watch out for. The four invocation patterns are:

1. Method Invocation

2. Function Invocation

3. Constructor Invocation

4. Apply And Call Invocation

Function Execution
JavaScript (like all languages these days) has the ability to modularize logic in functions which
can be invoked at any point within the execution.

The invocation operator is a pair of round brackets (), that can contain zero or more
expressions separated by a comma.
Boolean and Null Type
JavaScript Functions

The Four Invocation Patterns

Even though there is only one invocation operator (), there are four invocation patterns. Each pattern
differs in how the this parameter is initialized.

Method Invocation

When a function is part of an object, it is called a method. Method invocation is the pattern of invoking a
function that is part of an object.
Syntax

var obj = {
value : 0 ,
increment : function() {
this.value+=1;
}
};

obj.increment(); //Method invocation


JavaScript Functions Boolean and Null Type
Method Invocation

Example var myObject = {


firstName : “John",
middleName : "",
lastName : “Doe",
fullName : function () {
return this.firstName + this.middleName
+ this.lastName;
}
}

myObject.fullName();
JavaScript Functions Boolean and Null Type
Function Invocation

When a function is not the property of an object, then it is invoked as a function.

The code inside a function is not executed when the function is defined.
The code inside a function is executed when the function is invoked.

“In JavaScript function can be invoked without being called.” – W3School

Example function myFunction (a, b) {


return a + b;
}

myFunction(50, 60);
JavaScript Functions Boolean and Null Type
Constructor Invocation

If a function invocation is preceded with the new keyword, it is a constructor invocation.

It looks like you create a new function, but since JavaScript functions are objects you actually create a
new object.

A constructor invocation creates a new object. The new object inherits the properties and methods from its
constructor.
Example // This is a function constructor:
function myFunction(arg1, arg2) {

this.firstName = arg1;
this.lastName = arg2;

// This creates a new object – Constructor Invocation


const myObj = new myFunction("John", "Doe");
JavaScript Functions Boolean and Null Type
Invocation using Call()

The call() method is a predefined JavaScript method.


It can be used to invoke (call) a method with an owner object as an argument (parameter).
With call(), an object can use a method belonging to another object.

Example const person = {


fullName: function() {
return this.firstName + " " + this.lastName;
}
}

const person1 = {
firstName:"John",
lastName: "Doe"
}

const person2 = {
firstName:"Mary",
lastName: "Doe"
}

// This will return "John Doe":


person.fullName.call(person1);
JavaScript Functions Boolean and Null Type
Invocation using Apply()

The apply() method is similar to the call() method. With the apply() method, you can write a method that
can be used on different objects.

Example const person = {


fullName: function() {
return this.firstName + " " + this.lastName;
}
}

const person1 = {
firstName: "Mary",
lastName: "Doe"
}

// This will return "Mary Doe":


person.fullName.apply(person1);
JavaScript Functions Boolean and Null Type
The Difference Between call() and apply()

The call() method takes arguments separately.


The apply() method takes arguments as an array.

Example: call() Example: apply()


const person = { const person = {
fullName: function(city, country) { fullName: function(city, country) {
return this.firstName + " " + return this.firstName + " " +
this.lastName + "," + city + "," + country; this.lastName + "," + city + "," + country;
} }
} }

const person1 = { const person1 = {


firstName:"John", firstName:"John",
lastName: "Doe" lastName: "Doe"
} }

person.fullName.call(person1, "Oslo", "Norway"); person.fullName.apply(person1, ["Oslo", "Norway"]);


JavaScript Functions Boolean and Null Type
bind()

Function Borrowing

With the bind() method, an object can borrow a method from another object.

Example const person = {


firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}

const member = {
firstName:"Hege",
lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);


JavaScript Functions Boolean and Null Type
Anonymous Functions

Anonymous Function is a function that does not have any name associated with it.

Normally we use the function keyword before the function name to define a function in JavaScript,
however, in anonymous functions in JavaScript, we use only the function keyword without the function
name.

An anonymous function is not accessible after its initial creation, it can only be accessed by a
variable it is stored in as a function as a value. An anonymous function can also have multiple
arguments, but only one expression.

Syntax

function() {
// Function Body
}
JavaScript Functions Boolean and Null Type
Anonymous Functions

Example:

In this example, we define an anonymous function that prints a message to the


console. The function is then stored in the greet variable. We can call the function by
invoking greet().

var greet = function () {

console.log("Welcome to GeeksforGeeks!");

};

greet();
JavaScript Closures Boolean and Null Type
What is a closure?

A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s
variables — a scope chain.

The closure has three scope chains:

 it has access to its own scope — variables defined between its curly brackets

 it has access to the outer function’s variables

 it has access to the global variables

In order to understand it better, please refer to the link below (one of best explanation):

https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4
JavaScript “this” Boolean and Null Type
What is “this”

In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:


Document Object Model
(DOM)
DOM Boolean and Null Type
The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document.

 When a web page is loaded, the browser creates a Document Object Model
of the page.

 The HTML DOM model is constructed as a tree of Objects.


HTML DOM Tree Boolean and Null Type
DOM Boolean and Null Type
The HTML DOM is a standard object model and programming interface for
HTML. It defines:

 The HTML elements as objects

 The properties of all HTML elements

 The methods to access all HTML elements

 The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
DOM Boolean and Null Type
With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
 JavaScript can change all the HTML elements in the page

 JavaScript can change all the HTML attributes in the page

 JavaScript can change all the CSS styles in the page

 JavaScript can remove existing HTML elements and attributes

 JavaScript can add new HTML elements and attributes

 JavaScript can react to all existing HTML events in the page

 JavaScript can create new HTML events in the page


Boolean and Null Type
Document Tree: Node

– There are many types of nodes in the DOM document tree,


representing elements, text, comments, the document type
declaration, etc.

– Every Object in the DOM document tree has properties and methods
defined by the Node host object
Boolean and Null Type
Document Tree: Node
Boolean and Null Type
Document Tree: Node

Some possible values of the nodeType property of Node instances


Boolean and Null Type
Document Tree: Node
Boolean and Null Type
DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming languages).

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

A property is a value that you can get or set (like changing the content of an HTML element).

A method is an action you can do (like add or deleting an HTML element).


DOM Document Object Boolean and Null Type
Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do this:

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections
Event Handling Boolean and Null Type

– An event is an occurrence of something potentially interesting to a


script:
– Ex: mouseover and mouseout events

– An HTML event attribute is used to specify a script to be called when an


event occurs
– Ex: onmouseover
– Name of attribute is on followed by event name
Event Handling Boolean and Null Type
Event Handling Boolean and Null Type

You might also like