0% found this document useful (0 votes)
2 views39 pages

Java Script

The document provides a comprehensive overview of JavaScript concepts including data types, variable declarations, functions, asynchronous programming, and object manipulation. It explains various JavaScript features such as the use of 'let', 'var', 'const', the 'defer' keyword, dialog boxes, higher-order functions, and the event loop. Additionally, it covers methods for arrays and objects, including manipulation techniques and differences between shallow and deep copies.

Uploaded by

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

Java Script

The document provides a comprehensive overview of JavaScript concepts including data types, variable declarations, functions, asynchronous programming, and object manipulation. It explains various JavaScript features such as the use of 'let', 'var', 'const', the 'defer' keyword, dialog boxes, higher-order functions, and the event loop. Additionally, it covers methods for arrays and objects, including manipulation techniques and differences between shallow and deep copies.

Uploaded by

Voku
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Que.

What will be the output of


string s = ”100”;
[Link](typeof +s);
Ans number.
because when we use a plus operator with small numeric strings, they get converted to
numbers.

Que. What will be the output of


string s = “100”;
[Link](typeof -s);
[Link](-s);
Ans number
-100

Que Differentiate between “let”, “var” and “const”


Ans “let” and “const” “var”
Variables are block scoped Variables are function scoped
If we access a variable before its declaration If we access a variable before its declaration
we get “not defined” we get error that “cannot access before
initialization”

Que What will happed if we create a variable without using “let”, “var” or “const”
Ans Will be treated like a global variable

Que Explain the use of “defer” keyword


Ans It is used in the script tag
<script src = “[Link]” defer>
Ye karta ye hai ki jab tak browser ka html parser pure html file ko parse na kar le tab tak
javascript file execute nahi hogi

Que Explain “debugger” keyword


Ans The “debugger” keyword in JavaScript is used to invoke a breakpoint in the code. When
the JavaScript engine encounters this keyword and if developer tools are open in the web
browser, the execution of the script will pause at the line where debugger is called. This
allows developers to inspect the current state of the program, including variables, the call
stack, and the execution context, to help with debugging.

Que Explain “Temporal Dead Zone”


Ans The Temporal Dead Zone (TDZ) in JavaScript refers to the time span between the entering
of a scope (such as a block or a function) and the point at which a variable declared with let
or const is initialized. During this period, accessing the variable results in a ReferenceError.
Understanding TDZ is crucial for grasping the behavior of let and const compared to var.
Que Explain dialoge boxes
Ans ALERT : alert(“Message”)
it shows a message on the browser with an OK button the result of the expression is
undefined

CONFIRM : confirm(“Are you Gay?”)


It shows a pop-up with an “Ok” and “cancel” button. If u click ok the expression results
true otherwise false

PROMPT : prompt(“enter your message”)


It shows a pop-up with some input field. If you input something and press ok then that
entered expression will be the result of the promt expression. If you click cancel then the
return value will be “null”

NOTE : - YOU CAN STORE THE RETURN VALUES OF THESE DIAGLOGUE


BOXES IN SOME VARIABLE
NOTE : - ALL WILL RESULT DIFFERENT IN DIFFERENT TABS AND
BROWSERS

Que What is template literal or template string ? Explain with example


Ans It is used to fetch vale from a variable and use it with string.

Example:-
let a = 10;
let b = 20;
[Link](`The sum of ${a} and ${b} is ${a + b}.`);

// Output: "The sum of 10 and 20 is 30."

NOTE : - Write the string in backticks(` `) if u wanna use ${} not (“ “) or (‘ ‘)

Que How many fallacy values are there


Ans Undefined
Null
empty string(‘ ‘)
0
NaN

Que What will be the output


a = ‘21’ ;
b = 21 ;
[Link](a==b);
[Link](a===b);
Ans true
false
This is because there is implicit conversion of the string to number in case of “==” but in
Case of “===” data type should also be same to result true.

Que Explain && and || operators


Ans In JavaScript, the && operator (logical AND) evaluates operands from left to right and
returns the first falsy value it encounters. If no falsy value is found, it returns the last value.

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.

Que How to delete a key-value pair of an object?


Ans We can do it by using the delete keyword as follows
delete [Link];
or
delete obj[“key”];
or
delete obj[‘key’];

