0% found this document useful (0 votes)
24 views28 pages

JS Students Notes-1

The document discusses the basics of JavaScript including its history, features, uses, differences from Java, data types, variables, and other core concepts. Key topics covered include JavaScript being an interpreted, client-side scripting language; its development in 1995; features like being lightweight, dynamically typed, and more. The summary also mentions variables like var, let, const and hoisting in JavaScript.

Uploaded by

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

JS Students Notes-1

The document discusses the basics of JavaScript including its history, features, uses, differences from Java, data types, variables, and other core concepts. Key topics covered include JavaScript being an interpreted, client-side scripting language; its development in 1995; features like being lightweight, dynamically typed, and more. The summary also mentions variables like var, let, const and hoisting in JavaScript.

Uploaded by

yusaf012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

What is JavaScript?

Javascript is a high-level , object based ,programming language. Javascript is a interpreted, user


friendly ,client-side scripting language.

History of javascript:

javascript developed by Brenden Eich-1995

First name of javascript --> MOCHA

next --> LIVESCRIPT

next--> JAVASCRIPT

FEATURES OF JAVASCRIPT:

1)Light Weight

2)interpreted language

3)Dynamically typed language

4)Weakly typed language

5)client-side scripting language

6)Synchronous language

Javascript characteristics:

1. Client-side-Scripting language - no compiler and without help of server logic we can update the data
2. High-level language - user-friendly
3. Interpreted language – line by line execution
4. Loosely typed – no strong syntax
5. Dynamic language – can change the datatype during the runtime
6. Object-based language – In JavaScript everything was object

Uses of JavaScript:

Difference between Java and JavaScript


Java javascript
Java is a strongly typed language and variables
JavaScript is a loosely typed language and has a
must be declared first to use in the program. Inmore relaxed syntax and rules.
Java, the type of a variable is checked at compile-
time.
Java is an object-oriented programming language JavaScript is a scripting language used for
primarily used for developing complex logic creating interactive and dynamic web pages.
applications.
Java applications can run in any virtual JavaScript code used to run only in the browser,
machine(JVM) or browser. but now it can run on the server via Node.js.
Objects of Java are class-based even we can’tJavaScript Objects are prototype-based.
make any program in java without creating a
class.
Java program has the file extension “.Java” andJavaScript file has the file extension “.js” and it is
translates source code into bytecodes which areinterpreted but not compiled, every browser has
executed by JVM(Java Virtual Machine). the Javascript interpreter to execute JS code.
Java supports multithreading, which allows JavaScript does not support multithreading,
multiple threads of execution to run concurrently
although it can simulate it through the use of web
within a single program. workers.
Java has a rich set of libraries and frameworksJavaScript
for has a wide variety of libraries and
building enterprise applications, such as Spring,
frameworks for building web applications, such
Hibernate as React, Angular, and Vue.
Java is mainly used for backend. Javascript is used for the frontend and backend
Java is statically typed, which means that databoth.
types are determined at compile time. JavaScript is dynamically typed, which means
Java uses more memory that data types are determined at runtime.
Javascript uses less memory.

Note: The file extension for the javascript is .js

Attaching the javascript file to html file:


We can attach the js file with html file in 2 ways.
1.Internal Way
2.External Way
1.Internal Way
By writing the code of javascript inside <script></script> tag
Syntax:
<body>
<h1>hello world</h1>
<script>
// javascript code……….
</script>
</body>
2. External Way
1. To write javascript externally to html file, we need to create an external javascript file with
extension as .js (ex: index.js)
2. After that link that javascript file to the html by using script tag.
Example:
<body>
<script src = “./index.js “></script>
</body>

Printing Statements in javascript:


In javascript we have 2 types of printing statements
1.document.write();
2.console.log();

1.document.write()
document.write() is a printing statement which is used to see the output in the web browser (client
purpose)
2.console.log()
Console.log() is a printing statement which is used to see the output in the console window
(developer view)
Here, console. is an object , dot is a period (or) access operator and log is a function and member of console.
that accepts argument as data to print in console.

TOKENS:

In JavaScript, a token is the smallest unit of a program that is meaningful to the interpreter.
JavaScript code is made up of various types of tokens, including

1. Keywords:
Reserved words that have special meanings in the language. Examples include var, if, else, for, while,
etc.
NOTE: Every keyword must be in the lower case and it is not used as Identifiers.

2. Identifiers:
These are names that are used to identify variables, functions, and other objects. For example, the
identifier myVariable could be used to identify a variable that stores the value 5.

Rulers: -an identifiers can't start with number. -We can’t use keywords as identifiers. -Except $, _ no
other Special Characteristics are allowed.
3.Literals:
Data which is used in the js programming is called as literals. For example, the literal 5 is a numeric
literal, and the literal "Hello, world!" is a string literal.

4. Operators:

These are symbols that are used to perform operations on operands. For example, the operator + is used to add
two numbers together.

JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables

1. var x = 10;
2. var _value="sonoo";

Incorrect JavaScript variables

1. var 123=30;
2. var *aa=320;

i. .

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript primitive data types

There are five types of primitive data types in JavaScript. They are as follows:

 Number

 String
 Undefined

 Null

 Boolean

 bigint

JavaScript non-primitive data types

The non-primitive data types are as follows:

 Object
 Array
 Function

Javascript var,let,const

Declaration Initialization Declaration Re- Re- Re-


declaration
and Declaration Initialization &
initialization Re-
Initialization
var ✓ ✓ ✓ ✓ ✓ ✓
let ✓ ✓ ✓ ✕ ✓ ✕
const ✕ ✕ ✓ ✕ ✕ ✕

GEC (Global Execution Context)

• Global Execution Context is a block of memory


• The global Execution context has two parts
1. Variable Phase
2. Execution Phase / Functional Phase
• JavaScript engine generally uses two phases to execute a JS code.
ii. Phase I (Variable Phase): All the memory is allocated for the declaration in
top to bottom order and assignment with the default value undefined in
variable area of global execution context.

Phase II (Execution Phase): All the instruction get executed in top to bottom order in execution area of
global execution context

Window object

When a JS file is given to browser by default a global window object is created and the
reference is stored in window variable.
The global object consist of pre-defined members (functions and variables) which belong to browser
window.
Any member we declare var in JS file is added inside global window object by JS engine. So we can
use member with the help of window.
Any members(functions and variable) created in global scope will be added into the window object
implicitly by JS Engine

var a=10; //var a is added into the global window object.


console.log(window.a); //10

Hoisting: Utilizing the variable before declaration and initialization is called as Hoisting.

Hoisting can be achieved by var, because var is a global scope or global variable.
Hoisting cannot be achieved by let and const, because let and const are script scope.
Whenever we hoist var the result is undefined.
Whenever we try to hoist let and const the result is Uncaught ReferrenceError.

Temporal Dead Zone (TDZ): In the process of hoisting the time taken between Utilization of the
variable before declaration and initialization.
TDZ is achieved only in let and const.
Because, whenever we try to hoist let and const the result is Uncaught ReferrenceError.
TDZ cannot be achieved in var.
Because, whenever we hoist var the result is undefined.

JavaScript Functions:
A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

Example:

function name(parameter1, parameter2, parameter3) {


// code to be executed
}

Function Invocation

The code inside the function will execute when "something" invokes (calls) the
function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)
Function Return:

When JavaScript reaches a return statement, the function will stop executing.If the
function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.

Why Functions?

With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

Types of Functions in JS:


1. Anonymous function
2. Named function
3. Function with expression
4. Nested function
5. Immediate invoking function
6. Arrow function
7. Higher order function
8. Callback function

1.Anonymous function
A function without name is known as Anonymous function

Syntax :

