Java Script
Java Script
Que What will happed if we create a variable without using “let”, “var” or “const”
Ans Will be treated like a global variable
Example:-
let a = 10;
let b = 20;
[Link](`The sum of ${a} and ${b} is ${a + b}.`);
In JavaScript, the || operator (logical OR) evaluates operands from left to right and returns
the first truthy value it encounters. If no true values are there, it returns the last value.
Que An object is declared using const keyword. Can we change the properties of that object?
Ans Yes we can because we are changing the properties not that object. Basically const stops
from redeclaration.
freeze():-
This method also prevents any deletion or insertion of a key-value pair if used with an
object. But you cannot change the existing properties.
Que How can we check whether a given key is present in the object or not?
Ans We can do it by using “in” keyword.
For example [Link](key in obj);
It will result true if the ley is present otherwise false.
Splice:-
It is the same as slice but it modifies the original array also.
This behaviour happens with all reference types in JavaScript, such as arrays and objects.
For these types, variables hold references to the memory location where the data is stored,
rather than the data itself. Therefore, when you assign one variable to another, both
variables point to the same data, and changes made through one variable are reflected in the
other.
Deep copy:-
Creates a fully independent copy of the original structure, including nested objects. Suitable
for complex or deeply nested data structures.
When a reference type (e.g., object, array, function) is passed as an argument to a function,
a reference to the object is passed. This means that changes made to the object's properties
inside the function do affect the original object.
Example:-
function a(b){
b();
}
a(function(){
[Link]("i am an anonymous function")
});
Example:
function greet(name, callback) {
[Link]('Hello, ' + name + '!');
callback();
}
function sayGoodbye() {
[Link]('Goodbye!');
}
greet('Alice', sayGoodbye);
If you simply pass a js code in form of string it will execute that code, For example
setTimeout(‘[Link](“Hi”)’);
The setTimeout returns a unique identifier for the timeout and you can pass that id to
cleartime out function to stop its running
Exapmle:-
const timeoutID = setTimeout(() => {
[Link]('This will not be printed');
}, 5000);
clearTimeout(timeoutID);
You can cancel an interval using the clearInterval function if you need to stop the repeated
execution
Example:
const intervalID = setInterval(() => {
[Link]('This will be printed every second until cleared');
}, 1000);
setTimeout(() => {
clearInterval(intervalID);
[Link]('Interval cleared');
}, 5000);
Example:
[Link]('Start');
[Link]('Middle');
[Link]('End');
Output:-
Start
Middle
End
Asynchronous Programming:
Asynchronous programming, on the other hand, allows for tasks to be initiated and then run
in the background, letting other code execute without waiting for those tasks to complete.
This is achieved using callbacks, promises, and async/await syntax.
Example:
[Link]('Start');
setTimeout(() => {
[Link]('Timeout Callback');
}, 0);
[Link]('End');
Output:-
Start
End
Timeout Callback
Call Stack: JavaScript has a call stack where function calls are added and executed in a
Last In, First Out (LIFO) order. When a function is called, it’s pushed onto the call stack,
and when the function returns, it’s popped off the stack.
Web APIs (or Node APIs): When asynchronous operations (like setTimeout, fetch, or I/O
operations in [Link]) are invoked, they are offloaded to the Web APIs or Node APIs,
which handle these operations separately from the call stack.
Callback Queue (or Task Queue): Once the asynchronous operation is completed, the
corresponding callback function is placed in the callback queue. This queue follows a First
In, First Out (FIFO) order.
Event Loop: The event loop continuously monitors the call stack and the callback queue. If
the call stack is empty, the event loop picks the first callback from the callback queue and
pushes it onto the call stack for execution. This ensures that asynchronous operations are
processed without blocking the main thread.
CALLBACK QUEUE:
The callback queue is where callback functions from completed asynchronous operations
are placed, waiting to be executed.
Que Explain Asynchronous code and synchronous code in js in short.
Ans Asynchronous code:
Jo code directly run na hoke web APIs ke section chala jata hai waha se fir callback queue
me jata aur fir jab call stack empty ho jata hai tab event loop usko call stack me execute
hone ke liye bhejta hai.
Wo code Web APIs ke section me isliye jata hai kyoki utne code ko thoda time chaiye aur
utne time ke liye ham baki ka synchronous code to rokna nahi chahenge.
Synchronous code:
Wo code jo line by line execute hota hai with corresponding output.
EXAMPLE:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
[Link]('Outer Variable: ' + outerVariable);
[Link]('Inner Variable: ' + innerVariable);
}
}
const newFunction = outerFunction('outside');
newFunction('inside');
Example:
const obj={
a:function f(){
[Link](“HI”);
}
}
obj.a;
Que What are different ways to make a function?
Ans There are following ways:
FUNCTION DECLARATION:
In this method we declare a function, for example
function f(){
[Link](“hi”);
}
FUCNTION EXPRESSION:
const a=function(){
[Link](“hi”);
};
NOTE:- for arrow function, Agar ek hi parameter hai to () nab hi lagao to chalega aur
agar function ki body me ek hi line of code hai to {} na lagao to bhi chalega
function strictFunction() {
"use strict";
// This function is in strict mode
let y = 20;
[Link](y); // Outputs: 20
}
Que Explain for…of and for…in loops
Ans for…of loop is used to iterate over iterable objects like arrays, strings, maps, sets, etc
Syntax:
for (const element of iterable) {
// Code to be executed for each element
}
const a = [1,2,3,4,5];
[Link]((x)=>{
[Link](x);
})
OR
[Link](function(x){
[Link](x);
})
Example:
const numbers = [1, 2, 3, 4, 5];
const doubled = [Link](number => number * 2);
[Link](doubled); // Output: [2, 4, 6, 8, 10]
OR
const numbers = [1, 2, 3, 4, 5];
const doubled = [Link](function(number) {
return number * 2;
});
[Link](doubled); // Output: [2, 4, 6, 8, 10]
Example:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = [Link](function(number) {
return number % 2 === 0;
});
[Link](evenNumbers); // Output: [2, 4, 6, 8, 10]
SOME:
The some method tests whether at least one element in the array passes the condition
implemented by the provided function. If any element meets the condition, some returns
true; otherwise, it returns false.
Syntax: [Link](function(element, index, array), thisArg)
EXAMPLE:
const numbers = [1, 2, 3, 4, 5];
const allPositive = [Link](function(number) {
return number > 0;
});
[Link](allPositive); // Output: true
inside a function, arguments is an array-like object that provides access to all arguments
passed to the function. It includes not only the explicitly defined parameters but also any
additional arguments passed during the function call.
function sum() {
let total = 0;
for (let i = 0; i < [Link]; i++) {
total += arguments[i];
}
return total;
}
[Link](sum(1, 2, 3)); // Output: 6
Copying Arrays
You can use the spread operator to create a shallow copy of an array. This is useful when
you want to manipulate an array without modifying the original.
javascript
Copy code
const original = [1, 2, 3];
const copy = [...original];
[Link](copy); // Output: [1, 2, 3]
Concatenating Arrays
The spread operator can concatenate arrays easily. It allows you to combine multiple arrays
into a single array.
javascript
Copy code
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
When calling functions, the spread operator can be used to pass an array of arguments as
individual arguments to the function.
javascript
Copy code
function sum(a, b, c) {
return a + b + c;
}
Creating Arrays
You can use the spread operator to insert elements into arrays, either at the beginning or in
the middle.
javascript
Copy code
const arr1 = [1, 2, 3];
const arr2 = [0, ...arr1, 4, 5];
Objects
While primarily used with arrays, the spread syntax can also be used with objects, allowing
shallow copying or merging of object properties.
javascript
Copy code
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
[Link](obj2); // Output: { a: 1, b: 2, c: 3 }
Considerations
● Shallow Copy: The spread operator performs a shallow copy. If the array or object
contains nested arrays or objects, those nested structures are still referenced rather
than copied deeply.
● Iterables: The spread operator works with any iterable, such as arrays, strings, and
array-like objects (like arguments).
● Browser Support: The spread operator is widely supported in modern JavaScript
environments but may require transpilation for compatibility with older browsers.
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<head>
<html> <title>innerHTML
<head> Example</title>
<title>innerHTML </head>
Example</title> <body>
</head> <div id="myDiv">Hello,
<body> world!</div>
<button
<div id="myDiv">Hello, onclick="changeContent()">Change
world!</div> Content</button>
<script>
<script> function changeContent() {
var element = var element =
[Link]("myDiv" [Link]("myDiv"
); );
[Link] = "New
[Link]([Link]); content!";
}
// Outputs: Hello, world! </script>
</body>
</script> </html>
</body>
Que What is the difference between innerText and textContent
</html>
Ans
innerText
● textContent
Example:
// Assume there's an element <div id="myDiv"></div>
var myDiv = [Link]('myDiv');
getAttribute():
The getAttribute method is used to get the value of a specified attribute from an element. If
the attribute does not exist, it returns null or an empty string (depending on the attribute).
Example:
// Assume there's an element <div id="myDiv" class="myClass"></div>
var myDiv = [Link]('myDiv');
Example:
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
Here, the <div id="parent"> element is the parent of both <div id="child1"> and <div
id="child2">.
Child Element:
A child element is an element that is contained within another element (called the parent
element). In the DOM tree, the child element is one level below its parent element.
Example:
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
Here, <div id="child1"> and <div id="child2"> are child elements of the <div id="parent">
element.
Sibling element:
Sibling elements are elements that share the same parent element. In the DOM tree, sibling
elements are on the same level.
Example:
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
Here, <div id="child1"> and <div id="child2"> are sibling elements because they share the
same parent element (<div id="parent">).
Que What are the differences between a node and element in js DOM?
Ans In the context of the JavaScript Document Object Model (DOM), the terms "element" and
"node" have specific meanings:
Node:
A node is the basic building block of the DOM. It represents any single point in the
document tree. The DOM API provides the `Node` interface, which is the primary data
type for the entire Document Object Model.
● Types: There are several types of nodes, including:
● Element nodes: Represent elements (e.g., `<div>`, `<span>`).
● Text nodes: Represent the text content within elements.
● Comment nodes: Represent comments in the HTML.
● Document nodes: Represent the entire document (the root of the DOM tree).
● DocumentFragment nodes: Represent a minimal document object that has no
parent.
● Attribute nodes: Represent attributes of elements (though in modern DOM,
attributes are usually accessed directly via elements).
Element
An element is a specific type of node. Elements are the most common type of nodes, and
they represent the HTML elements in the document. The DOM API provides the `Element`
interface, which extends the `Node` interface.
Key Differences
1. Inheritance:
All elements are nodes, but not all nodes are elements. The `Element` interface inherits
from the `Node` interface, meaning elements have all the properties and methods of nodes,
plus additional ones specific to elements.
2. Specificity:
Nodes can be of various types, while elements specifically refer to HTML elements.
In summary, while nodes form the general structure of the DOM, elements are a specific
type of node that represent HTML tags and come with additional properties and methods
tailored for handling HTML elements.
Example:
append:
more flexible method that can add multiple nodes and/or strings to the end of the list of
children of a specified parent node
Syntax: [Link](...nodesOrDOMStrings)
Parameters:
Example:
// Create new elements
var newDiv = [Link]("div");
var newSpan = [Link]("span");
Example:
//HTML
<button id="myButton">Click Me</button>
//JAVASCRIPT
[Link]('myButton').addEventListener('click', function() {
alert('Button was clicked!');
});
Common Events
● click: Occurs when an element is clicked.
● mouseover: Occurs when the mouse pointer moves over an element.
● mouseout: Occurs when the mouse pointer moves away from an element.
● keydown: Occurs when a key is pressed down.
● keyup: Occurs when a key is released.
● load: Occurs when the page has finished loading.
● submit: Occurs when a form is submitted.
● change: Occurs when the value of an element changes (e.g., a select box).
● dblclick: Occurs when an element is double clicked.
● Input: Occurs when input is given
Ans
hi2
hi3
hi4
Aisa isliye kyoki jab direct onclick lagate jaoge to vo agla wala onclick usko overwrite kar
degas to sirf h1 aaya.
But, addEventListener se click event lagaoge to sare chalenge koi kisi ko overwrite nhi
karega
Que The default behaviour of a form is to redirect when submit is clicked. How can we stop this
default behaviour?
Ans By default, when a form is submitted, the browser sends the form data to the specified
action attribute in the form tag. This often leads to a page reload. To prevent this default
reload behavior, we can use JavaScript. submit karne pe ek submit event fire hota hai isliye
Example:-
HTML
<form id="myForm">
<button type="submit">Submit</button>
//note agar type submit hoga to hi form submit hoga
</form>
});
JAVASCRIPT
const form = [Link]('myForm');
[Link]('submit', (event) => {
[Link]();
// Perform custom actions here
[Link]('Form submitted without reloading the page');
});
keydown: This event is fired when a key is pressed down. It continues to fire as long as the
key is held down, making it useful for detecting continuous key presses.
keypress: This event is fired when a key that produces a character value is pressed down. It
is similar to the keydown event but is specific to keys that produce a character (e.g., letters,
numbers). Note that this event has been deprecated and should be avoided in modern web
development.
keyup: This event is fired when a key is released. It is useful for detecting when the user
stops pressing a key.
● mousedown: Triggered when the user presses a mouse button down over an
element. This event is useful for starting actions when the mouse button is pressed,
such as dragging.
● mouseup: Triggered when the user releases a mouse button over an element. It is
used in conjunction with mousedown to complete actions like dragging.
● mouseover: Triggered when the mouse pointer enters the area of an element. It is
often used to display tooltips or highlight elements when hovered over.
● mouseout: Triggered when the mouse pointer leaves the area of an element. It is
used to remove tooltips or revert highlighting when the pointer moves away.
● mousemove: Triggered when the mouse pointer moves over an element. It is useful
for tracking the position of the mouse or creating interactive features like drawing
on a canvas.
● contextmenu: Triggered when the user right-clicks on an element, typically used
to display a custom context menu.
● wheel: event in JavaScript is triggered when the user rotates the scroll wheel on
their mouse, or performs a similar gesture on a touchpad. It allows developers to
handle scrolling actions, such as zooming or panning content, or implementing
custom scrolling behavior.
Que If we want ki kisi element pe event lagaye aur vo event bas ek baar chale then how to do it?
Ans In the third parameter of the addEventListener pass {once:true} object.
Example:
[Link]('click', () => {
alert('Button clicked once!'); },
{ once: true });
Array Destructuring
Array destructuring allows you to unpack values from arrays and assign them to variables
in a single statement.
**Basic Example:**
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
[Link](a); // 1
[Link](b); // 2
[Link](c); // 3
**Skipping Elements:**
You can skip elements in the array by using commas.
**Default Values:**
You can assign default values to variables if the unpacked value is `undefined`.
[Link](a); // 1
[Link](b); // 2
**Rest Operator:**
The rest operator (`...`) can be used to assign remaining elements to a single variable.
javascript
const numbers = [1, 2, 3, 4];
const [a, ...rest] = numbers;
[Link](a); // 1
[Link](rest); // [2, 3, 4]
Object Destructuring
Object destructuring allows you to unpack properties from objects into distinct variables.
**Basic Example:**
const person = {
name: 'Alice',
age: 25
};
[Link](name); // Alice
[Link](age); // 25
**Renaming Variables:**
You can rename variables while destructuring.
const person = {
name: 'Alice',
age: 25
};
[Link](personName); // Alice
[Link](personAge); // 25
**Default Values:**
You can assign default values if the property is `undefined`.
const person = {
name: 'Alice'
};
[Link](name); // Alice
[Link](age); // 30
**Nested Destructuring:**
You can destructure nested objects.
const person = {
name: 'Alice',
address: {
city: 'Wonderland',
zip: '12345'
}
};
[Link](name); // Alice
[Link](city); // Wonderland
[Link](zip); // 12345
**Rest Properties:**
The rest operator (`...`) can be used to collect the remaining properties.
const person = {
name: 'Alice',
age: 25,
job: 'Engineer'
};
const { name, ...rest } = person;
[Link](name); // Alice
[Link](rest); // { age: 25, job: 'Engineer' }
Destructuring is a powerful feature in JavaScript that enhances code readability and reduces
the need for repetitive code when working with arrays and objects.
Example
States of a Promise:
● Pending: The initial state. The operation is still ongoing, and the result is not yet
available.
● Fulfilled: The operation completed successfully, and the promise has a resulting
value.
● Rejected: The operation failed, and the promise has a reason for the failure.
Handling a Promise:
Once a promise is created, you can handle its outcome using the .then() and .catch()
methods:
● then(): This is used to handle the fulfilled case. It takes a function that will be
called with the result when the promise is resolved.
● catch(): This is used to handle the rejected case. It takes a function that will be
called with the reason when the promise is rejected.
Example:
const d = 21;
const p = new Promise((resolve, reject) => {
if (d == 21) {
OUTPUT:
resolve("Promise resolved");
} Promise Resolved
else {
reject("Promise rejected");
}
})
[Link]((resolution) => {
[Link](resolution);
}).catch((rejection) => {
[Link](rejection)
})
[Link]("start");
const d = 22;
const p = new Promise((resolve, reject) => {
if (d == 21) {
resolve("Promise resolved");
}
else {
reject("Promise rejected");
}
})
[Link]((resolution) => {
[Link](resolution);
}).catch((rejection) => {
[Link](rejection)
})
[Link]("end");
Ans start
end
Promise rejected
Because promises are asynchronous and they will be executed after execution of
synchronous code
[Link]("start");
const d = 22;
const p = new Promise((resolve, reject) => {
if (d == 21) {
resolve("Promise resolved");
}
else {
reject("Promise rejected");
}
})
[Link]((resolution) => {
[Link](resolution);
}).catch((rejection) => {
[Link](rejection)
})
setTimeout(()=>{
[Link]("Inside setTimeOut");
},0);
[Link]("end");
Ans start
end
Promise rejected
Inside setTimeOut
Here both promise and setTimout will be handled by the browser but setTimeout will be
kept in call back queue while promises will be kept in microtask queue and microtask
queue wale callback queue walo se pehle execute hone ke liye call stack me jaenge.
Que Show an example of callback hell getting fixed with the help of promises
Ans
suppose in this html file we wanna change the colors of all headings in gap of one second,
then this can be done in two ways.
The first way is to use nested callback and setTimeout which will cause a callback hell and
the second way is to fix that callback hell using promises
The next two pages show a callback hell and a method to fix this callback hell using
promises
In an convenient manner.
Callback hell
Fixed using promises
Que What does then and catch method of a promise return ?
Ans A promise
Example
fetch('[Link]
.then(response => {
if (![Link]) {
throw new Error('Network response was not ok');
}
return [Link](); // Parse the response as JSON
})
.then(data => {
[Link](data); // Handle the data from the server
})
.catch(error => {
[Link]('There was a problem with the fetch operation:', error);
});
Key Points:
● URL: The first parameter of fetch() is the URL you want to request.
● Response Handling: The response object has various methods like .json(), .text(),
etc., to parse the response body.
● Error Handling: If the request fails (e.g., network issues or a bad response status),
it can be caught using the .catch() method.
● Asynchronous: fetch is non-blocking, meaning it doesn't pause the execution of
the script while waiting for the server's response.
fetch('[Link] {
method: 'POST', // Specify the HTTP method as POST
headers: {
'Content-Type': 'application/json', // Set the content type to JSON
},
body: [Link]({
key1: 'value1', // Data you want to send to the server
key2: 'value2',
}),
})
.then(response => {
if (![Link]) { // Check if the response status is OK (200-299)
throw new Error('Network response was not ok');
}
return [Link](); // Parse the JSON from the response
})
.then(data => {
[Link]('Success:', data); // Handle the successful response data
})
.catch(error => {
[Link]('Error:', error); // Handle any errors that occurred during the fetch
});
Key Features:
1. Persistence: Data stored in local storage is persistent and remains even after the
browser is closed and reopened. It doesn't expire unless explicitly cleared by the
user or the application.
2. Capacity: Local storage has a capacity limit, which is usually around 5-10 MB per
origin (i.e., per domain). This is much larger than cookies, but still limited.
3. Key-Value Storage: Data in local storage is stored as strings in key-value pairs.
The keys and values are both strings, though you can store more complex data by
serializing it into a JSON string.
Basic Operations:
Setting Data:
[Link]('key', 'value');
Getting Data:
let value = [Link]('key');
Removing Data:
[Link]('key');