Que What is the difference between seal() and freeze() methods in ?


Ans seal():-
This method prevents any deletion or insertion of a key-value pair if used with an object.
But you can change the existing properties.

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.

Que Can we keep multiple type of datatypes in arrays


Ans Yes

Que Explain push() function.


Ans It is used to add one or more elements in the end of the array
Syntax :- [Link](element1, element2, …..);
Const a=[‘deepak’ ,null, 1 ,1.5];
[Link](“hi”, 23, undefined);

Que Can we add key-value pairs in js?


Ans Yes

Que What is the difference between shift() and pop() methods?


Ans shift() removes an element from the front of an array while pop() removes from the end.

Que What is the unshift() function in js?


Ans It will add an element in front of the array.

Que Does concatenation of two arrays modify the original array?


Ans No

Que Explain and give the syntax of concat function in arrays


Ans concat() function is used to merge two or more arrays.
Syntax: [Link](arr2, arr3, arr4,……);

Que Does reverse() and sort() modify the original array?


Ans Yes

Que What is the difference between slice() and splice() methods ?


Ans Slice:-
This method gives a part of an array in a given range and gives a new array not modified
original one.
Syntax: [Link](st,end)

Splice:-
It is the same as slice but it modifies the original array also.

Que Find the output of


let a = [1, 2, 3];
let b=a;
[Link](4, 5);
[Link](a);
[Link](b);
Ans [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

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.

Que What is shallow copy and Deep copy?


Ans Shallow copy:-
Copies elements/properties but shares references for nested structures. Suitable for non-
nested or shallow data structures.

Deep copy:-
Creates a fully independent copy of the original structure, including nested objects. Suitable
for complex or deeply nested data structures.

Que Does a copy of variables is created when variables is passed to functions?


Ans When a primitive type (e.g., number, string, boolean, null, undefined, symbol, bigint) is
passed as an argument to a function, a copy of the variable is passed. This means that
changes made to the parameter inside the function do not affect the original variable.

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.

Que Which variable has the largest scope ?


{
let b=2;
const c=3;
var d=4;
}
function f(){
e=5;
var f =6;
}
Ans b and c has only local scope of that bracket
d has a scope inside as well as outside the bracket/block.
f is declared with ‘var’ but if ‘var’ is in a function is stays in the scope of the function only.
e is not declared with any of ‘let’, ‘var’ or ‘const’ so it will be a global variable.
So, e has the largest scope.

Que What is a Higher order function in javascript?


Ans In JavaScript, a higher-order function is a function that does at least one of the following:
1. Takes one or more functions as arguments.
2. Returns a function as its result.

Que What is [Link]() ?


Ans ‘[Link]()’ is a method in JavaScript that is used to display an interactive listing of the
properties of a specified JavaScript object. It is particularly useful for inspecting the
properties and structure of objects in a more detailed and readable format than [Link].

Que Explain anonymous function in js


Ans An anonymous function in JavaScript is a function that does not have a name. These
functions are often used as arguments to other functions or assigned to variables.
Anonymous functions are useful for creating quick, throwaway functions or for use in
callbacks and event handlers.

Example:-
function a(b){
b();
}
a(function(){
[Link]("i am an anonymous function")
});

Que What are callback functions?


Ans In JavaScript, a callback function is a function that is passed as an argument to another
function, with the expectation that the callback function will be invoked (or called back) at
a certain point inside the containing function

Example:
function greet(name, callback) {
[Link]('Hello, ' + name + '!');
callback();
}
function sayGoodbye() {
[Link]('Goodbye!');
}
greet('Alice', sayGoodbye);

NOTE:- Here sayGoodbye is a callback function

Que What is setTimeout?


Ans ‘setTimeout’ is a function in JavaScript that allows you to execute a piece of code or a
function after a specified delay (measured in milliseconds). It is commonly used for
scheduling tasks to run in the future, creating delays, or deferring code execution.

If you simply pass a js code in form of string it will execute that code, For example
setTimeout(‘[Link](“Hi”)’);

You can also give a delay time in milliseconds, For example


setTimeout(‘[Link](“Hi”)’,3000);
This example prints "Hi" to the console after a delay of 2000 milliseconds (2 seconds).

Its complete syntax is


setTimeout(function, delay, [param1, param2, ...])
● function: The function to be executed after the delay.
● delay: The time, in milliseconds, to wait before executing the function.
● param1, param2, ... (optional): Additional parameters to pass to the function.
BASIC USAGE:
setTimeout(() => {
[Link]('This message is displayed after 2 seconds');
}, 2000);

USING NAMED FUNCTION:


function sayHello(name) {
[Link](`Hello, ${name}!`);
}
setTimeout(sayHello, 3000, 'Alice');

USING ANONYMOUS FUNCTION:


setTimeout(function() {
[Link]('This message is displayed after 2 seconds');
}, 2000);

Que What is clearTimeout?


Ans You can cancel a timeout using the ‘clearTimeout’ function if you need to prevent the
scheduled function from running.

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);