function(parameters) {

// function body

2.Named Function

A function with name is called as named function


Syntax :
function functionName(parameters) {
// function body
}
3 . Function with expression
It is the way to execute the anonymous function
Passing whole anonymous function as a value to a variable is known as function with
expression.
The function which is passed as a value is known as first class function
EX: let x=function(){
//block of code
}
x();

4.Nested function

A function which is declared inside another function is known as nested function.


Nested functions are unidirectional i.e., We can access parent function properties in child function
but vice-versa is not possible.
The ability of js engine to search a variable in the outer scope when it is not available in the local
scope is known as lexical scoping or scope chaining.
Whenever the child function needs a property from parent function the closure will be formed and
it consists of only required data.
A closure is a feature of JavaScript that allows inner functions to access the outer scope of a
function. Closure helps in binding a function to its outer boundary and is created automatically
whenever a function is created. A block is also treated as a scope since ES6. Since JavaScript is
event-driven so closures are useful as it helps to maintain the state between events.

Function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
}
child ();
}
parent ();

JavaScript currying

Calling a child function along with parent by using one more parenthesis is known as java script
currying
Example:
Function parent () {
let a=10;
function child () {
let b=20;
console.log(a+b);
}
return child;
}
parent () (); ==JavaScript currying

Immediate invoking function(IIF):


A function which is called immediately as soon as the function declaration is known as IIF
We can invoke anonymous function by using IIF
Example:
(function () {
console.log(“Hello”);
})();

Arrow function:
It was introduced in ES6 version of JS.
The main purpose of using arrow function is to reduce the syntax.
Example:
Let x= (a, b) =>console.log(a+b);
Let y=(a,b)=>{return a + b };

Rules to write arrow function:-


1) In arrow function no need of writing 'function' keyword
2) In arrow function no need of writing function_name
3) we can neglect {} whenever we have only 1 printing statement
4) we can neglect () whenever we have only 1 parameter
5) we can also neglect () whenever we dont have any parameter but it has to be replaced with '_'
6) we can write return type function even without return keyword using arrow function
7) if we are using {} it is mandatory to use return keyword

Higher order function(HOF):

A function which accepts a function as a parameter is known as HOF


It is used to perform multiple operations with different values.

Example:
Function hof (a, b, task){
Let res=task(a,b);
return res;
};
Let add=hof(10,20,function(x , y){
return x + y;
}
Let mul = hof(10,20,function(x , y){
return x*y;
}
Console.log(add());
Console.log(mul());
Callback function:

A function which is passed as an argument to another function is known as callback function.


The function is invoked in the outer function to complete an action
Example :
function first(){
Console.log(“first”);
}
function second(){
Console.log(“third”);
}
function third(callback){
Console.log(“second”);
Callback()
}
first();
third(second);
STRING CONCEPT IN JAVASCRIPT

STRING:-Collection of characters (or) bunch of characters we called it as


string

String methods:-
String.length
String.slice()
String.substring()
String.substr()
String.replace()
String.replaceAll()
String.toUpperCase()
String. toLowerCase
String.concat()
String.trim()
String.trimStart()
trimEnd()
padStart()
padEnd()
String charAt()
String charCodeAt()
String split()

JAVASCRIPT ARRAYS
ARRAYS:- Array is collection of different elements.Array is heterogrnous in nature.
• In javascript we can create array in 3 ways.
1. By array literal
2.By using an Array constructor (using new keyword)
1) JavaScript array literal:-
• The syntax of creating array using array literal is: var
arrayname=[value1,value2.....valueN];
• As you can see, values are contained inside [ ] and separated by , (comma).
• The .length property returns the length of an array.

Ex:-<script>
var emp=["Sonoo","Vimal","Ratan"]; for (i=0;i<emp.length;i++)
{ document.write(emp[i] + "<br/>");
}
</script>

2) JavaScript array constructor (new keyword):-


Here, you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly.
Ex:-
<script>
var emp=new Array("Jai","Vijay","Smith"); for (i=0;i<emp.length;i++)
{ document.write(emp[i] + "<br>");
}
</script>
Output:- Jai
Vijay Smith

Java script Array methods:


push() : It will insert an element of an array at the end
unshift() : It will insert an element of an array at the first
pop() : It will remove elements of array from the end
shift() : It will remove elements of array from the start
indexOf() :It will return a index of particular element
Includes() : It will check whether the particular element is present in array or not.
At() : It will return the element which is present in particular index.
Slice() : It will give slice of an array and it will not affect the original array.
Splice() : It is used to add or remove elements from an array
Join() : It is used to join all elements of an array into a string.
Concat() : It is used to join/concat two or more arrays.
toString() : It converts all the elements in an array into a single string and returns
that string.
Reverse() : It is used to reverse an array.

