Javascript - MEAN Stack Unit-2 N
Javascript - MEAN Stack Unit-2 N
Javascript - MEAN Stack Unit-2 N
JAVA SCRIPT
Java Script:
JavaScript is a programming language used for creating dynamic, interactive web pages and web
applications. It is a client-side scripting language, which means it runs on the user's web browser
rather than on the server.
JavaScript is commonly used for adding functionality to web pages such as form validation, creating
animations, and making web pages more interactive. It is also used for developing web applications,
including single-page applications (SPAs), which allow users to interact with web pages without having to
reload the entire page.
JavaScript was first released in 1995 by Netscape Communications Corporation and has since become one
of the most widely used programming languages on the web. It is often used alongside HTML and CSS,
which are used for creating the structure and style of web pages, respectively.
JavaScript has evolved significantly over the years, with new features and updates being added to the
language on a regular basis. Some of the most popular frameworks and libraries built on top of JavaScript
include React, Angular, and Vue.js.
Why We Need JavaScript:
JavaScript is an essential component of modern web development, and there are several reasons why we
need it:
1. Dynamic Interactivity: JavaScript allows web developers to create interactive and dynamic web pages
that respond to user actions without needing to reload the entire page. This makes for a more engaging
and user-friendly experience.
2. Form Validation: JavaScript can be used to validate user input on web forms before it is submitted
to the server. This helps to ensure that the data submitted is accurate and meets certain criteria.
3. Client-side Processing: JavaScript allows web developers to perform calculations, manipulate data,
and perform other operations on the client-side. This reduces the load on the server and improves the
overall performance of web applications.
But server-side languages
have certain limitations
such as :-
Multiple request-
response cycles to
handle multiple user
requests
More network
bandwidth
consumption
Increased response
time
4. Cross-browser Compatibility: JavaScript is supported by all major web browsers, which means that
web developers can write code once and have it run on multiple platforms without the need for
additional code.
5. Integration with other technologies: JavaScript can be used in conjunction with other web
technologies such as HTML, CSS, and AJAX to create powerful and sophisticated web applications.
Overall, JavaScript is a versatile and essential tool for modern web development, allowing developers
to create interactive, engaging, and responsive web applications that can run on any platform.
What is JavaScript:
JavaScript is the programming language for web users to convert static web pages to dynamic web pages.
Web page designed using HTML and CSS is static.
Overall, identifiers are an important part of writing clear and readable code in JavaScript. By using
meaningful and descriptive names for your variables, functions, objects, and classes, you can make your
code easier to understand and maintain.
Primitive & Non-Primitive Data Types:
In JavaScript, there are two main categories of data types: primitive and non-primitive (or reference) types.
1. Primitive Data Types: Primitive data types are simple, immutable data types that are stored
directly in memory. They are also passed by value, meaning that when you pass a primitive data
type as an argument to a function or assign it to a variable, a copy of the value is created. The
following are the six primitive data types in JavaScript:
➢ Number: Represents numerical values, including integers and floating-point numbers. For example:
var x = 3; var y = 3.14;
➢ String: Represents textual data, enclosed in single or double quotes. For example:
var name = "John"; var message = 'Hello, world!';
➢ Boolean: Represents a logical value, either true or false. For example:
var isStudent = true; var isAdmin = false;
➢ Null: Represents the intentional absence of any object value. For example:
var value = null;
➢ Undefined: Represents a declared variable that has not been assigned a value. For example:
var value;
➢ Symbol: Represents a unique, immutable value that is used as an identifier for object properties.
Symbols were added in ECMAScript 6. For example:
var id = Symbol("id");
2. Non-Primitive (Reference) Data Types: Non-primitive data types are more complex data types
that are not stored directly in memory, but rather as a reference to a location in memory where the
data is stored. When you pass a non-primitive data type as an argument to a function or assign it to a
variable, you are passing a reference to that data, rather than a copy of the data itself. The following
are examples of non-primitive data types in JavaScript:
➢ Object: Represents a collection of properties and values. For example:
var person = {
name: "John",
age: 30
};
➢ Array: Represents a collection of values, stored in an ordered list. For example:
var numbers = [1, 2, 3, 4, 5];
➢ Function: Represents a reusable block of code that performs a specific task. For example:
function greet(name) {
console.log("Hello, " + name + "!");
}
Overall, understanding the difference between primitive and non-primitive data types in JavaScript is
important for writing efficient and effective code.
Operators & Type of Operators:
In JavaScript, operators are used to perform various types of operations on values, such as mathematical
operations, logical operations, and assignment operations. Here are some common types of operators in
JavaScript:
1. Arithmetic Operators: Arithmetic operators are used to perform mathematical operations on
numerical values. The following are arithmetic operators in JavaScript:
Addition: +
Subtraction: -
Multiplication:
* Division: /
Modulus: %
Increment: ++
Decrement: --
2. Comparison Operators: Comparison operators are used to compare two values and return a Boolean
value (true or false). The following are comparison operators in JavaScript:
Equal to: ==
Not equal to: !=
Strict equal to: ===
Strict not equal to: !==
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
3. Logical Operators: Logical operators are used to perform logical operations on Boolean values.
The following are logical operators in JavaScript:
Logical AND: &&
Logical OR: ||
Logical NOT: !
4. Assignment Operators: Assignment operators are used to assign values to variables. The following are
assignment operators in JavaScript:
Assignment: =
Addition assignment: +=
Subtraction assignment: -=
Multiplication assignment: *=
Division assignment: /=
Modulus assignment: %=
5. Bitwise Operators: Bitwise operators are used to perform bitwise operations on binary values. The
following are bitwise operators in JavaScript:
Bitwise AND: &
Bitwise OR: |
Bitwise XOR: ^
Bitwise NOT: ~
Left shift: <<
Right shift: >>
Zero-fill right shift: >>>
Overall, understanding the different types of operators in JavaScript is important for writing complex and
efficient code. By using operators effectively, you can perform a wide range of operations on values and
create complex logic in your code.
Types of Statements:
In JavaScript, the statements can be classified into two types.
Conditional Statements:
Conditional statements help you to decide based on certain conditions.
These conditions are specified by a set of conditional statements having boolean expressions that are
evaluated to a boolean value true or false.
Non-Conditional Statements:
Non-Conditional statements are those statements that do not need any condition to control the program
execution flow.
Non-Conditional statements are those statements that do not need any condition to control the program
execution flow.
Types of Non-Conditional Statements
Comments
Comments in JavaScript can be used to prevent the execution of a certain lines of code and to
add information in the code that explains the significance of the line of code being written.
JavaScript supports two kinds of comments.
Example:
// Formula to find the area of a circle given its radius
var areaOfCircle = 2 * pi * radius;
/*Formula to find the area of a circle based on
given its radius value.
*/
var areaOfCircle = 2 * pi * radius;
Note: As a best practice, it is recommended to use comments for documentation purposes and avoid using it
for code commenting.
Break Statement
While iterating over the block of code getting executed within the loop, the loop may be required to be
exited if certain condition is met.
The 'break' statement is used to terminate the loop and transfer control to the first statement following the
loop.
Syntax:
break;
Below example shows for loop with five iterations which increment variable "counter".
When loop counter = 3, loop terminates. Also, shown below is the value of the counter and loopVar for
every iteration of the loop.
var counter = 0;
for (var loop = 0; loop < 5; loop++) {
if (loop == 3)
break;
counter++;
}
loopVar counter
0 1
1 2
loopVar counter
2 3
3 Loop terminated. counter = 3.
The 'if' statement used in the above example is a conditional / decision-making statement.
Continue Statement
There are times when during the iteration of the block of code within the loop, the block execution may be
required to be skipped for a specific value and then continue to execute the block for all the other values.
JavaScript gives a 'continue' statement to handle this.
Continue statement is used to terminate the current iteration of the loop and continue execution of the loop
with the next iteration.
Syntax:
continue;
Below example shows for loop with five iterations which increment variable "counter".
When loop counter = 3, the current iteration is skipped and moved to the next iteration.
Also, shown below is the value of the counter and the variable loop for every iteration of the loop.
var counter = 0;
for (var loop = 0; loop < 5; loop++) {
if (loop == 3)
continue;
counter++;
}
loopVar counter
0 1
1 2
2 3
3 Iteration terminated. Hence counter is not incremented.
4 4
The 'if' statement used in the example is a conditional / decision-making statement.
Types of Conditional Statements
Conditional statements help in performing different actions for different conditions.
It is also termed as decision-making statements.
Ternary operator
It is a conditional operator that evaluates to one of the values based on whether the condition is true or false.
It happens to be the only operator in JavaScript that takes three operands. It is mostly used as a shortcut of
'if-else' condition.
Example:
let n = 10;
let res;
(n%2 ==0) ? res = "even" : res = "odd";
console.log(res);
StatementsIn JavaScript, there are several types of statements that can be used to control the flow of the
program, define variables, and execute code. Here are the most common types of statements in JavaScript:
1. Expression Statements: Expression statements are used to evaluate an expression and potentially
update a variable. For example:
var x = 5;
x = x + 1;
2. Conditional Statements: Conditional statements are used to control the flow of the program based on
certain conditions. The following are conditional statements in JavaScript:
➢ If statement: Executes a block of code if a specified condition is true. For example:
if (x > 5)
{
These non-conditional statements are essential building blocks for writing JavaScript code. By
understanding how to use them effectively, you can create variables, functions, objects, and arrays that can
be used to perform a wide range of tasks in your JavaScript programs.
Types of Conditional Statements:
Conditional statements in JavaScript are used to make decisions based on a certain condition or set of
conditions. There are three types of conditional statements in JavaScript:
1. if statement: The if statement is the most basic type of conditional statement in JavaScript. It is used
to execute a block of code if a certain condition is true. The syntax for the if statement is as follows:
if (condition) {
// code to execute if the condition is true
}
2. if...else statement: The if...else statement is used when you want to execute one block of code if a
condition is true, and a different block of code if the condition is false. The syntax for the if...else
statement is as follows:
if (condition) {
// code to execute if the condition is true
}
else {
// code to execute if the condition is false
}
3. switch statement: The switch statement is used when you want to execute different blocks of code
depending on the value of an expression. The switch statement evaluates the expression and executes
the block of code that corresponds to the value of the expression. The syntax for the switch statement
is as follows:
switch (expression) {
case value1:
// code to execute if expression is equal to value1
break;
case value2:
// code to execute if expression is equal to value2
break;
...
default:
// code to execute if expression doesn't match any of the cases
break;
}
These conditional statements are essential for creating flexible and dynamic JavaScript programs. By using
them, you can make your code respond to different situations and conditions, and perform different
actions based on the input or data that it receives.
If & Switch Statements:
In JavaScript, if and switch statements are conditional statements that allow you to execute different
blocks of code based on certain conditions. Here is an overview of how these statements work:
if Statement:
The if statement is used to execute a block of code if a certain condition is true. Here is the basic syntax for
the if statement:
if (condition) {
// code to execute if the condition is true
}
You can also use an else clause to execute a different block of code if the condition is false. Here is an
example:
if (condition) {
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if neither condition1 nor condition2 is true
}
Switch Statement:
The switch statement is used to execute different blocks of code based on the value of an expression. Here
is the basic syntax for the switch statement:
switch (expression) {
case value1:
// code to execute if expression is equal to value1
break;
case value2:
Here's an example of how to use a for loop to print the numbers 1 through 5:
for (var i = 1; i <= 5; i++) {
console.log(i);
}
//Output: 1 2 3 4 5
While Loop:
The while loop is used when you don't know how many times you need to execute a block of code. The
loop will continue to execute as long as the condition is true. The basic syntax for the while loop is as
follows:
while (condition) {
// code to execute
}
Here's an example of how to use a while loop to print the numbers 1 through 5:
var i = 1;
while (i <= 5) {
console.log(i);
i++;
} //Output: 1 2 3 4 5
do...while Loop:
The do...while loop is similar to the while loop, but it will always execute the block of code at least once,
even if the condition is false. The basic syntax for the do...while loop is as follows:
do {
// code to execute
}while (condition);
Here's an example of how to use a do...while loop to print the numbers 1 through 5:
var i = 1;
do {
console.log(i);
i++;
} while (i <= 5); //Output: 1 2 3 4 5
All three types of loops are important tools for creating flexible and dynamic JavaScript programs that can
handle a wide range of input and conditions.
Functions in javascript:
Functions are one of the integral components of JavaScript. A JavaScript function is a set of statements that
performs a specific task. They become a reusable unit of code.
In JavaScript, functions are first-class objects. i.e., functions can be passed as an argument to other
functions, it can be a return value of another function or can be assigned as a value to a variable.
JavaScript leverages this behavior to extend its capabilities.
Types of Functions:
JavaScript has two types of functions.
1. User-defined functions
JavaScript allows to write own functions called as user-defined functions. The user-defined functions
can also be created using a much simpler syntax called arrow functions.
2. Built-in functions
JavaScript provides several predefined functions that perform tasks such as displaying dialog boxes,
parsing a string argument, timing-related operations, and so on.
In JavaScript, there are several types of functions that you can use to organize your code and make it more
reusable. Here are the main types of functions in JavaScript:
1. Function Declarations:
A function declaration defines a named function with a specified set of parameters. You can call the
function by using its name and passing in the required arguments. Here's the basic syntax for a function
declaration:
function functionName(parameters) {
// code to execute
}
Here's an example of how to define and call a function:
function sayHello(name) {
console.log("Hello, " + name + "!");
}
sayHello("John"); // Output: Hello, John!
2. Function Expressions:
A function expression defines a function as part of an expression, rather than as a statement. This allows
you to define and call functions dynamically at runtime. Here's the basic syntax for a function expression:
var functionName = function(parameters) {
// code to execute
};
Here's an example of how to define and call a function expression:
var sayHello = function(name) {
console.log("Hello, " + name + "!");
};
sayHello("John"); // Output: Hello, John!
3. Arrow Functions:
Arrow functions provide a more concise syntax for defining functions. They are similar to function
expressions, but with a simpler syntax and an implicit return value. Here's the basic syntax for an arrow
function:
var functionName = (parameters) => {
// code to execute
};
Here's an example of how to define and call an arrow function:
var sayHello = (name) => {
console.log("Hello, " + name + "!");
};
sayHello("John"); // Output: Hello, John!
4. Anonymous Functions:
An anonymous function is a function without a name. Anonymous functions are often used as callback
functions, or as functions that are immediately invoked. Here's an example of how to define and call an
anonymous function:
var addNumbers = function(a, b) {
return a + b;
}
5. Named Functions:
A named function is a function that has a name and can be called using that name. Here is an example of a
named function:
function addNumbers(a, b) {
return a + b;
}
You can call this function by using its name, like this:
var result = addNumbers(2, 3);
console.log(result); // Output: 5
6. IIFE (Immediately Invoked Function Expressions):
An IIFE is a function that is executed immediately after it is created. This can be useful for creating private
scopes or for executing code that needs to run once. Here is an example of an IIFE:
(function() {
// code to execute
})();
The parentheses around the function expression are necessary to tell JavaScript that this is a function
expression and not a function declaration.
7. Recursive Functions:
A recursive function is a function that calls itself. Recursive functions can be used to solve problems that
can be broken down into smaller sub-problems. Here is an example of a recursive function:
function factorial(n) {
if (n === 0) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
This function calculates the factorial of a number by calling itself with a smaller value until it reaches the
base case (n = 0).
These are some of the most common types of functions in JavaScript. By using these functions effectively,
you can create powerful and flexible programs that can handle a wide range of tasks.
function outerFunction() {
console.log('Outer function is called.');
function innerFunction() {
console.log('Inner function is called.');
}
innerFunction();
}
outerFunction();
In this example, innerFunction is defined inside outerFunction. When outerFunction is called, it logs
a message to the console and then calls innerFunction, which logs another message to the console.
Nested functions can be useful in JavaScript because they can be used to encapsulate functionality and
keep it private to the outer function. This can be useful for creating modular code and avoiding naming
conflicts.
One common use case for nested functions is when creating closures. A closure is a function that has
access to variables in its lexical scope, even after the outer function has returned. Here's an example:
function outerFunction() {
let counter = 0;
function incrementCounter() {
counter++;
console.log('Counter value:', counter);
}
return incrementCounter;
}
const myCounter = outerFunction();
myCounter(); // Output: Counter value: 1
myCounter(); // Output: Counter value: 2
myCounter(); // Output: Counter value: 3
Built-in-Functions:
JavaScript has a wide range of built-in functions, also known as global functions, that are available for use
without needing to define them first. These functions are built into the JavaScript language and are
available globally to all scripts.
Here are some commonly used built-in functions in JavaScript:
➢ console.log(): This function is used to output data to the console for debugging purposes. It takes
any number of arguments, which are printed to the console as separate messages.
➢ parseInt(): This function converts a string to an integer. It takes a string as an argument and returns
an integer.
➢ parseFloat(): This function converts a string to a floating-point number. It takes a string as
an argument and returns a number.
➢ alert(): This function creates a pop-up window with a message. It takes a string as an argument and
displays it in the pop-up window.
➢ confirm(): This function creates a pop-up window with a message and two buttons, "OK" and
"Cancel". It returns true if the user clicks "OK" and false if the user clicks "Cancel".
➢ prompt(): This function creates a pop-up window with a message and an input field for the user
to enter data. It returns the value entered by the user as a string.
➢ setTimeout(): This function executes a function after a specified amount of time. It takes two
arguments: the function to execute and the time delay in milliseconds.
➢ setInterval(): This function executes a function repeatedly at a specified interval. It takes two
arguments: the function to execute and the time interval in milliseconds.
These are just a few of the built-in functions available in JavaScript. There are many more functions that
provide powerful functionality for manipulating data, working with the DOM, handling events, and
more.
Other Built-in Functions:
Built-in
Description Example
functions
It throws an alert box and is often used when user
alert() interaction is required to decide whether execution alert("Let us proceed");
should proceed or not.
It throws a confirm box where user can click
let decision = confirm("Shall we
confirm() "OK" or "Cancel". If "OK" is clicked, the function
proceed?");
returns "true", else returns "false".
It produces a box where user can enter an input.
The user input may be used for some processing let userInput = prompt("Please enter
prompt()
later. This function takes parameter of type string your name:");
which represents the label of the box.
This function checks if the data-type of given
isNaN(30); //false
isNaN() parameter is number or not. If number, it returns
isNaN('hello'); //true
"false", else it returns "true".
It determines if the number given as parameter is a
finite number. If the parameter value is isFinite(30); //true
isFinite()
NaN,positive infinity, or negative infinity, this isFinite('hello'); //false
method will return false, else will return true.
This function parses string and returns an integer parseInt("10"); //10
number. parseInt("10 20 30"); //10, only the
parseInt()
It takes two parameters. The first parameter is the integer part is returned
string to be parsed. The second parameter parseInt("10 years"); //10
represents radix which is an integer between 2 and parseInt("years 10"); //NaN, the
36 that represents the numerical system to be used first character stops the parsing
and is optional.
The method stops parsing when it encounters a
non-numerical character and returns the gathered
number.
It returns NaN when the first non-whitespace
character cannot be converted to number.
This function parses string and returns a float
number.
parseFloat("10.34"); //10.34
The method stops parsing when it encounters a
parseFloat("10 20 30"); //10
parseFloat() non-numerical character and further characters are
parseFloat("10.50 years"); //10.50
ignored.
It returns NaN when the first non-whitespace
character cannot be converted to number.
It takes an argument of type string which can be an eval("let num1=2; let
eval() expression, statement or sequence of statements num2=3;let result= num1 *
and evaluates them. num2;console.log(result)");
JavaScript provides two-timer built-in functions. Let us explore these timer functions.
Built-in
Description Example
functions
It executes a given function after waiting
function executeMe(){
for the specified number of milliseconds.
console.log("Function says hello!")
It takes 2 parameters. First is the function
setTimeout() }
to be executed and the second is the
setTimeout(executeMe, 3000);
number of milliseconds after which the
//It executes executeMe() after 3 seconds.
given function should be executed.
It cancels a timeout previously
established by calling setTimeout(). function executeMe(){
It takes the parameter "timeoutID" which console.log("Function says hello!")
clearTimeout() is the identifier of the timeout that can be }
used to cancel the execution of let timerId= setTimeout(executeMe, 3000);
setTimeout(). The ID is returned by the clearTimeout(timerId);
setTimeout().
It executes the given function
repetitively. function executeMe(){
It takes 2 parameters, first is the function console.log("Function says hello!");
setInterval() to be executed and second is the number }
of milliseconds. The function executes setInterval(executeMe,3000);
continuously after every given number of //It executes executeMe() every 3 seconds
milliseconds.
function executeMe(){
console.log("Function says hello!");
It cancels the timed, repeating execution }
which was previously established by a let timerId=setInterval(executeMe, 2000);
call to setInterval(). function stopInterval(){
It takes the parameter “intervalID” which clearInterval(timerId);
clearInterval()
is the identifier of the timeout that can be console.log("Function says bye to
used to cancel the execution of setInterval()!")
setInterval(). The ID is returned by the setTimeout(stopInterval,5000)
setInterval(). //It executes executeMe() every 2 seconds
and after 5 seconds, further calls to
executeMe() is stopped.
When myFunction is called, it logs the value of globalVariable and localVariable to the console. When
globalVariable is accessed inside the function, it is found because it has global scope. When localVariable
is accessed outside the function, it results in an error because it has local scope and is not accessible
outside the function.
It is important to be aware of variable scope in functions because it can affect the behavior and
performance of a program. In particular, it is important to avoid naming conflicts between variables with
the same name but different scopes.
Working With Classes:
In JavaScript, classes were introduced in ECMAScript 2015 as a new syntax for creating objects and
defining their properties and methods. Classes are a template for creating objects, and they can be thought
of as blueprints for objects. Here's an example of a class in JavaScript:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
const john = new Person('John', 30);
john.greet(); // Output: Hello, my name is John and I'm 30 years old.
Classes in JavaScript also support inheritance, which allows you to create a new class based on an existing
class. Here's an example:
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
console.log(`${this.name} is studying.`);
}
}
const jane = new Student('Jane', 20, 'A');
jane.greet(); // Output: Hello, my name is Jane and I'm 20 years
old. jane.study(); // Output: Jane is studying.
To create an object from the Student class, the same new keyword is used along with the Student class
name and any arguments required by the constructor method. The jane instance is then created with the
name property set to "Jane", the age property set to 20, and the grade property set to "A". The greet and
study methods can then be called on the jane instance to log messages to the console.
Creating & Inheriting Classes:
In JavaScript, you can create classes using the class keyword, and you can inherit from a parent class using
the extends keyword. Here is an example of creating and inheriting classes in JavaScript:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
class Dog extends Animal {
constructor(name){
super(name);
}
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Fido');
dog.speak(); // Output: Fido barks.
We then create a child class Dog that extends the Animal class using the extends keyword. The Dog class
also has a constructor method that calls the super method to invoke the constructor of the parent class and
set the name property. The Dog class overrides the speak method of the parent class to log a different
message.
Finally, we create an instance of the Dog class called dog and call the speak method on it, which logs the
message "Fido barks." to the console.
In addition to inheriting properties and methods from the parent class, a child class can also define its own
properties and methods. Here is an example:
class Animal{
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
fetch() {
console.log(`${this.name} fetches a ball.`);
}
}
const dog = new Dog('Fido', 'Labrador');
dog.speak(); // Output: Fido barks.
dog.fetch(); // Output: Fido fetches a ball.
console.log(dog.breed); // Output: Labrador
In summary, you can create classes in JavaScript using the class keyword, and you can inherit from a parent
class using the extends keyword. Child classes can override parent class methods and define their own
properties and methods.
In-Built Events & Handlers:
In JavaScript, there are many built-in events that you can use to trigger actions in your web page or
application. You can use event handlers to respond to these events and execute code when the events
occur.
Event- Description
Event
handler
click onclick When the user clicks on an element, the event handler onclick handles it.
keypress onkeypress When the user presses the keyboard's key, event handler onkeypress handles it.
keyup onkeyup When the user releases the keyboard's key, the event handler onkeyup handles it.
load onload When HTML document is loaded in the browser, event handler onload handles it
blur onblur When an element loses focus, the event handler onblur handles it.
When the selection of checked state change for input, select or text-area element changes,
change onchange
event handler onchange handles it.
Here are some of the most common built-in events and their associated event handlers in JavaScript:
1. Click Event - This event occurs when a user clicks on an element, such as a button or a link. The
event handler for this event is the onclick event handler.
Example:
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
alert("Hello World!");
</script>
2. Submit Event - This event occurs when a user submits a form. The event handler for this event is the
onsubmit event handler.
Example: <button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
alert("Hello World!");
}
</script>
3. Mouseover Event - This event occurs when a user moves their mouse over an element. The event
handler for this event is the onmouseover event handler.
Example:
<div onmouseover="myFunction()">Hover over me</div>
<script>
function myFunction() {
alert("Mouse over!");
}
</script>
4. Keydown Event - This event occurs when a user presses a key on their keyboard. The event handler for
this event is the onkeydown event handler.
Example:
<input type="text" onkeydown="myFunction()">
<script>
function myFunction() {
alert("Key down!");
}
</script>
5. Load Event - This event occurs when a web page or image has finished loading. The event handler for
this event is the onload event handler.
Example:
<img src="myimage.jpg" onload="myFunction()">
<script>
function myFunction() {
alert("Image loaded!");
}
</script>
These are just a few examples of the many built-in events and event handlers available in JavaScript. By
using these events and handlers, you can create dynamic and interactive web pages and applications.
Working with Objects:
In JavaScript, objects are a fundamental data structure that allows you to store and manipulate data in a
flexible way. Objects are collections of properties, where each property has a key and a value.
Here's an example of how to create a simple object in JavaScript:
let person = {
name: 'John',
age: 30,
gender: 'male'
};
You can access the properties of an object using dot notation or bracket notation:
// Dot notation
console.log(person.name); // Output: 'John'
// Bracket notation
console.log(person['age']); // Output: 30
You can also add or modify properties of an object:
person.email = '[email protected]'; // Add a new
property person.age = 31; // Modify an existing property
JavaScript also has built-in functions called constructors that allow you to create objects based on a
blueprint or template. Here's an example:
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
let person1 = new Person('John', 30, 'male');
let person2 = new Person('Jane', 25, 'female');
console.log(person1.name); // Output: 'John'
console.log(person2.age); // Output: 25
JavaScript also has a built-in Object class that provides many useful methods for working with objects,
such as Object.keys(), Object.values(), and Object.entries(). Here's an example:
let person = {
name: 'John',
age: 30,
gender: 'male'
};
console.log(Object.keys(person)); // Output: ['name', 'age', 'gender']
console.log(Object.values(person)); // Output: ['John', 30, 'male']
console.log(Object.entries(person)); // Output: [['name', 'John'], ['age', 30], ['gender', 'male']]
These are just a few examples of the many ways to work with objects in JavaScript. By using objects, you
can create powerful and flexible data structures that can be used in a variety of applications.
Types of Objects:
In JavaScript, there are several types of objects that you can work with. Here are some of the most common
types of objects:
1. Built-in Objects - These are objects that are built into the JavaScript language, such as Object, Array,
String, and Number.
Example:
let person = {
name: 'John',
age: 30,
gender: 'male'
};
let names = ['John', 'Jane', 'Joe'];
let message = 'Hello, world!';
let number = 42;
2. Custom Objects - These are objects that you create yourself using constructors or classes.
Example:
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
let person1 = new Person('John', 30, 'male');
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
}
}
let animal1 = new Animal('Fluffy', 'cat');
3. Document Objects - These are objects that represent elements in an HTML document, such as
document, window, and HTMLElement.
Example:
let myDiv = document.getElementById('my-div');
window.alert('Hello, world!');
document.title = 'My Website';
4. Host Objects - These are objects that are provided by the environment in which JavaScript is running,
such as the XMLHttpRequest object for making HTTP requests in a web browser.
Example:
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
console.log(xhr.response);
};
xhr.send();
These are just a few examples of the many types of objects that you can work with in JavaScript. By
understanding the different types of objects and how they work, you can create powerful and flexible
applications that take advantage of JavaScript's object-oriented features.
Creating Objects:
In JavaScript, you can create objects in several ways:
1. Object Literal Syntax:
This is the simplest way to create an object. You can define an object using a pair of curly braces, and then
specify key-value pairs separated by commas.
Example:
const person = {
name: "John",
age: 30,
hobbies: ["reading", "running"]
};
2. Constructor Function:
You can create an object using a constructor function. This involves creating a function that serves as a
blueprint for the object, and then using the "new" keyword to create a new instance of the object.
Example:
class Person {
constructor(name, age, hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
}
const person = new Person("John", 30, ["reading", "running"]);
Combining & Cloning Objects Using Spread Operator:
In JavaScript, you can use the spread operator (...) to combine and clone objects. The spread operator can
be used to spread the properties of one object into another object, and also to create a new object with
the properties of an existing object.
1. Combining objects using the spread operator:
You can combine objects by spreading their properties into a new object. This can be useful when you want
to merge two or more objects into a single object.
Syntax:
let object1Name = {
//properties
};
let object2Name = {
//properties
};
let combinedObjectName = {
...object1Name,
...object2Name
};
//the combined object will have all the properties of object1 and object2
Example:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj); // Output: { a: 1, b: 2, c: 3, d: 4 }
2. Cloning objects using the spread operator:
You can clone an object by spreading its properties into a new object. This creates a new object with the
same properties as the original object, but they are not reference equal.
Syntax: let copyObject = { ...originalObject };
Example:
const obj1 = { a: 1, b: 2 };
const clonedObj = { ...obj1 };
console.log(clonedObj); // Output: { a: 1, b: 2 }
console.log(obj1 === clonedObj); // Output: false
To perform a deep copy of an object, you can use a library such as lodash, or you can write your own
recursive function that clones nested objects.
Destructing Objects:
In JavaScript, object destructuring is a way to extract properties from an object and assign them to variables
with the same name as the property. This can make your code more concise and easier to read.
Here's an example of how to destructure an object:
const person = { name: 'John', age: 30, hobbies: ['reading', 'running'] };
const { name, age, hobbies } = person;
console.log(name); // Output: 'John'
console.log(age); // Output: 30
console.log(hobbies); // Output: ['reading', 'running']
You can also use destructuring to assign default values to variables if the property does not exist on the
object:
const person = { name: 'John', age: 30 };
const { name, age, hobbies = [] } = person;
console.log(hobbies); // Output: []
You can also use destructuring with nested objects:
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA'
}
};
const { name, age, address: { city } } = person;
console.log(city); // Output: 'Anytown'
Browser & Document Object Model:
In JavaScript, the Browser Object Model (BOM) and the Document Object Model (DOM) are two
important APIs that allow JavaScript code to interact with the web browser and the document displayed in
it.
The Browser Object Model (BOM) provides JavaScript access to the browser's window and its various
components such as the location bar, history, and screen. The BOM is not standardized and varies between
different browsers.
Browser Object ModelThe Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by specifying
window or directly. For example: window.alert("hello javascript");
is same as:alert("hello javascript ");
properties
The window
object represents a window
in browser. An object of window is created automatically by the browser.
Methods of window object
The important methods of window object are as follows:
Method Description
The Document Object Model (DOM) provides JavaScript access to the HTML document displayed in
the browser. The DOM represents the document as a tree-like structure of nodes, and allows JavaScript
code to manipulate the structure and content of the document.
The HTML DOM Tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element
Some commonly used DOM methods include:
➢ document.getElementById() - returns the element with the specified ID.
➢ document.createElement() - creates a new HTML element.
➢ element.appendChild() - adds a new child node to an element.
➢ element.innerHTML - gets or sets the HTML content of an element.
Here's an example of how to use the DOM to manipulate the content of an HTML page:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="myHeading">Hello World!</h1>
<button id="myButton">Click me</button>
<script>
const heading = document.getElementById('myHeading');
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
heading.innerHTML = 'Hello JavaScript!';
});
</script>
</body>
</html>
Creating Arrays:
In JavaScript, arrays are a type of object that can store multiple values in a single variable. Here are some
ways to create arrays in JavaScript:
1. Literal notation: You can create an array using literal notation by enclosing a comma-separated list
of values in square brackets []:
const fruits = ['apple', 'banana', 'orange'];
2. Constructor notation: You can also create an array using the Array constructor and passing in the
initial values as arguments:
const numbers = new Array(1, 2, 3, 4, 5);
3. Empty array: You can create an empty array by using literal notation with no values between
the brackets or by using the Array constructor with no arguments:
const emptyArray1 = [];
const emptyArray2 = new Array();
Once you have created an array, you can access its elements using bracket notation and the index of the
element, which starts at 0:
const fruits = ['apple', 'banana'];
console.log(fruits[0]); // Output: 'apple'
console.log(fruits[1]); // Output: 'banana'
You can also modify the values of individual elements or add new elements to the array:
function func1() {
console.log("Am in func1");
}
function func2() {
console.log("Am in func2");
}
According to JavaScript sequentially execution nature, the output of the above code snippet would be as
shown below:
If previous code is modified by adding setTimeout() method in for loop as shown below, then observe the
output once again.
Modified code snippet:
for (var i = 0; i < 2; i++) {
setTimeout(function() {
console.log("setTimeout message");
func1();
},5000 );
func2();
}
New Output:
As observed in the output above, due to usage of setTimeout() method the entire execution of code behavior
has been changed, and the code has been executed asynchronously.
Asynchronous Programming Techniques
Some of the real-time situations where you may need to use the JavaScript Asynchronous code of execution
while implementing business logic are:
To make an HTTP request call.
To perform any input/output operations.
To deal with client and server communication.
These executions in JavaScript can also be achieved through many techniques.
Some of the techniques are:
Callbacks
Promises
Async/Await
Callbacks:
A callback function is a function that is passed as an argument to another function. Callbacks make sure that
a certain function does not execute until another function has already finished execution.
Callbacks are handy in case if there is a requirement to inform the executing function on what next when the
asynchronous task completes. Here the problem is there are bunch of asynchronous tasks, which expect you
to define one callback within another callback and so on. This leads to callback hell.
Callback hell, which is also called a Pyramid of Doom, consists of more than one nested callback which
makes code hard to read and debug. As calls become more nested, the code becomes deeper and increasingly
more difficult to manage, especially if there are more loops, conditional statements, and so on in the code.
Example:
myFun1(function () {
myFun2(function () {
myFun3(function () {
myFun4(function () {
....
});
});
});
});
In the above example, it is noticed that the "pyramid" of nested calls grows to the right with every
asynchronous action. It leads to callback hell. So, this way of coding is not very good practice.
To overcome the disadvantage of callbacks, the concept of Promises was introduced.
Promises
A Promise is a holder for a result (or an error) that will become available in the future.
Promise provides a more structured way to write asynchronous calls.
Promises have replaced callback functions as the preferred programming style for handling asynchronous
calls.
Built-in support for promises has been introduced as part of JavaScript from 2015.
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its
resulting value.
A Promise is a returned object to which you can attach callbacks, instead of passing callbacks into a
function.
Promise comes to the rescue when there are chained asynchronous calls that are dependent on each other.
Using Promises
The constructor of the Promise accepts only one argument, a function with parameters resolve and reject.
new Promise(function (resolve, reject) {
//async code here
//resolve if success, reject if error
});
A Promise has three states:
Pending: the result of the async call is not known yet.
Resolved: async call returned with success.
Rejected: async call returned with an error.
To structure the async code, the async operation will be wrapped in a Promise object and handled using
"then".
var myPromise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("success");
}, 2000);
});
myPromise.then(
function (data) {
console.log(data + " received in 2 seconds");
},
function (error) {
console.log(error);
}
); //output: Success receive in 2 seconds
Promises have replaced callbacks and have solved the problem of ‘callback hell’. The sample code has
been shown below to understand how developers handled multiple asynchronous calls without Promises in
traditional JavaScript applications.
doSomething(function(result){
doSomethingElse(result,function(newResult){
doThirfThing(newResult,function(finalResult){
console.log('Print the final result ' +finalResult);
}, failureCallback);
}, failurCallback);
}, failureCallback);
The ’Callback hell’, is now resolved using ‘Chaining’ which creates readable code and is an eminent
feature of Promise. Here, the asynchronous code can be chained using multiple then statements.
doSomething().then(function (result) {
return doSomethingElse(result);
})
.then(function (newResult) {
return doThirdThing(newResult);
})
.then(function (finalResult) {
console.log("Print the final result " + finalResult)
})
.catch(failureCallBack);
Async and Await
"async/await" was introduced to implement asynchronous code with promises that resemble synchronous
code. "async/await" is simple, easy, readable and understandable than the promises.
Async/Await vs Promises
Async/Await Promises
Scope The entire wrapper function is asynchronous. Only the promise chain itself is asynchronous.
Synchronous work needs to be moved
Synchronous work can be handled in
out of the callback.
Logic the same callback.
Multiple promises can be handled with
Multiple promises use Promise.all().
simple variables.
Error
You can use try, catch and finally. You can use then, catch and finally.
Handling
Using Async/Await
Async Function
An async function is declared with an async keyword. It always returns a promise and if the value returned
is not a promise, the JavaScript will automatically wrap the value in a resolved promise.
Example:
async function hello() {
//Value will be wrapped in a resolved promise and returned
return "Hello Async";
}
hello().then(val => console.log(val)); // Hello Async
Await
Await keyword makes JavaScript wait until the promise returns a result. It works only inside async
functions. JavaScript throws Syntax error if await is used inside regular functions. Await keyword pauses
only the async function execution and resumes when the Promise is settled.
Example:
function sayAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}