Que What are setInterval and clearInterval


Ans setInterval is a function in JavaScript that repeatedly executes a specified function or code
snippet with a fixed time delay between each call
Syntax: setInterval(function, delay, [param1, param2, ...])

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);

Que What is synchronous and asynchronous programming in JavaScript?


Ans Synchronous Programming:
Synchronous programming means that code is executed sequentially, one statement at a
time. Each operation must complete before the next one begins. This can lead to blocking
behaviour if a task takes a long time to complete.

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

Que Explain event loop and callback queue


Ans EVENT LOOP:
The event loop is a fundamental part of JavaScript's concurrency model, enabling non-
blocking I/O operations despite JavaScript being single-threaded. Its main purpose is to
handle asynchronous operations such as I/O, timers, and user interactions efficiently.
Here’s how it works:

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.

Que What is closure in JavaScript?


Ans In JavaScript, a closure is a function that has access to its own scope, the scope of the outer
function, and the global scope. This occurs when a function is defined inside another
function, and the inner function retains access to the variables and arguments of the outer
function, even after the outer function has finished executing.

EXAMPLE:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
[Link]('Outer Variable: ' + outerVariable);
[Link]('Inner Variable: ' + innerVariable);
}
}
const newFunction = outerFunction('outside');
newFunction('inside');

1. outerFunction is called with the argument 'outside', and it returns innerFunction.


2. The returned innerFunction is assigned to newFunction.
3. When newFunction is called with the argument 'inside', it logs both the
outerVariable and innerVariable.
4. Despite outerFunction having finished execution, innerFunction retains access to
outerVariable. This is the essence of a closure: it "closes over" its surrounding
state.

Que What is the difference in methods and functions in javascript?


Ans Every method is a function but every function is not a method.
Ek function ko method tab bolte hai jab usko ek object ke ander rakh dete hai

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”);
};

ARROW FUNCTIONS EXPRESSION:


const a=(n1,n2)=>n1+n2;

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

Que Give an example of using arrow function expression with setTimeout


Ans setTimeout(() => {
[Link]("This message is displayed after 2 seconds");
}, 2000);

Que What is “use strict” mode?


Ans "use strict"; is a directive in JavaScript that enables strict mode for the entire script or
individual functions. When you use "use strict";, you're opting into a stricter set of rules and
better error handling in JavaScript

USING STRICT MODE:


Global Strict Mode: Placing "use strict"; at the beginning of a script file applies strict
mode to the entire file.
Function-level Strict Mode: Placing "use strict"; inside a function enables strict mode
only within that function
.
EXAMPLE
"use strict";

// This code is in strict mode


let x = 10;
[Link](x); // Outputs: 10

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
}

for… in loop is used to iterate over objects


