• JavaScript isa light-weight object-oriented programming language which is
used by several websites for scripting the webpages. It is an interpreted,
full-fledged programming language that enables dynamic interactivity on
websites when applied to an HTML document.
• Why JavaScript was introduced?
• To create interactive websites
• Example: Pop ups, event on click
• Many websites are using JavaScript
2
Introduction
3.
• For effectiveand efficient web development, developers must know three
languages:
• HTML – for creating the web page and defining its content
• CSS – for specifying the layout and styles of the various elements
• Javascript – for programming the behaviour of the web page
• JS is an easy to learn, lightweight, interpreted scripting language.
• It was created by a Netscape developer named Brendan Eich in 1995.
• It can run both on client side as well as server side web browsers.
3
Overview
4.
• Website Clientside (Js, Jquery, React js)
• Website Server side (Node JS, Express js)
• Mobile Development (React Native, Phone Gap, ionic)
• Software Development (electronjs EX-VScode)
4
Where is JavaScript used ?
5.
• ECMA Internationalis an organization that creates standards for technologies
• The organization created/published a standard ECMA-262
• ECMA-262 : This is a standard published by ECMA international. It contains the
specification for a general purpose scripting language.
5
What is ECMAScript and ES6,ES7…?
?
6.
• The specificationdefined in ECMA-262 for creating a general purpose scripting
language
• ECMAScript provides the rules, details, and guidelines that a scripting language
must observe to be considered ECMAScript compliant
6
What is ECMAScript?
What is JavaScript?
• A general purpose scripting language that conforms to the ECMAScript
specification
• By reading the ECMAScript specification, we learn how to create a scripting
language
• By reading the JavaScript documentation, we learn how to use a scripting
language.
7.
ECMA Script versions
7
•ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and
ES6.
• ES6 or ECMAScript (2015) major change
• Since 2016, versions are named by year (ECMAScript 2016, 2017, 2018,
2019, 2020 (11th
edition).
8.
8
1
What is
JavaScript?
2
What can
JSdo?
• One of the most popular
and widely used
scripting language.
• Capable of Front-end,
Back-end, Full Stack
development
• Build Web/ Mobile
applications, Real-time
networking apps like
chats, video streaming
services, Games, etc.
3
Where does
JS code run?
• JS engine present in a
browser (SpiderMonkey, V8)
or outside a browser (Node)
presents the run-time
environment for JS code
4
JavaScript vs
ECMAScript?
• ECMAScript - specification that
provides the rules, details, and
guidelines that a scripting language
must observe to be considered
ECMAScript compliant.
• JavaScript – programming
language that conforms to
ECMAScript
Four Important Questions
• JavaScript codeis inserted between <script> and
</script> tags.
• Any number of scripts can be placed in a web
page.
• Three ways of placing and using a script:
Inside <head> section
Inside <body> section
External JS file
10
JavaScript
Inclusion
• JS can"display" o/p in different ways, by using
innerHTML - writes into an HTML element
document.write() - writes into the HTML output
window.alert() / alert() – writes into a pop up alert box
console.log() – writes into the browser console
16
JavaScript
Output
17.
Example : Asyncv/s Defer
17
Async in script tag in JavaScript is a way to load scripts asynchronously. That means, if a script is async, it will be loaded independently
of other scripts on the page, and will not block the page from loading.
If you have a page with several external scripts, loading them all asynchronously can speed up the page load time, because the browser
can download and execute them in parallel.
To use async, simply add the async attribute to your script tag:
<script async src="script.js"></script>
What is defer in script tag in JavaScript?
By using the defer attribute in HTML, the browser will load the script only after parsing (loading) the page. This can be helpful if you
have a script that is dependent on other scripts, or if you want to improve the loading time of your page by loading scripts after the
initial page load.
To use defer, simply add the defer attribute to your script tag:
<script defer src="script.js"></script>
The async and defer attributes both allow the browser to continue parsing the HTML document while JavaScript files are being
downloaded, but they differ in when those files are executed.
Async downloads and executes JavaScript as soon as it’s available, while defer attribute waits until the HTML document has been
parsed before downloading and executing any external scripts.
18.
Example: Async
18
Why errorappears: We are trying to change the inner HTML
JavaScript loads line by line.
Browser has not loaded the h1 tag, thus we cannot select the things that does not exist
as the browser has not rendered the code for h1 tag hence, element was not found
Example document.write()
21
Nowadays, GoogleChrome is no longer running the script named document.write.
2016 Chrome updates have led it to decide that this type of file should not be
available on websites as it increases the page load time.
• Variables areidentified using unique names called identifiers.
• General rules for naming variables are:
• Can contain letters, digits, underscores, and dollar signs
• Must begin with a letter, $ and _
• Are case sensitive (x and X are different variables)
• Keywords cannot be used as names
• Must not contain any white-space, or special character (!, @, #, %, ^, &, *)
• Variable Declaration – var | in ES6 (var was removed) let | const was
introduced
• Variable Scope – global, local, block
26
JavaScript Variables
27.
var firstNumber;
firstNumber =10;
const x = 10;
let fname, age;
fname = "Anu";
age = 12;
let fname = "Anu", age = 12, city = "Noida";
27
Declaring a variable
Assigning value to declared variable
Declaring + Assigning value
Declaring and assigning values to
multiple variables in one statement
Declaring multiple variables in one statement
and then assigning values to them
Declaring & Defining Variables
28.
JavaScript var keyword
28
Thevar is the oldest keyword to declare a variable in JavaScript.
Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope.
It means variables defined outside the function can be accessed globally, and variables defined inside a
particular function can be accessed within the function.
Example 1: Variable ‘a’ is declared globally. So,
the scope of the variable ‘a’ is global, and it can be
accessible everywhere in the program. The output
shown is in the console.
Example 2: The variable ‘a’ is declared inside the function. If the user
tries to access it outside the function, it will display the error. Users
can declare the 2 variables with the same name using the var
keyword. Also, the user can reassign the value into the var variable.
29.
JavaScript var keyword
29
Example3: The user can re-declare
the variable using var and the user
can update var variable.
Example 4: If users use the var variable before the
declaration, it initializes with the undefined value.
The output is shown in the console.
30.
JavaScript: let keyword
30
Thelet keyword is an improved version of the var keyword.
Scope: block scoped: The scope of a let variable is only block scoped. It can’t be accessible
outside the particular block ({block}). Example 2: The code returns an error because we
are accessing the let variable outside the function
block.
Example 1:
31.
JavaScript: let keyword
31
Example3: Users cannot re-declare
the variable defined with the let
keyword but can update it.
Example 4: Users can declare the variable with the
same name in different blocks using the let keyword.
32.
JavaScript: let keyword
32
Example5: If users use the let variable before the
declaration, it does not initialize with undefined just
like a var variable, and returns an error.
33.
JavaScript: const keyword
33
Theconst keyword has all the properties that are the same as the let keyword, except the user
cannot update it.
Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it
returns an error. The user cannot update the const variable once it is declared.
Example 1: We are changing the value of
the const variable so that it returns an error.
The output is shown in the console
34.
Var, const andlet
34
Let and const do not become properties of window object
35.
Var, const andlet
35
Let and const do not become properties of window object, but var gets attached.
Open developer tools -> Console-> type window (press enter)
• String
• Number
•Boolean
• Undefined
• Null
46
Primitive/ Value Data Types
• Object
• Array
Non-Primitive/ Reference Data Types
JavaScript
Data Types
48
Difference between Undefinedand Null
Undefined: It means a variable has been declared but not yet has been assigned a value.
Null: It is an assignment value. It can be assigned to a variable as representation of no value.
Function is areusable block of code, which on invocation performs a particular task.
53
function name(parameter1, parameter2, parameter3)
{
// statements or code to be executed
}
• Syntax – function keyword, followed by a name, followed by parentheses
• Parameters - multiple comma separated parameters, can be passed to a function
• Definition – function has to be defined before use
• Invocation – function executes only when invoked
JavaScript Functions
57
Arrow Function
• Ifthere is only one parameter being passed, then parentheses around parameters can be omitted in
arrow function.
• If there are no parameters, then empty parentheses have to be placed (parentheses cannot be omitted
in this case).
58.
58
Anonymous Function
It isa 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.
59.
Need for AnonymousFunction
59
Suppose we want to add a timer in show function
JavaScript saves the name of the function in
RAM and the starting point (line no.)
Storing the name is effective when we want to run the function
multiple times. Thus, anonymous function can be used (i) when we
have to execute the program only one time. (ii) when function is
passed is parameter to another function for one time
JS Objects
61
Objects areVariables
JavaScript variables can contain single values:
let person = "John Doe";
Object values are written as name :
value pairs (name and value separated by
a colon).
A JavaScript object is a collection
of named values
62.
Object Methods
62
Methods areactions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
JavaScript objects are containers for named values, called properties and methods.
The this keyword refers to the current object in a method or constructor.
In this example, this refers to the person object
63.
Creating a JavaScriptObject
63
There are different ways to create new objects:
•Create a single object, using an object literal.
•Create a single object, with the keyword new.
•Factory function
•Constructor function
64.
Using an ObjectLiteral
64
•This is the easiest way to create a JavaScript Object.
•Using an object literal, you both define and create an object in one statement.
•An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
65.
Using the JavaScriptKeyword new
65
The following example creates a new JavaScript object using new Object(), and then adds 4 properties:
New keyword in JavaScript is used to create an instance of an object that has a constructor function. It
Creates a blank, plain JavaScript object
66.
JavaScript Objects areMutable
66
Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of person:
let x = person; // Will not create a copy of person.
The object x is not a copy of person. It is person. Both x and person are the same object.
Any changes to x will also change person, because x and person are the same object.
67.
• JS objectis an entity having state (properties) and behavior (method)
• Ways to create objects:
67
Object literal
Factory function
Object instance
Constructor function
JavaScript Objects
68.
• JS objectis an entity having state (properties) and behavior (method)
• Ways to create objects:
68
Object literal
Factory function
Object instance
Constructor function
JavaScript Objects
69.
Factory function
69
A factoryfunction is a function that returns a new
object. The following creates a person object
named person1:
let person1 = {
firstName: 'John',
lastName: 'Doe',
getFullName() {
return this.firstName + ' ' + this.lastName;
},
};
console.log(person1.getFullName());
Output: John Doe
The person1 object has two properties: firstName and
lastName, and one method getFullName() that returns
the full name.
Suppose that you need to create another similar object
called person2, you can duplicate the code as follows:
let person2 = {
firstName: 'Jane',
lastName: 'Doe',
getFullName() {
return this.firstName + ' ' + this.lastName;
},
};
console.log(person2.getFullName());
Output: Jane Doe
In this example, the person1 and person2 objects have
the same properties and methods.
The problem is that the more objects you want to create,
the more duplicate code you have.
70.
Example of factoryfunction
70
function createPerson(firstName, lastName) {
return {
firstName: firstName,
lastName: lastName,
getFullName() {
return firstName + ' ' + lastName;
},
};
}
When a function creates and returns a new object, it is called a factory function.
The createPerson() is a factory function because it returns a new person object.
let emp1=createPerson(“John”, “Doe”);
Console.log(Emp1.getFullName());
71.
• JS objectis an entity having state (properties) and behavior (method)
• Ways to create objects:
71
Object literal
Factory function
Object instance
Constructor function
JavaScript Objects
72.
• A classis an extensible program-code-template for creating objects, providing initial
values for state (member variables) and implementations of behavior (member
functions or methods). 1
• Useful for creating many objects of the same kind.
72
1 https://en.wikipedia.org/wiki/Class_(computer_programming)
class ClassName {
constructor() { ... } // automatically called by new; initializes the object;
constructor is a keyword;
method1() { ... }
method2() { ... }
method3() { ... }
...
}
JavaScript Classes
• JS objectis an entity having state (properties) and behavior (method)
• Ways to create objects:
74
Object literal
Factory function
Object instance
Constructor function
JavaScript Objects
75.
Object destructuring providesan alternative way to assign properties of an object to
variables.
75
Object Destructuring
76.
• A newaddition to the set of operators in JavaScript ES6
• It takes an iterable (like an array) and expands it into
individual values
• Denoted by three dots (…)
• Some uses of spread operator:
Copy an array
Concatenating arrays
Passing array as argument
Combining objects
76
Spread
Operator
79
Event driven programming
Event-DrivenProgramming makes use of the following concepts:
• an event loop (event listener) - it keeps listening for event triggers and when an event occurs,
the event loop determines the event callback (event handler) and invokes it
• an event handler - gets called when an event is triggered, and performs the said action
Image Courtesy: https://www.researchgate.net/figure/Architecture-of-Event-driven-Programming-Model_fig1_323279886
80.
• In event-drivenparadigm there are two actors –
the subject (event emitter) and the observer (event listener)
• On detecting an event, the event listener triggers a callback function (event handler), which
performs the corresponding action
Eg. - Clicking ( event )
a “print” button ( event listener )
activates the actual print process ( event handler)
• In this paradigm, flow of execution is dictated by events
The program loads and then waits for user input events
As each event occurs, the program runs a particular code in response
The overall flow of what code is executed is determined by the series of events that occur
80
Event driven programming
81.
• JS enginerunning in the browser provides an event-driven platform for JS
• JS in the browser interacts with event emitters (HTML elements capable of emitting events)
• JS functions act as event listeners and handle/ react to events emitted by the elements
81
How event-driven approach applies to JS in the browser?
Image Courtesy: https://courses.cs.washington.edu/courses/cse331/13sp/lectures/lect24-events.pdf
82.
What is anEvent ?
something the browser or user does, like clicking
a button, loading of page, change in input field
value, occurrence of an error
82
Types of events
i. User Interface events (load, unload, error, resize, scroll)
ii. Focus & Blur events (focus, blur, focusin, focusout)
iii. Mouse events (click, mouse-down, mouseup, mouseout, mouseover)
iv. Keyboard events (input, keydown, keypress, keyup)
v. Form events (submit, input, change)
vi. Mutation events
vii. HTML5 events
viii. CSS events
JavaScript
Events
83.
Callback functions allowthe scheduling of asynchronous actions, i.e.,
actions that we initiate now, but they finish later
83
Callback
Function
In technical parlance
In JavaScript, functions can take functions as arguments, and can
be returned by other functions. Any function that is passed as an
argument and subsequently called by the function that receives it, is
called a callback function.
In simple words
A callback is a function that is to be executed after another
function has finished executing - hence the name ‘call back’.
A callback is a function passed as an argument to another function
Text Courtesy: https://www.sitepoint.com/callbacks-javascript/