JavaScript 1
JavaScript 1
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of nodes, where each
node corresponds to a part of the document (such as an element, attribute, or text). JavaScript can interact with the DOM to manipulate the content, structure,
and styling of a web page dynamically.
Event.preventdefault(): it is used to prevent the default behavior(page reloading, reflects the bahviour at the end point of the page link) of the buttons in DOM.
1. Selecting Elements:
o document.getElementById(id): Selects an element by its ID.
o document.getElementsByClassName(className): Selects elements by their class name.
o document.getElementsByTagName(tagName): Selects elements by their tag name.
o document.querySelector(selector): Selects the first element that matches a CSS selector.
o document.querySelectorAll(selector): Selects all elements that match a CSS selector. It provides a nodelist of elements.
2. Creating and Inserting Elements:
o document.createElement(tagName): Creates a new element. And then add it to the DOM as,
document.body.appendChild(element);
parentElement.appendChild(element);
name: The name of the attribute you want to set (e.g., "id", "class", "href").
value: The value you want to assign to that attribute.
Document Properties
Element Properties
Node Properties
Window Properties
window.innerWidth: Returns the inner width of the window's content area.
window.innerHeight: Returns the inner height of the window's content area.
window.outerWidth: Returns the outer width of the window (including the browser chrome).
window.outerHeight: Returns the outer height of the window (including the browser chrome).
window.location: Returns a Location object with information about the current URL.
window.history: Returns a History object with methods to interact with the browser's session history.
window.navigator: Returns a Navigator object with information about the browser.
HOISTING
Hoisting in JavaScript is a behavior in which variable and function declarations are moved, or "hoisted," to the top of their containing scope during the
compilation phase. This means that no matter where variables and functions are declared, they are moved to the top of their scope before code
execution.
With variables declared using var, the declaration is hoisted to the top, but the assignment remains in place . and during their hoisting they are
initialized to undefined.
For example:
in this the variable declared with var keyword is hoisted to the top but the assignment i.e, its assigned value (5) does not hoist to the top.
Function declarations are hoisted entirely, meaning both the function name and the body are moved to the top of their scope:
Arrow functions are not hoisted so they have to define first before calling them.
they must be called below their declaration otherwise they leads to an error.
However, function expressions (whether using var, let, or const) are not hoisted in the same way:
Variables declared with let and const are also hoisted, but they are not initialized. They are in a "temporal dead zone" from the start of the
block until the declaration is encountered, meaning they cannot be accessed before their declaration:
Trying to access a before its declaration results in a ReferenceError.
Declaration and initialization: Once let a = 5; is executed, a is no longer in the TDZ.
Anonymous Function: anonymous function are those functions which does not have a name. in this code both the functions are anonymous.
Parentheses: The function is wrapped inside parentheses to turn it into a function expression instead of a function declaration.
Invocation: The final set of parentheses () after the function expression immediately invokes the function.
Benefits of IIFE:
1. Avoids Global Scope Pollution: Variables defined inside an IIFE are not accessible outside its scope.
2. Private Variables: Helps in creating private variables and functions.
2-D array
They are essentially an array of arrays.
Creating a 2D Array
let array2D = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Accessing Elements
To access elements in a 2D array, you use two sets of square brackets. The first bracket refers to the row, and the second bracket refers to the column:
Modifying Elements
Both string index and elements index are accessible inside the array using their index values .
Note: the comma inside the string will also treated as an element so it also has an index and even the
white space does also have an index value inside a string.
Accessing element :
Find() method:
The find() method in JavaScript is used to search for the first element in an array that satisfies a provided testing function. It
returns the value of the first element that passes the test, or undefined if no elements pass the test.
callback(element, index, array): A function that tests each element of the array. It takes three arguments:
thisArg (optional): An object to use as this when executing the callback function.
1. Output of Computation: Functions are often used to perform calculations or process data. Returning a value allows you to use the result of
these operations elsewhere in your code.
2. Modularity and Reusability: Functions that return values can be more modular and reusable. They can be called from other parts of your
code and their results can be used or combined with other values.
3. Function Chaining: Returning a value, especially an object or a function, allows for method chaining. This is common in libraries like
jQuery or in custom implementations.
4. Testing and Debugging: Functions that return values are easier to test and debug because you can check their output directly.
5. Consistency: Even if you don’t need a return value in some cases, having a consistent return strategy helps in maintaining and understanding
code, especially in larger projects.
Slice() Splice()
Purpose: Creates a new array that is a shallow Purpose: Changes the contents of an array by
copy of a portion of the original array. removing, replacing, or adding elements.
Prototype chain
Prototype is used to create methods that are shared across all instances without them to recreate for every instances.
Prototype Chain:
The prototype is a mechanism for inheritance in JavaScript. When you try to access a property or method on an object, JavaScript first looks
at the object itself. If it doesn't find the property, it looks at the object's prototype, and then the prototype's prototype, and so on, until it
reaches null.
This chain of prototypes is called the prototype chain.
Basic Concept:
1) Prototype Property:
2) Prototype Chain: When you access a property or method on an object, JavaScript first looks at the object itself. If it doesn’t find it there, it looks up
the prototype chain.
3) Object.create: You can create objects with a specific prototype using Object.create(). This method creates a new object with the specified
prototype object.
Here, rabbit inherits from animal, so it has access to animal's eats property.
4) Modifying Prototypes: You can modify the prototype of a constructor function or an object directly.
In this example, a last method is added to Array.prototype, making it available to all array instances.
5) Prototype Inheritance with ES6 Classes: ES6 introduced classes, which are syntactic sugar over JavaScript’s prototype-based inheritance.
in this example, first a class is created with the name animals and then another class is created with the name dog which inherites the
properties and methods of animal class with the help of entends keyword.
In this example, Dog inherits from Animal, and the speak method is overridden.
__proto__
__proto__ allows you to directly access and modify the prototype of an object.
It is considered a legacy feature and should be avoided in modern js , instead Object.getPrototypeOf and Object.setPrototypeOf are more
prefered to use.
When you try to access rabbit.eats, JavaScript follows the prototype chain to animal and finds eats.
Object.getPrototypeOf:
Purpose: Object.getPrototypeOf is used to retrieve the prototype (i.e., the internal [[Prototype]] property) of a given object.
Syntax: Object.getPrototypeOf(obj)
obj: The object whose prototype you want to retrieve.
Returns: The prototype of the specified object, or null if there is no prototype.
In this example, dog is created with animal as its prototype using Object.create.
Purpose: Object.setPrototypeOf is used to set the prototype (i.e., the internal [[Prototype]] property) of a specified object.
Syntax: Object.setPrototypeOf(obj, prototype)
Parameters:
o obj: The object whose prototype you want to set.
o prototype: The object that should be the new prototype of obj, or null to remove the prototype.
Returns: The object obj with its prototype set to prototype.
Key Points
“null” will remove the prototype of obj (including the prototype which is automatically added by java script)
4. Performance Considerations:
While Object.setPrototypeOf is useful, setting prototypes dynamically can have performance implications. It's generally better to define
prototypes during object creation (e.g., using Object.create).
When you create a function and intend to use it as a constructor (with the new keyword), you can define properties and methods on the function's
prototype property. This method is used before the introduction of ES6 but now the class concept is used in place of this.
2. Object Prototype (Object.create Method)
You can create a new object with a specific prototype using Object.create. This allows you to define an object that serves as a prototype for other
objects.
With the introduction of ES6, JavaScript introduced the class syntax, which provides a more straightforward and familiar way to define prototypes
and create objects.
5. Using Object.setPrototypeOf
Constructor
a constructor is a special function used to create and initialize objects. When you define a class or a constructor function, it is invoked automatically when a new
instance of that class or function is created using the new keyword.
The constructor method in a JavaScript class is a special method used for creating and initializing an object instance of that class. It is typically used to
set up initial properties or perform setup tasks when an object is created.
Custom Setup Logic: If there is any custom logic that should run when an object is instantiated (e.g., setting default values, performing calculations), the
constructor is the ideal place for it.
Constructor in class can be omitted if not necessary and is useful for initializing values i.e, is added if necessary.
Instance.
An instance is a specific, concrete object created from a class or a constructor function in object-oriented programming. It represents a single, unique
occurrence of the object type defined by the class or constructor.
1. Unique Object:
o An instance is a unique object, with its own set of data (properties) and behaviors (methods). Even though multiple instances can be
created from the same class or constructor, each one is distinct and independent from the others.
2. Created from a Blueprint:
o A class or a constructor function serves as a blueprint that defines the structure and behavior of the objects. When you create an
instance, you're creating an object that follows this blueprint but can have its own unique values for properties.
o However, the class or constructor itself is not an object—it's just the template.
3. Independent State:
o Each instance has its own state, which means it stores its own data. Modifying the state of one instance does not affect the state of
another instance created from the same class or constructor.
Instance Creation:
When you create an instance, you are essentially creating a new object based on the class or constructor function.
This new object has its own set of properties and methods, which are defined by the class or constructor function.
Each instance can hold different data, even though they are created from the same blueprint.
All these three methods are used for same purpose. So you can use whatever option you want.
Classes
Class is a program-code template for creating an objects. Those object will have some state(variables) and behavior(function) inside it.
Classes provide a more intuitive and structured way to create objects and manage inheritance compared to the traditional
prototype-based approach.
A class is a blueprint for creating objects with specific properties and methods. Classes make it easier to structure and reuse
code, particularly when dealing with objects that share similar characteristics.
You define a class using the ‘class’ keyword. Inside a class, you can define a constructor (a special method for initializing
objects) and other methods.
Constructor method is called when a new object is created using the class. It is used to initialize the object's properties.
Methods can be defined inside a class. They are reusable functions that operate on the data contained in the object (class
instance).
A class can inherit properties and methods from another class using the extends keyword.
Static methods are methods that belong to the class itself rather than to any instance of the class i.e, these methods can directly be applied on
class but they can not be used with the instance objects.
You can define a static method in a class using the ‘static’ keyword before the method name.
In this example, if we does not use the super keyword inside the constructor of child class then it will throw an error. So it is necessary to use
the super() if we want to create an constructor in the child class. In other words the super() keyword will give access to the parent class
constructor as well as allows us to modify them or to add other properties to the child class constructor.
Super() with methods: You can use super.methodName() to call a method from the parent class.
Trying to create a method with the same name (as in the parent class) in the child class will overrides the parent class method . so that
‘super.sayHello()’ is used to call the parent class method in the child class method and to add soe more functionality to the method without
overriding the parent class method.
Passing arguments from a child class constructor to its parent class constructor:
4. Accessing Parent Class Properties: If you need to access a property or method from the parent class within a method of the
child class, super.propertyName or super.methodName() is required.
Note: if the constructor of child class and parent class have dissimilar parameters then, it is necessary for the child element
to take the parent class parameter and then pass it to the parent class using ‘super(parameterTo Pass)’ or set a default
default value for that parameter.
Child class constructor taking the parameters for it’s parent class constructor and then passing the parameter to the
parent class constructor (‘super(name)’) is already discussed above.
Here’s an example of setting a default value for the parent class constructor parameter.
Callback hell
"Callback hell" in JavaScript refers to a situation where multiple asynchronous operations are nested within each other using callbacks, leading to
deeply nested code that is difficult to read and maintain. This typically happens when you're dealing with asynchronous tasks like file reading, API
calls, or timers, where each task depends on the completion of the previous one.
This will creates an pyramid structure called pyramid of doom.
Async/Await: Introduced in ES2017, async/await allows you to write asynchronous code in a synchronous-like
manner, making it even easier to read.
Modularizing the code: Breaking down the callbacks into smaller, named functions instead of using anonymous
functions can also help reduce the complexity.
In general programming we will not creates a promise instead when we sent a request to an API then this API sent back a promise in response of our
request and we will then have to handle this promise.
States of promises:
Pending: it is the initial state. The operation is ongoing, and the promise's result is not yet available.
Fulfilled: it is the state at which operation completed successfully, and the promise has a result value.
Rejected: it is the state at which the operation failed, and the promise has a reason for the failure.
Constructor: The ‘Promise’ constructor is used to create a new promise. It takes a function called the executor, which has two parameters: ‘ resolve’ and
‘reject’.
The ‘resolve’ and ‘reject’ are the functions created by the javascript internally .
Chaining: Promises can be chained using .then() and .catch(), allowing for sequential asynchronous operations. It is necessary to execute the
promises in an synchronous way.
First the promise data1 is fetched .
Once the data1 is resolved then it will
return the data2 promise i.e, data2 will
starts fetching.
Once the data2 is resolved then it will
return the data3 promise i.e, data3 will
starts fetching.
Once the data3 is resolved then the res is
loged to the console.
It is the simple way of handling promises
in an synchronous way then the method
given below.
It is more readable to the one given
below.
If the promises are not chained then we can not fetch them in synchronous manner. i.e,
Output:
Console.log(“fetching data 1”); Fetching data 1
Fetching data 2
P1.then( ()=>{console.log(“ data 1 fetched successfully”)} ); Data 1 fetched successfully
Data 2 fetched successfully
Console.log(“fetching data 2”);
i.e, in this way both the promises are fetched
P2.then( ()=>{console.log(“data 2 fetched successfully”)} ); asynchronously.
setInterval: it is an asynchronous function used to execute a code again and again after the given time delay.
The use of the clearInterval(function , delay time) will not stops the interval function after the provided delay time instead it imidiatly stops the
interval function. Hence to stop the interval function after a provide time delay ,the clearInterval function must be used with settimeout function or in
the conditional statement.
Asyn / await
async and await are used to handle asynchronous operations more easily and make code look more readable, especially when dealing with promises.
They allow you to write asynchronous code in a synchronous-looking manner, avoiding the need for complex .then() chains.
An async function always returns a promise automatically. Inside an async function, you can use await to wait for a promise to resolve.
How async and await work:
1. async keyword:
o You use the async keyword before a function declaration to indicate that the function is asynchronous. It will always return a promise,
even if the function doesn't explicitly return one.
o Inside an async function, you can use the await keyword.
2. await keyword:
o The await keyword can only be used inside an async function.
o It pauses the execution of the async function until the promise is resolved or rejected, and then returns the result of the promise.
o If the promise is rejected, await will throw the error, so you can handle it using try/catch.
o When you use await in JavaScript, it only pauses the execution of the async function that contains it, not the entire program. Other code
outside the async function, or even synchronous code within the async function itself (before the await keyword), will continue to execute
normally.
Parallel Execution: If you need to run multiple asynchronous tasks in parallel, you can use Promise.all() or run them without ‘awaiting’ right
away.
Mostly the API’s follow the convention of using lowercase letters with hyphens to separate words in endpoint URLs. This is because URLs are case-insensitive and
using lowercase makes them easier to read and maintain.
REST API: A REST API (Representational State Transfer API) is a way for two systems (like a client and a server) to communicate over the
web using standard HTTP methods. It follows the principles of REST architecture, where resources (data) are accessed using URLs, and HTTP
methods define the operations to perform on those resources.
1. Resources: Everything in a REST API is a resource, and resources are represented by URLs. For example:
o https://api.example.com/users could represent a collection of users.
o https://api.example.com/users/1 could represent a specific user with the ID 1.
2. HTTP Methods: REST APIs use standard HTTP methods to perform operations on resources these methods are called http verbs:
o GET: Retrieve data (read). Or get the data from the server. When no option is passed to the fetch API then is bydefault using the GET
option
o POST: Create new data (write).
o PUT: Update existing data (replace).
o PATCH: Partially update data.
o DELETE: Remove data.
3. Stateless: Each request from the client to the server must contain all the information needed to process the request. The server does not store
the client state between requests.
4. JSON or XML: REST APIs often return data in JSON (JavaScript Object Notation) or XML format, though JSON is the most popular due to
its simplicity and readability.
Key Characteristics:
Scalability: REST APIs can scale easily, allowing multiple systems or applications to communicate with the server simultaneously.
Stateless: Every request is independent, meaning the server doesn’t retain any information from previous requests.
Layered System: REST APIs can be built with multiple layers like security, caching, etc., without affecting the client-server communication.
When to Use REST APIs:
When building web services that need to be consumed by web apps, mobile apps, or other services.
When you want a flexible, scalable, and stateless system.
REST APIs are widely used and form the backbone of modern web services.
Fetch API: The fetch API is a modern JavaScript interface used for making network requests, typically HTTP requests, such as GET, POST, PUT, and
DELETE. It is a cleaner and more flexible alternative to the older XMLHttpRequest API and allows you to work with promises to handle asynchronous requests.
The fetch api provides an interface for fetching (sending / receiving ) resources.
Syntax:
These are the most common APIs, used for communication between web servers and clients (browsers, apps, etc.) over the internet using
HTTP/HTTPS. They are designed to expose web services or data to other systems.
REST (Representational State Transfer): A widely used architectural style for building APIs that use HTTP requests for CRUD (Create, Read, Update,
Delete) operations.
o Example: Twitter API, GitHub API
SOAP (Simple Object Access Protocol): An older protocol, often used in enterprise environments, that uses XML to send messages over HTTP, SMTP, and
other protocols.
o Example: PayPal API, Microsoft Azure API
GraphQL: A query language for APIs that allows clients to request specific data from the server. It provides more flexibility compared to REST.
o Example: GitHub GraphQL API
gRPC: A high-performance, open-source RPC (Remote Procedure Call) framework used in distributed systems for efficient communication between
services.
o Example: Google APIs
2. Operating System APIs
These APIs are provided by an operating system (OS) to allow interaction with its functions, such as file management, memory allocation, hardware
access, etc.
These APIs are used within software libraries or frameworks, enabling developers to utilize predefined functions or objects.
jQuery API: JavaScript library providing an API for handling HTML documents, event handling, and animation.
Django API: A Python web framework API for building web applications.
4. Hardware APIs
These APIs provide an interface for software to interact with hardware devices like printers, cameras, or storage devices.
OpenGL (Open Graphics Library): An API used for rendering 2D and 3D vector graphics.
DirectX API: A collection of APIs for handling multimedia, especially game programming and video, on Microsoft platforms.
5. Database APIs
These APIs are used to communicate with databases and manipulate data stored in them.
JDBC (Java Database Connectivity): An API that enables Java applications to interact with databases.
ODBC (Open Database Connectivity): A standard API used to access database management systems (DBMS).
MongoDB API: Allows applications to interact with MongoDB databases.
6. Remote APIs
Remote APIs allow systems or services that are located on different machines to communicate over a network. They are usually web-based but not
always.
AWS API: Used to interact with Amazon Web Services for cloud computing and storage.
Twilio API: Allows interaction with telecommunication services like SMS, calls, etc.
7. Open APIs (Public APIs)
Open APIs are publicly available to developers and other users, typically with minimal restrictions. They are often designed to encourage external
developers to build applications on top of the service they provide.
Facebook API: Allows access to Facebook's social graph and related services.
Google Maps API: Allows developers to integrate Google Maps services into their applications.
8. Partner APIs
Partner APIs are exposed to specific developers or business partners, usually under strict control and agreements. They are not publicly accessible but
used to integrate services between businesses.
eBay Partner API: Allows partners to access eBay’s product and transaction data.
Shopify Partner API: Provides partners with access to Shopify’s merchant data.
These APIs are intended for internal use within a company or organization. They are used to integrate internal systems or services and are not
exposed to external users.
Internal Services API: Used within a company to enable communication between different services, such as inventory management and
accounting systems.
Composite APIs combine multiple service or data API calls into a single request. These are useful when you need to access multiple resources in one
API call, which can improve performance by reducing the number of requests.
Example: A composite API might retrieve customer data and order history in a single call.
WebSocket APIs allow for two-way communication between the client and server. Unlike REST APIs, which follow a request-response model,
WebSocket APIs can send and receive messages asynchronously, making them ideal for real-time applications like chat apps or live data streaming.
Summary:
Each type of API serves a different purpose and helps in achieving different communication goals, depending on the architecture and requirements of
the system.
1. Asynchronous: The page doesn't reload when data is fetched, resulting in a smoother user experience.
2. Faster: Only specific parts of a page are updated, reducing server load and improving performance.
3. Dynamic: AJAX allows you to interact with the server without reloading the page, enabling dynamic and real-time updates.
Disadvantages of AJAX:
AJAJ: (Asynchronous JavaScript and JSON) is a variation of the traditional AJAX (Asynchronous JavaScript and XML) approach, where JSON
is used instead of XML for data transmission between the client and the server.
JSON: JSON (JavaScript Object Notation) is a lightweight data format commonly used for transferring data between a server and a web
application. JSON is easy to read and write for humans and easy for machines to parse and generate. It is essentially a string representation of a
JavaScript object i.e, JSON string.
JSON Syntax:
For example, while JSON requires keys to be strings, in JavaScript objects, keys can be unquoted if they follow identifier naming rules.
Rules of JSON:
1. Data Must Be a String: JSON is always represented as a string. If you're transmitting JSON, it needs to be serialized into a string using
JSON.stringify().
2. No Functions: JSON cannot contain functions or undefined values, as it's a data format meant for storage or transmission.
3. Double Quotes: All keys and string values in JSON must be enclosed in double quotes ("), unlike JavaScript objects, which can use single or
double quotes for strings and unquoted keys.
json() method: The json() method in JavaScript is used to parse a response body as JSON. It is most commonly used with the Fetch API to handle the
response from a network request. When you fetch data from an API, the response is typically in a format like JSON, and the json() method extracts the JSON
data from the response stream and returns a JavaScript object.
The json() method is a promise-based function that reads the body of the response stream and parses it as JSON.
It returns a promise that resolves with a JavaScript object (or array) parsed from the JSON data.
Asynchronous: The json() method is part of the Fetch API's promise chain, making it asynchronous and non-blocking.
Using async-await with json():
‘event.clientX’ and ‘event.clintY’ are used to track the horizontal and vertical position of the mouse.
An ‘mousemove’ event listener is added to update the mouse position every time when it moves.
Note that the tracker element in html must have fixed position in the window so that it remain in the window throughout the site.