EX:-
Const a={‘a’:1, ‘b’:2, ‘c’:3};
for(const val in a){
[Link](a[val];
}

NOTE: USING FOR…IN LOOP WITH OBJECT IS SLOW.


So we can use another method
EXAMPLE:

const obj = {'a':1,'b':2,'c':3};


const b=[Link](obj); // will store an array of keys of object ‘obj’
const c=[Link](obj); // will store an an array of values of object ‘obj’
const d=[Link](obj); // will store an array of [key, value] pairs of the object ‘obj’
// and now you can iterate according to your requirement using for..of loop
for(const x of b){[Link](x);}
for(const x of c){[Link](x);}
for(const x of d){[Link](x);}

Que Explain forEach method in js


Ans It is used to iterate over arrays.
It takes a callback function an a parameter.
EXAMPLE:

const a = [1,2,3,4,5];
[Link]((x)=>{
[Link](x);
})
OR
[Link](function(x){
[Link](x);
})

Que const a = [1,2,3,4,5];


x=[Link]((x)=>{
[Link](x);
return 21;
})
What will x store?
Ans x will store undefined because return to vo anonymous function kar rha hai return, forEach
nahi. To foreach undefined return krta hai to undefined x me aa jaega

Que Explain map


Ans In JavaScript, the map method is a built-in function that allows you to transform elements
in an array. It creates a new array populated with the results of calling a provided function
on every element in the calling array. The original array remains unchanged.

Syntax: [Link](function(currentValue, index, array), thisArg)

currentValue (required): The current element being processed in the array.


index (optional): The index of the current element being processed in the array.
array (optional): The array map was called upon. Used to access original array
elements
thisArg (optional): Value to use as this when executing the callback function.

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]

Que Explain filter


Ans In JavaScript, the filter method creates a new array with all elements that pass the test
implemented by the provided function. This method is useful when you want to extract a
subset of elements from an array based on certain criteria.

Syntax: [Link](function(element, index, array), thisArg)

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]

Que Explain reduce


Ans The reduce method in JavaScript is used to execute a reducer function on each element of
an array, resulting in a single output value. It's a powerful tool for summing up values,
combining elements into a single object, or performing any cumulative operation.

Syntax: [Link](callback(accumulator, currentValue, index, array), initialValue)


● callback (required): A function to execute on each element in the array, taking
four arguments:
● accumulator (required): The accumulated value previously returned in the
last invocation of the callback, or initialValue, if supplied.
● currentValue (required): The current element being processed in the array.
● index (optional): The index of the current element being processed in the
array.
● array (optional): The array reduce was called upon.
● initialValue (optional): A value to use as the first argument to the first call of
the callback. If no initial value is supplied, the first element in the array will
be used as the initial accumulator value, and the callback will start from the
second element.
Example:
const numbers = [1, 2, 3, 4, 5];
const sum = [Link]((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
[Link](sum); // Output: 15

Que Explain some and every method in js


Ans In JavaScript, the some and every methods are used to test elements in an array against a
provided condition. Both methods take a callback function as an argument and return a
boolean value based on the condition applied to the elements of the array.

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)

● element (required): The current element being processed in the array.


● index (optional): The index of the current element being processed in the
array.
● array (optional): The array some was called upon.
● thisArg (optional): Value to use as this when executing the callback
function.
EXAMPLE:
const numbers = [1, 2, 3, 4, 5];
const hasEven = [Link](function(number) {
return number % 2 === 0;
});
[Link](hasEven); // Output: true
EVERY:
The every method tests whether all elements in the array pass the condition implemented
by the provided function. If all elements meet the condition, every 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

Que Explain Arguments keywords in js


Ans In JavaScript, the arguments keyword is a local variable available within all non-arrow
functions. It allows access to all arguments passed to the function, even if they were not
explicitly named as parameters when defining the function

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

Que Explain spread operator in js


Ans The spread operator (...) in JavaScript is a powerful and versatile syntax that allows an
iterable (like an array or a string) to be expanded into individual elements. It provides an
easy way to manipulate arrays (or other iterables) and make copies, merge arrays, pass
function arguments, and more.

Syntax and Usage

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];

[Link](combined); // Output: [1, 2, 3, 4, 5, 6]

Passing Function Arguments

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;
}

const numbers = [1, 2, 3];


[Link](sum(...numbers)); // Output: 6

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];

[Link](arr2); // Output: [0, 1, 2, 3, 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.

Que What are rest parameters?


Ans Allows you to pass any number of values

Que What is destructuring?


Ans It basically makes extracting data shorter and easier

Que Explain DOM in js


Ans 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:

With the object model, JavaScript gets all the power it needs to create

dynamic HTML:

● JavaScript can change all the HTML elements in the page


● JavaScript can change all the HTML attributes in the page
● JavaScript can change all the CSS styles in the page
● JavaScript can remove existing HTML elements and attributes
● JavaScript can add new HTML elements and attributes
● JavaScript can react to all existing HTML events in the page
● JavaScript can create new HTML events in the page
The HTML DOM is a standard object model and programming interface for
HTML. It defines:

The HTML elements as objects T

he properties of all HTML elements

The methods to access all HTML elements

The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.

Que What is DOM manipulation?


Ans DOM (Document Object Model) manipulation is the process of dynamically changing the
content, structure, and style of a web page using scripting languages like JavaScript.

Various ways yo select elements:


getElementByTagName()
getElementByClassName()
getElementById()
[Link]()
[Link]()

Que What Is the difference between [Link] and [Link]()?


Ans [Link] returns the first element that matches a specified css selector
[Link]() returns a Node list that of all elements that matches the
selector

Que What is innerHTML?


Ans innerHTML is a property in JavaScript that is used to get or set the HTML content of an
element. It is commonly used to manipulate the content of HTML elements dynamically.
When you use innerHTML, you can either retrieve the current HTML content of an element
or replace the existing content with new HTML.

GETTING EXAMPLE SETTING EXAMPLE

<!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

● Definition: innerText represents the


"rendered" text content of a node and its ● Definition: textContent represents the
descendants. It takes into account CSS text content of a node and its
styles, including display: none and visibility descendants in a straightforward
properties. This means innerText will not manner. It includes all text, even if it
include hidden text. is hidden with CSS.

● Live Updates: innerText triggers a reflow of


the document to compute the up-to-date ● Performance: textContent is generally
layout and recomputes the content, making faster because it does not trigger
it slower in some cases. reflow or layout changes.

● Whitespace: It also normalizes the text by ● Whitespace: It preserves all


removing extra spaces and line breaks. whitespace, including extra spaces
and line breaks.
Que Explain getAttribute() and setAttribute() in js
Ans setAttribute():
The setAttribute method is used to set the value of an attribute on a specified element. If the
attribute already exists, it updates the value; if it does not exist, it creates the attribute with
the specified value.

Example:
// Assume there's an element <div id="myDiv"></div>
var myDiv = [Link]('myDiv');

// Set the class attribute to "myClass"


[Link]('class', 'myClass');

// Now the element will be <div id="myDiv" class="myClass"></div>

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');

// Get the value of the class attribute


var classValue = [Link]('class');

// classValue will be "myClass"

Que Explain parent, children and sibling in context of DOM.


Ans Parent element:
A parent element is an element that contains other elements (called child elements). In the
DOM tree, the parent element is one level above its child elements.

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.

Examples: `<div>`, `<p>`, `<a>`, `<span>`, etc.


- **Properties and Methods**: Elements have specific properties and methods that are not
available to other types of nodes. For example, `getElementById`,
`getElementsByClassName`, `innerHTML`, `outerHTML`, and `classList` are specific to
elements.

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.

3. Properties and Methods:


Nodes have general properties like `nodeType`, `nodeName`, `nodeValue`, and
`childNodes`.
Elements have additional properties and methods like `tagName`, `innerHTML`,
`outerHTML`, `getAttribute`, `setAttribute`, and `classList`.

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.

Que Explain appendChild and append in js DOM


Ans appendChild:
It is used to add a single node to the end of the list of children of a specified parent node.
Syntax: [Link](childNode)
Parameters:

● parentNode: The node to which you want to add the child.


● childNode: The node that you want to add to the parent.

Returns: The appended child node.


Behavior:

● Only a single node can be appended at a time.


● If the childNode is already in the document, it will be moved from its current
position to the new position.
● Cannot append text directly; text must be wrapped in a text node.

Example:

// Create a new element


var newDiv = [Link]("div");

// Create a text node


var newContent = [Link]("Hi there!");
// Add the text node to the div
[Link](newContent);

// Add the new div to the body


[Link](newDiv);

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:

● nodesOrDOMStrings: One or more nodes or strings to be added. Strings will be


automatically converted to text nodes.

Returns: No return value (undefined).


Behavior:

● Can append multiple nodes and strings at once.


● If a string is provided, it will be appended as a text node.
● If a node is already in the document, it will be moved to the new position.
● More modern and versatile than appendChild.

Example:
// Create new elements
var newDiv = [Link]("div");
var newSpan = [Link]("span");

// Create text content


var text1 = "Hello, ";
var text2 = "World!";

// Append elements and text to the div