JAVASCRIPT OBJECTS
JavaScript object is a non-primitive data-type that allows you to store
multiple collections of data.

The syntax to declare an object is:

const object_name = {
key1: value1,
key2: value2
}

Here, an object object_name is defined. Each member of an object is a key:


value pair separated by commas and enclosed in curly braces {} .

Example:
// object creation

const person = {

name: 'John',

age: 20

};
console.log (typeof person); // object

Accessing Object Properties

You can access the value of a property by using its key.


1. Using dot Notation

Here's the syntax of the dot notation.

objectname.key

Example:

const person = {

name: 'John',

age: 20,

};

// accessing property

console.log(person.name); // John
2. Using bracket Notation

Here is the syntax of the bracket notation.

objectName[“key”]

Example:
const person = {

name: 'John',

age: 20,

};

// accessing property

console.log(person["name"]); // John

JavaScript Nested Objects


An object can also contain another object. For example,

// nested object

const student = {

name: 'John',

age: 20,

marks: {

science: 70,

math: 75

// accessing property of student object

console.log(student.marks); // {science: 70, math: 75}

// accessing property of marks object

console.log(student.marks.science); // 70
Destructuring in js
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack
values from arrays, or properties from objects, into distinct variables.

Example: (Array Destructuring)


let arr = [10,20,30,40,50]
let [a,b,c,d,e] = arr //Destructuring
console.log(a);

let arr = [10,20,[1000,"hello",["hii",2000]]]


let [a,b,[c,d,[e,f]]] = arr //Destructuring
console.log(e);

Example: (Object Destructuring)


let obj={
ename:"Raj",
company:"Google",
sal:60000
}
let {ename,company,sal} = obj //Destructuring
console.log(ename);

let obj={
ename:"Raj",
company:"Google",
sal:60000,
games:{
outdoor:["cricket","volleyball","football"],
indoor:["ludo","chess"]
}
}
//Destructuring
let {ename,company,sal,games:{outdoor:[a,b,c],indoor:[x,y]}} = obj
console.log(ename);
console.log(a,x);

Advance array methods


Filter() :
filter() is a HOF which will check a particular condition for each
element in the original array. If the element satisfy the
condition the element will be pushed to the new array.
Syntax :
arr.filter((ele,index,arr)=>{
return condition
})
Example :
let numbers = [1, 2, 3, 4, 5];
let evenNo = numbers.filter((x) => x % 2 === 0);
console.log(evenNo); //[2, 4]
callback: This is the function that is used to test each element in the
array. It takes three arguments:
• element: The current element being processed in the
array.
• index (optional): The index of the current element being
processed.
• array (optional): The array filter was called upon.
Map() :
The map() method in JavaScript is used to create a new array by applying a
function to every element in an existing array. It does not modify the
original array. Instead, it returns a new array with the modified elements.
EX:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers. Map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

Reduce() : the reduce() is a HOF which will return a single value from the
original array. if no initial value is given, the accumulator will be assigned
with the first value of the array
SYNTAX:-
arr.reduce((acc,ele,index,arr)=>{
//statements
},init)

Example: -
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce(( accumulator,currentValue,index,arr) => {
console.log( accumulator, currentValue,index);
return accumulator+currentValue
},100);
console.log(sum);//115
Object: -
A JavaScript object is an entity having state and behavior (properties
and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.
JavaScript is an object-based language. Everything is an object in
JavaScript.
Creating Objects in JavaScript:
There are 2 ways to create objects.
1.By object literal.
2.By creating instance of Object directly (using new keyword).
1)JavaScript Object by object literal:
The syntax of creating object using object literal is given below:
VariableName object=
{
property1:value1,
property2:value2,
propertyN:valueN
}
As you can see, property and value is separated by : (colon).
Example of creating object in JavaScript.
<script>
Let emp={
id:102,
name:"Kumar", salary:40000
}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
2) By creating instance of Object:
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Example of creating object directly.
<script>
var emp=new Object(); emp.id=101; emp.name="Ravi";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
In JavaScript, to access and manipulate object properties: dot notation
Dot notation
Dot notation is the most common way to access object properties. It uses
a period (.) to access the value of a property by its key.
Here’s an example:
Const person = { name: 'John', age: 30, address: {
street: '123 Main St',
city: 'New York'
}
};
console.log(person.name); // John console.log(person.address.city); //
New York
OBJECT METHODS:
1.keys : It will return array of keys
2.Values : It will return array of values
3.Entries : It will return array of keys and values
Example:-
let obj4={
ename:"lavanya",
id:123,
sal:20000
};
let obj5={
ename1:"bujji", id1:12, sal1:40000
};
console.log(Object.keys(obj4));//array of keys
console.log(Object.values(obj4))//array of values
console.log(Object.entries(obj4))//array of keys and values
Loops in js
forEach - 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
forEach():-

The forEach() method calls a function for each element in an array.


The forEach() method is not executed for empty elements.

Example:
const array1 = ['a', 'b', 'c’];

array1.forEach((element) => console.log(element));

Output:- 1
2
3
4
5
For of loop:-
Iterable objects are objects that can be iterated over with for..of. <script>
Ex:-const name = "W3Schools";
let text = ""
for (const x of name){ text += x + "<br>";
}
For in loop:-
The JavaScript for in loop iterates over the keys of an object
Ex:-
const object = { a: 1, b: 2, c: 3 };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// Expected output:
// "a: 1“
// "b: 2“
// "c: 3“

“this” keyword
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:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

Example:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

this in a Method
When used in an object method, this refers to the object.

In the example on top of this page, this refers to the person object.

Because the fullName method is a method of the person object.

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

this Alone
When used alone, this refers to the global object.

Because this is running in the global scope.


In a browser window the global object is [object Window]:

Example
let x = this;

this in a Function
In a function, the global object is the default binding for this.

In a browser window the global object is [object Window]:

Example
function myFunction() {
return this;
}

DOM
In JavaScript, the DOM (Document Object Model) is a programming
interface for web documents. It represents the structure of a
document as a tree-like model where each node is an object
representing a part of the document, such as elements, attributes,
and text.
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:
DOM Methods: -
Methods used to target HTML elements in JavaScript file
document.getElementById(id): This method allows you to retrieve
an element from the document by its unique id.
document.getElementsByClassName(className): This method
returns a collection of all elements in the document with a specified
class name.it will return HTMLCollection which is an impure array.
No array methods will work on HTMLCollection
document.getElementsByTagName(tagName): Returns a collection
of elements with the specified tag name.
document.querySelector(selector): Returns the first element that
matches a specified CSS selector.
document.querySelectorAll(selector): Returns a NodeList of all
elements that match a specified CSS selector.
NOTE: difference between HTMLCollection and NodeList
NodeList and HTMLCollection both are impure array, but the
difference is we can apply forEach() in NodeList but we cannot apply
any of the array methods on HTMLCollection.
To check whether the array is pure or not we have a method called
Array.isArray(), if array is pure it will return true else false.
To convert impure array to pure array we have a method called
Array.from()
DOM EVENTS
 Event: An action performed by the user on the webpage is
known as an event
 A JavaScript can be executed when an event occurs, like when
a user clicks on an HTML element.
 onclick
 onmouseover
 onmouseout
 ondblclick
 onkeydown
 onkeyup

addEventListener

 The addEventListener() method attaches an event handler to


the specified element
 The first parameter is the type of the event (like "click" or
"mousedown" or any other HTML DOM Event.)
 The second parameter is the function we want to call when the
event occurs.
 Ex:
element.addEventListener("click", function(){
// codes
},use capture);

Event Propagation
 Event propagation refers to the way events travel through the
DOM tree. When an event occurs on an element, it can trigger
event handlers not only on that element but also on its parent
elements, all the way up to the root of the document. There
are two phases of event propagation:
1. Capturing Phase: The event travels from the root of the DOM
tree down to the target element.
2. Bubbling Phase: The event then bubbles up from the target
element back to the root.
 event.stopPropagation(): This method prevents further
propagation of the current event. It stops the event from
bubbling up the DOM tree or from capturing down the tree
 event.stopPropagation() in bubbling phase, it will block the
progation to reach to the outer most element from the
targetted element
 event.stopPropagation() in capturing phase, it will block the
propagation to reach to the targetted element
 event.stopImmediatePropagation() :- this method of the Event
interface prevents other listeners of the same event from being
called.
JAVASCRIPT OBJECT NOTATION (JSON)
 It is format of storing and transporting data.
 It is used when the data is sent form the server to web page
 It is a popular data format for developers because of its human
readable text, light weight which requires less coding and faster
process
Example: [
{“fname”:”Ram”,”lname”:”Patil”},
{“fname”:”Raj”,”lname”:”smith”},
{“fname”:”Ashish”,”lname”:”gouda”}
]
SYNTAX:
 Data is in Key value pairs
 Data is separated by ‘,’
 Curly braces holds objects
 [ ]---holds array
In JavaScript, there are two main methods used to work with JSON
(JavaScript Object Notation):
1.JSON.Stringify() : used to convert normal object to JSON format
2.JSON.parse(): Used to convert JSON format of data to normal
object
TIME DELAYS
 setTimeOut() and setInterval() are two functions in js allows to
schedule tasks to be executed at later time. Used for
animations, pulling data from server and other asynchronous
tasks.
 setTimeOut() :
 Runs the code with time delay
Syntax : setTimeOut( function , delay ) ;
• function: The function you want to execute.
• delay: The amount of time (in milliseconds) before the function
is executed
 setInterval() :
 The function similar to setTimeOut, but it schedules a function
to be executed repeatedly at specified interval.
Syntax : window.setInterval( function , delay ) ;
• function: The function you want to execute.
• delay: The amount of time (in milliseconds) before the function
is executed
 cancel a setTimeout, you use clearTimeout
Promises
 In JavaScript, promises are a mechanism for handling
asynchronous operations. They provide a way to work with
asynchronous code in a more structured and readable manner.
Promises represent a value that may not be available yet but
will be resolved at some point in the future, either successfully
with a result or with an error.
A promise represents the eventual result of an asynchronous
operation. It can be in one of three states:
• Pending: Initial state, neither fulfilled nor rejected.
• Fulfilled: Meaning the operation completed successfully.
• Rejected: Meaning the operation failed.
SYNTAX TO CREATE A PROMISE:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation, e.g., fetching data from a server.

if (/* operation successful */) {


resolve('Success data'); // Resolve if successful.
} else {
reject('Error message'); // Reject if there's an error.
}
});

CONSUMING A PROMISE:
 Then() : It will executed when the promise will be in resolved
state
 Catch() : It will get executed when the promise is in rejected
state
 Finally() : It will execute always means promise is in resolve ,
reject or in pending state

Fetch API
 * fetch() is used to send a request to backend, it accepts a
URL/API as an argument. This url should be in String
 * The fetch method returns a promise object, This object need
to be handled using then() and catch()
 * We need to first handle the response object and parse it to
get normal object using json()
 * In the next then method we will be able to consume the data
(using data from backed is called consuming data)
 EXAMPLE:-
fetch("https://api.github.com/users")
.then((response) => response.json())
.then((data) => {
console.log(data[0].login);
})
.catch((error) => {
console.log(error);
});

Async and await


 "async and await make promises easier to write"
 async makes a function return a Promise
 await makes a function wait for a Promise
 Async : The async keyword is used to define a function that
returns a promise. It allows you to write
 Await : The await keyword is used inside an async function to
wait for a Promise to settle (either resolve or reject). It can only
be used inside an async function

let fetchData = async function () {


let response = await fetch("https://api.github.com/users");
let data = await response.json();
console.log(data); // [{},{},{},{},……]
};
fetchData();

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

Adding and Deleting Elements


Method Description
document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

You might also like