[Link](newSpan, text1, text2);

// Add the new div to the body


[Link](newDiv);

Que How can we create elements in JS DOM?


Ans

Que What are events listeners in JS?


Ans Event listeners in JavaScript are functions that wait for specific events to occur on specific
elements and then execute the associated code when those events happen

Syntax: [Link](event, handler, options);


● element: The DOM element to which you want to attach the event listener.
● event: A string representing the event type to listen for (e.g., "click", "mouseover",
"keydown").
● handler: The function to run when the event occurs.
● options (optional): An object or boolean value specifying characteristics about the
event listener.

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

Que Find the output


HTML JAVASCRIPT
<!DOCTYPE html> const a =
<html lang="en"> [Link](".heading");
<head>
<meta charset="UTF-8" /> [Link] = function () {
<meta name="viewport" [Link]("hi1");
content="width=device-width, initial- };
scale=1.0" /> [Link] = function () {
<title>Document</title> [Link]("hi2");
};
<script src="[Link]" defer></script>
[Link]("click", function () {
</head>
[Link]("hi3");
<body>
});
<h1 class="heading">dialogue
boxes</h1> [Link]("click", function () {
</body> [Link]("hi4");
</html> });

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 Defer Vs Async Script tag


Ans
DEFER ASYNC
Downloads: The script is downloaded Downloads: The script is downloaded
in the background while the browser in the background while the browser
continues parsing the HTML. continues parsing the HTML.
Execution: The script is executed after Execution: The script is executed as
the HTML has been fully parsed and the soon as it is downloaded, regardless of the
DOM is constructed. parsing status of the HTML.
Order: Scripts with defer are executed Order: Scripts with async are executed
in the order they appear in the document. in an unpredictable order.
Use case: Ideal for scripts that depend Use case: Suitable for scripts that are
on the DOM being ready, such as scripts independent of the DOM and don't rely on
that manipulate DOM elements. other scripts.

Que Explain cloneNode() in JavaScript


Ans cloneNode() is a method in JavaScript that creates a duplicate of a specified node. It's part
of the Node interface and is used for cloning elements in the Document Object Model
(DOM).

Syntax: clone = [Link](deep);

clone: The newly created cloned node.


node: The original node to be cloned.
deep: An optional boolean parameter.
● true: Clones the node and all its descendants (deep clone).
● false (default): Clones only the specified node without its children (shallow clone).

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');
});

Que Explain keyboard events


Ans There are three main keyboard events:

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.

Que Explain mouse events


Ans ● click: Triggered when the user presses and releases a mouse button over an
element. It is often used to execute actions when users click on buttons, links, or
other interactive elements.

● dblclick: Triggered when the user double-clicks on an element. It is commonly


used for actions like opening files or performing special functions in applications.

● 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 Explain event propagation in js


Ans In JavaScript, event propagation is a fundamental concept that determines how events are
handled in the DOM (Document Object Model). It involves two main phases: event
capturing and event bubbling

Event Capturing (or Capture Phase):


Event capturing is the first phase of event propagation. During this phase, the event starts
from the top of the DOM tree (the document) and travels down to the target element where
the event actually occurred.

Event Bubbling (or Bubble Phase):


Event bubbling is the second phase of event propagation. During this phase, the event starts
from the target element where it occurred and bubbles up to the top of the DOM tree.

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 });

Que What is Destructuring in javascript?


Ans Destructuring in JavaScript is a convenient way of extracting values from arrays or
properties from objects into distinct variables. It simplifies the process of assigning
variables from complex data structures.

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.

const numbers = [1, 2, 3];


const [first, , third] = numbers;
[Link](first); // 1
[Link](third); // 3

**Default Values:**
You can assign default values to variables if the unpacked value is `undefined`.

const numbers = [1];


const [a, b = 2] = numbers;

[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
};

const { name, age } = person;

[Link](name); // Alice
[Link](age); // 25
**Renaming Variables:**
You can rename variables while destructuring.

const person = {
name: 'Alice',
age: 25
};

const { name: personName, age: personAge } = person;

[Link](personName); // Alice
[Link](personAge); // 25

**Default Values:**
You can assign default values if the property is `undefined`.

const person = {
name: 'Alice'
};

const { name, age = 30 } = person;

[Link](name); // Alice
[Link](age); // 30

**Nested Destructuring:**
You can destructure nested objects.

const person = {
name: 'Alice',
address: {
city: 'Wonderland',
zip: '12345'
}
};

const { name, address: { city, zip } } = person;

[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.

Que What is JSON?


Ans JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for
humans to read and write, and easy for machines to parse and generate. It is primarily used
to transmit data between a server and a web application as text.

Key Characteristics of JSON:


● Syntax: JSON syntax is derived from JavaScript object notation, but it is language-
independent, meaning it can be used with most programming languages.
● Structure: JSON data is organized in key-value pairs:
o Object: { "key": "value" }
o Array: [ "value1", "value2", "value3" ]
● Data Types: JSON supports simple data types like strings, numbers, booleans,
arrays, and objects (which are similar to dictionaries or hash maps in other
languages).
Example:
{
"name": "John",
"age": 30,
"isStudent": false,
"courses": ["Math", "Science", "History"],
"address": {
"city": "New York",
"zipcode": "10001"
}
}

Que What is an API?


Ans An API, or Application Programming Interface, is a set of rules and tools that allow
different software applications to communicate with each other. It defines the methods and
data formats that applications can use to request and exchange information.
Key Points About APIs:
Interface: APIs act as an interface between different software programs. For example,
when you use an app on your phone to check the weather, it might use an API to fetch data
from a weather service.
Endpoints: APIs typically consist of endpoints, which are specific URLs that can be called
by applications to perform certain actions (like retrieving data, sending data, etc.).
Requests and Responses: APIs work by sending requests to an endpoint and receiving a
response. The request might include specific parameters or data, and the response will
contain the requested information, usually in a structured format like JSON or XML.
REST and SOAP: Two common types of APIs are REST (Representational State
Transfer) and SOAP (Simple Object Access Protocol). REST is more common and uses
standard HTTP methods like GET, POST, PUT, and DELETE. SOAP is more rigid and
relies on XML-based messaging.
Security: APIs often use authentication methods like API keys, OAuth, or tokens to ensure
that only authorized users can access or modify the data.

Que What is callback hell


Ans "Callback hell" (also known as "Pyramid of Doom") is a term used in JavaScript to
describe a situation where multiple nested callbacks make code difficult to read and
maintain. This commonly happens when dealing with asynchronous operations, such as
handling multiple asynchronous requests or tasks.

Example

Que What are promises in javascript?


Ans Promise is an object representing the eventual completion or failure of an asynchronous
operation and its resulting value. Promises provide a way to handle asynchronous code in a
more manageable and readable way, avoiding "callback hell."

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)
})

Que What will be the output of the 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)
})
[Link]("end");
Ans start
end
Promise rejected

Because promises are asynchronous and they will be executed after execution of
synchronous code

Que What will be the output of this 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

Que Explain fetch() function


Ans fetch() function is used to make HTTP requests from the web browser to a server. It allows
you to asynchronously fetch resources across the network. This function returns a Promise
that resolves to the Response object representing the response to the request.

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.

Que How to send a post request using fetch


Ans To send a POST request you have to provide another parameter which is an object to the
fetch function and you have to mention the following things which is mentioned in this
example.

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
});

Que Explain async-await


Ans async is used with function and that function always returns a promise. Await is used along
with a promise which will then contain the resolved value of that promise.

Que Explain optional chaining in JavaScript


Ans Optional chaining (?.) in JavaScript is a feature that allows you to safely access deeply
nested properties of an object without having to explicitly check if each reference in the
chain is valid (i.e., not null or undefined). If any part of the chain is null or undefined, the
expression short-circuits and returns undefined without throwing an error.

WITHOUT OPTIONAL CHAINING :


let street = user && [Link] && [Link];
OR
let street;
if (user) {
if ([Link]) {
street = [Link];
}
}

WITH OPTIONAL CHAINING :


let street = user?.address?.street;

Que Explain local storage in JavaScript?


Ans Local storage in JavaScript is a feature that allows you to store data in the user's browser. It
is part of the Web Storage API, which provides mechanisms to store key-value pairs in a
web browser.

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');

Clearing All Data:


[Link]();

Checking the Storage:


let length = [Link];
Que
Ans

You might also like