Faq JS 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Javascript - FAQ SET 2

_____________________________________________
__

Q1 : Differences and use local, session and cookie storage?


Local storage, session storage, and cookies are all ways to store data in a
user's browser, but they have some key differences.

Local storage allows you to store data on the user's device permanently,
until the user manually clears it. This means that the data will still be
available even if the user closes the browser or restarts their device.
Session storage, on the other hand, only stores data for a single browser
session. The data is deleted when the user closes the browser or restarts
their device.

Cookies are small text files that are stored on the user's device by the
website. They are used to remember the user's preferences or activity on
the website. Cookies are sent back to the server with each request, which
allows the website to maintain state. Cookies have a size limit of 4KB and
have expiration time.

In general, you would use local storage if you need to store data
permanently, and session storage or cookies if you only need to store
data temporarily.

Q2 : explain about Data types in javascript?

JavaScript has several built-in data types, including:


1. Number: used for numeric values, including integers and floating-
point numbers.
2. String: used for text values.
3. Boolean: used for true/false values.
4. Undefined: used when a variable has been declared but has not
been assigned a value.
5. Symbol: used to create unique and immutable identifiers.
6. Object: used to store collections of data and functions.

JavaScript also has two special data types:


1. null: represents a null or empty value.
2. NaN: represents a "not a number" value.
JavaScript is a dynamically-typed language, which means that variables
do not have a fixed data type. The same variable can hold values of
different data types during the execution of a program.
JavaScript also has a typeof operator which is used to check the data type
of a variable. It returns a string indicating the type of the variable.

For example,
let x = 10;
console.log(typeof x); // "number"

let y = "hello";
console.log(typeof y); // "string"

let z = true;
console.log(typeof z); // "boolean"

JavaScript also has a new operator called instanceof which is used to


check the type of an object, it returns a boolean indicating whether the
object is an instance of the specified constructor.
For Example,

let x = new Array();


console.log(x instanceof Array); // true
console.log(x instanceof Object); // true

Q3 : how does react convert jsx to vanilla js?


React converts JSX to vanilla JavaScript using a transpiler, such as
Babel.
When a React application is built, the JSX code is transformed into
JavaScript code that can be understood by the browser. This process is
known as transpilation. The transpiler, such as Babel, will parse the JSX
code and convert it into equivalent JavaScript code, which can be
understood by the browser.

For example, this JSX code:

const element = <h1>Hello, world!</h1>;

Will be transpiled to this JavaScript code:

const element = React.createElement("h1", null, "Hello, world!");


In the transpiled JavaScript, React.createElement is used to create a
virtual DOM node that represents the JSX element. The first argument is
the type of the element, the second argument is the properties of the
element and the rest are the children of the element.
When the JavaScript code is executed, React uses this virtual DOM to
update the actual DOM, which is what the user sees in the browser. This
process is known as "reconciliation" and it ensures that the DOM is
updated efficiently, only changing the elements that need to be updated.
So, React converts JSX to vanilla JavaScript using transpilation and this
conversion allows React to work efficiently with the DOM and update the
UI in an efficient way.

Q4 : Explain all array methods available in javascript?

Here are some commonly used array methods in JavaScript:


1. concat(): combines two or more arrays into a single array.
2. every(): checks if every element in an array pass a test.
3. filter(): creates a new array with elements that pass a test.
4. find(): returns the first element that passes a test.
5. forEach(): executes a function for each element in an array.
6. join(): converts an array to a string, with a separator between
elements.
7. indexOf(): returns the first index at which an element can be
found.
8. map(): creates a new array with the results of a function for each
element.
9. pop(): removes the last element from an array and returns it.
10. push(): adds one or more elements to the end of an array and
returns the new length.
11. reduce(): applies a function to reduce an array to a single value.
12. reverse(): reverses the order of elements in an array.
13. shift(): removes the first element from an array and returns it.
14.slice(): extracts a part of an array and returns it as a new array.
15. sort(): sorts the elements of an array in place.
16.splice(): adds or removes elements from an array.
17. toString(): returns a string representation of an array.
18. unshift(): adds one or more elements to the front of an array
and returns the new length.
19.some(): checks if any element in an array passes a test.

Note that not all methods are available in all versions of JavaScript, and
your exact usage may vary depending on the version you are using.
Q5 : What are the features added in ES6?

ECMAScript 6 (ES6), also known as ECMAScript 2015, is a version of


JavaScript that was released in 2015. It introduced several new features
and improvements to the language. Some of the main features added in
ES6 include:

1. Arrow functions: a shorthand for defining anonymous functions,


with a more concise syntax.
2. Classes: a new way to define object-oriented classes and
constructors.
3. Template literals: a new way to create string templates, with
support for string interpolation.
4. Destructuring: a new way to extract data from arrays or objects
and assign it to variables.
5. Default parameters: a way to specify default values for function
parameters.
6. Spread operator: a way to expand arrays and objects and pass them
as separate arguments to a function.
7. Rest parameters: a way to gather remaining arguments into an
array.
8. Promises: a new way to handle asynchronous code, to make it
easier to write and reason about.
9. Modules: a new way to organize and share JavaScript code,
including support for imports and exports.
10. let and const: new ways to declare variables, with block-level
scope and immutability.

These are some of the main features added in ES6. There are many more
features and enhancements, such as Symbols, Iterators, Generators, and
more. These new features help developers to write more efficient and
maintainable code, and makes JavaScript more powerful.

Q5 : Explain about Arrow function?

Arrow functions, also known as "fat arrow" functions, are a shorthand


syntax for defining anonymous functions in JavaScript. They were
introduced in ECMAScript 6 (ES6) and are a more concise way to write
function expressions.
Here is an example of an anonymous function defined using the
traditional function keyword:

let add = function (a, b) {


return a + b;
}
And here is the same function defined using an arrow function:

let add = (a, b) => {


return a + b;
}

Arrow functions have several key features:

1. They have a shorter syntax than traditional function expressions.


2. They do not bind their own this, arguments, super, or new.target
values.
3. They are always anonymous.

A few more examples of arrow function are

let double = (x) => x * 2;


let greet = () => console.log("Hello World!");
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(x => x * 2);

Arrow function are very useful in array methods like map, filter, reduce
etc and they are also useful when you are passing function as a
parameter.

Arrow functions can be very useful in simplifying your code and making
it more readable and maintainable.

Q6 : Difference between javascript, react and typescript?

JavaScript, React, and TypeScript are all technologies related to web


development, but they serve different purposes:

 JavaScript is a programming language that is widely used to create


interactive websites, as well as to build server-side applications
and mobile apps using frameworks like Node.js. JavaScript is
supported by all web browsers and is the de facto standard for
client-side web development.
 React is a JavaScript library for building user interfaces. It was
developed by Facebook and is now maintained by a community of
developers. React allows developers to create reusable UI
components and manage the state of an application. It uses a
virtual DOM that optimizes the performance of web applications.
 TypeScript is a superset of JavaScript, which adds optional types
and other features to the language. It was developed by Microsoft
and is now an open-source project. TypeScript is designed to
improve the development experience by providing better tooling
and catching errors early. It can also be used to build large-scale
applications, with features like interfaces and classes.

In summary, JavaScript is a programming language, React is a library


for building user interfaces, and TypeScript is a superset of JavaScript
that adds optional types and other features to improve the development
experience.

React and TypeScript can be used together to build web applications.


React allows developers to build reusable components and manage the
state of an application, while TypeScript provides better tooling and
catching errors early.

Q7 : explain all events and onclick functionality?

JavaScript allows you to add interactivity to web pages by using events.


Events are actions or occurrences that happen in the browser, such as a
button being clicked, a page being loaded, or a user moving the mouse
over an element.
Here are some common events in JavaScript:

 click: Triggered when an element is clicked.


 mousedown: Triggered when a mouse button is pressed down on
an element.
 mouseup: Triggered when a mouse button is released on an
element.
 mousemove: Triggered when the mouse is moved over an element.
 mouseover: Triggered when the mouse pointer enters an element.
 mouseout: Triggered when the mouse pointer leaves an element.
 keydown: Triggered when a key is pressed down on the keyboard.
 keyup: Triggered when a key is released on the keyboard.
 submit: Triggered when a form is submitted.
 load: Triggered when a page or an image is fully loaded.
 resize: Triggered when the browser window is resized.
 scroll: Triggered when the document view is scrolled.

onclick is a JavaScript function that is used to add a click event to an


element. It is used to execute a function when an element is clicked.
Here's an example of how to use the onclick function:
<button onclick="alert('Button clicked!')">Click me</button>

In this example, when the button is clicked, the alert function will be
called and the message "Button clicked!" will be displayed.

You can also use the addEventListener method to attach an event to an


element.

let button = document.getElementById("myBtn");


button.addEventListener("click", function(){
alert("Button clicked!");
});

This method is more flexible as you can attach multiple events to the
same element and also you can remove events using
removeEventListener method.

These are just some examples of how events and onclick functionality
can be used in JavaScript. There are many other types of events and
ways to handle them, but these are the most common.

Q8 : How does async and defer work?

In HTML, async and defer are attributes that can be used to load
external scripts (JavaScript files) asynchronously.

The async attribute tells the browser to load the script asynchronously,
which means that it will download the script file in the background while
the page continues to load. Once the script is downloaded, it will be
executed immediately. This can improve the performance of a page by
allowing it to load faster. However, it can also cause issues if the script
relies on other resources or elements that haven't loaded yet.

The defer attribute tells the browser to load the script asynchronously,
but to only execute it once the page has finished loading. This can be
useful for scripts that don't need to run immediately, but should be
executed after the page has loaded.

Here's an example of how to use the async attribute:

<script async src="script.js"></script>

And here's an example of how to use the defer attribute:


<script defer src="script.js"></script>

When both async and defer are present, defer will take precedence.
By default, script tags block the rendering of the page, it means the
browser will not render the page until the script is fully downloaded,
parsed and executed. Using async or defer allows the browser to
continue parsing and rendering the page while the script is being
downloaded, parsed, and executed in the background.

If you're using a library like jQuery, then it's usually recommended to use
the defer attribute, as it will ensure that jQuery is loaded and ready to
use before any scripts that rely on it are executed.

In summary,
 async attribute tells the browser to download the script file in the
background while the page continues to load, and execute the
script immediately.
 defer attribute tells the browser to download the script file in the
background while the page continues to load, and execute the
script only after the page is fully loaded.

Q9 : What is debouncing and throttling?

Debouncing and throttling are techniques used to limit the number of


times a function or event is executed in a given period of time.

Debouncing is a technique in which multiple function calls are


consolidated into a single call, executed after a certain period of time has
passed without any new calls being made. This is useful in situations
where a rapid succession of events (such as a user typing quickly) would
otherwise cause a function to be executed multiple times, wasting
resources and potentially causing unexpected behavior.

Throttling is similar to debouncing, but instead of waiting for a period of


time to pass before executing the function, it limits the number of times
the function can be executed within a given period of time. This is useful
in situations where you want to limit the rate at which a function is
executed (for example, to prevent a server from being overwhelmed with
requests).

Both debouncing and throttling are used to improve the performance


and responsiveness of a user interface, by preventing unnecessary
function calls and limiting the rate at which functions are executed.

Q10 : What is temporal deadzone?

Temporal dead zone (TDZ) is a concept in JavaScript that refers to a


period of time during which certain variables or function bindings are
not accessible.
In JavaScript, variables declared with the let or const keywords are not
accessible until they are initialized. This means that if a variable is
declared with let or const and then accessed before it is initialized, an
error will be thrown. The period of time between the variable declaration
and initialization is known as the temporal dead zone.

For example, if you declare a variable with let x; and then try to access
the variable before it is initialized, you will get a ReferenceError .

console.log(x); // ReferenceError: x is not defined


let x;

TDZ is also applicable on function binding with let or const keyword. If a


function is declared with let or const and then accessed before it is
initialized , an error will be thrown.

f(); // ReferenceError: x is not defined


let f = function() { console.log('Hello'); }

TDZ is a feature of JavaScript that is intended to help developers catch


errors early, by ensuring that variables and functions are properly
initialized before they are used.

Q11: Difference between for in & for of loop?

for...in and for...of are both looping constructs in JavaScript, but they are
used for different purposes and have some key differences.
A for...in loop is used to iterate over the enumerable properties of an
object. It will iterate over all enumerable properties, including those that
are inherited from the object's prototype.

let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key + ': ' + obj[key]);
}
// Output:
// a: 1
// b: 2
// c: 3

A for...of loop is used to iterate over the values of an iterable object, such
as an array or a string. It does not iterate over properties of an object,
instead it iterates over the values of the object.

let arr = [1, 2, 3];


for (let val of arr) {
console.log(val);
}
// Output:
// 1
// 2
// 3

for...of loop is not just limited to arrays, it can also be used with any
other object that implements the iterable interface.

In summary, for...in is used to iterate over the properties (keys) of an


object, while for...of is used to iterate over the values of an iterable
object.

Q12 : what is setTimeout? How does it work ?

setTimeout() is a JavaScript function that allows you to schedule a


function to be executed after a specified amount of time has passed. It is
a method of the window object, which is the global object in the browser.

The basic syntax of setTimeout() is as follows:

setTimeout(function, delay);
The function argument is the function that you want to execute after the
specified delay. The delay argument is the amount of time, in
milliseconds, that you want to wait before executing the function.

For example, the following code will log "Hello, World!" to the console
after a delay of 2 seconds (2000 milliseconds):

setTimeout(() => { console.log("Hello, World!") }, 2000);

setTimeout() works by adding the specified function to the browser's


JavaScript event queue. The function is not executed immediately, but
instead waits in the queue until the specified delay has passed. Once the
delay has passed, the function is removed from the queue and executed.

It's worth noting that when setTimeout is called, it returns an ID of the


timeout which can be used to clear the timeout using clearTimeout(id)
function.

setTimeout() is often used in conjunction with other JavaScript


functions and event-handling code to create timed events and effects in
web pages, such as delayed form submissions, timed animations, and
more.

Q13 : Task - you need to add items in div through a input box ?

Here's an example of how you might add items to a div element through
an input box using JavaScript:
HTML:

<div id="container"></div>
<input type="text" id="input-box">
<button id="add-button">Add</button>

JavaScript:

const container = document.getElementById("container");


const inputBox = document.getElementById("input-box");
const addButton = document.getElementById("add-button");

// Add event listener to the add button


addButton.addEventListener("click", function() {
// Get the value of the input box
const value = inputBox.value;
// Create a new div element
const newDiv = document.createElement("div");
// Set the text content of the new div to the value of the input box
newDiv.textContent = value;
// Append the new div to the container div
container.appendChild(newDiv);
// clear the input box
inputBox.value = ""
});

In this example, the div element with the id "container" will act as a
container for the items to be added. The input box is used to gather the
text to be added to the container and a button is used to trigger the
adding of an item to the container.
When the add button is clicked, the value of the input box is captured, a
new div element is created with the text content set to the value of the
input box and it is appended to the container div.
You can further style the divs as per your requirements.

Q14 : Explain Javascript object vs json?

JavaScript objects and JSON (JavaScript Object Notation) are both used
to represent data in JavaScript, but they have some key differences.

A JavaScript object is a collection of key-value pairs, where the keys are


strings and the values can be any data type (strings, numbers, booleans,
objects, etc.). Objects are created using curly braces {} and properties are
separated by commas.

const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};

JSON, on the other hand, 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 based on a subset of the JavaScript Programming
Language and its text format is a way of representing JavaScript objects
and arrays in a string format.

{
"firstName": "John",
"lastName": "Doe",
"age": 30
}

The main difference between a JavaScript object and JSON is that a


JavaScript object can have methods (functions), while JSON can only
have key-value pairs. JSON also requires keys to be enclosed in double-
quotes, while JavaScript objects do not.

It is possible to convert a JavaScript object to JSON using


JSON.stringify(object) method and JSON to JavaScript object using
JSON.parse(json) method.

In summary, JSON is a text-based format for representing JavaScript


objects, while a JavaScript object is an actual object in JavaScript. JSON
is typically used for transferring data between a server and a web
application, while JavaScript objects are used within a program to
represent and manipulate data.

Q15 : What will be the output and Explain approach of the


code?

for(var i=0;i<10;i++) {
setTimeout(function() {
console.log(i);
}, 1000)
}

The output of the code you provided would be the numbers 10 10 10 10


10 10 10 10 10 10, each logged to the console one second apart.

The approach used in this code is to use a for loop to iterate from 0 to 9,
and within each iteration, a setTimeout function is called with a callback
function that logs the current value of the loop variable i to the console.
However, the problem with this approach is that since the setTimeout
function is asynchronous, all the callbacks are invoked after the for-loop
has completed, so the value of i is always 10, the last value when the loop
completed, so the output will be 10 10 10 10 10 10 10 10 10 10 instead of
0123456789

You can use let instead of var or IIFE(immediately invoked function


expression) to solve the problem.
here is one way to correct the output so that it logs the numbers 0
through 9 as expected

for(var i=0;i<10;i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 1000 * i)
})(i);
}

In this version, an IIFE (immediately invoked function expression) is


used to create a new scope for each iteration of the loop, so each callback
function has access to its own copy of the variable i, rather than sharing
the same global variable. The function passed to setTimeout is invoked
after the given time delay, passing the correct value of i to the inner
function, which then logs that value to the console.

Alternatively, you can use let instead of var, as let is block scoped
variable and var is function scoped variable.

for(let i=0;i<10;i++) {
setTimeout(function() {
console.log(i);
}, 1000 * i)
}

This will also give the correct output of 0 1 2 3 4 5 6 7 8 9.

Q16 : Do you know callback hell ?

Yes, "callback hell" is a term used to describe a situation where a


program has a large number of nested callback functions, making the
code difficult to read and understand. This can happen when using
asynchronous programming techniques, such as those used in
JavaScript, where a function is passed as an argument to another
function and is only executed after some event occurs.

When many asynchronous operations are performed one after the other,
the code can become deeply nested and difficult to follow. This is often
referred to as "callback pyramid" or "callback hell". It can be difficult to
reason about the flow of control, and it becomes hard to locate bugs.
Promises and async/await are introduced to handle callback hell and
make the code more readable.
Promises provide a way to handle async operations in a more structured
way, allowing developers to chain together async operations in a way
that is similar to synchronous code.

With the introduction of async/await, it becomes much easier to write


and read asynchronous code that is easy to reason about. It makes the
code look like synchronous code, but under the hood it's still
asynchronous.

Q17 : How to fetch data from json file?

There are several ways to fetch data from a JSON file in JavaScript, but
one common way is to use the fetch() function. The fetch() function
allows you to make network requests similar to XMLHttpRequest
(XHR).

Here's an example of how you might use fetch() to load data from a local

JSON file:

fetch('data.json')

.then(response => response.json())

.then(data => {

// do something with the data

})

.catch(error => {

console.error('Error:', error);

});

In this example, the fetch() function is used to make a request to the

specified data.json file. The then() method is used to parse the response
as JSON and return a JavaScript object. The data returned from the file

can then be used in the next then callback function.

If there is any error in fetching the file it will be caught by the catch

block.

Alternatively, you can use XMLHttpRequest() object to fetch the json

file, an example would be like this:

var xhr = new XMLHttpRequest();


xhr.open('GET', 'data.json', true);
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status === 200) {
var data = xhr.response;
// do something with the data
}
};
xhr.send();

This code creates a new instance of the XMLHttpRequest object, opens a


GET request to the specified JSON file, sets the response type to JSON,
and then waits for the onload event to fire. Once the data is loaded, it can
be used within the onload callback function.

Please note that both of these examples assume that the JSON file is
hosted on the same domain as the JavaScript file. If the file is hosted on
a different domain, you'll need to configure the server to allow cross-
origin resource sharing (CORS) in order to fetch the file.

Q18 : What if the fetch api fails?

If the fetch() API fails, it will reject the promise with a TypeError or a
FailedFetchError and the catch() block will be executed. The catch()
block is used to handle any errors that occur during the fetch operation,
such as a network error or a failure to parse the response.

In the example I provided in my previous answer, the catch() block logs


the error to the console using console.error(). You can also handle the
error by displaying a message to the user or redirecting them to an error
page.

The catch() block will only be executed if the fetch request fails, such as
when the server is down or the internet connection is lost. If the request
is successful but the response has a non-2xx status code, the promise will
be resolved, but the response.ok property will be false. You can check the
response status and handle it accordingly:

fetch('data.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error, status = ${response.status}`);
}
return response.json();
})
.then(data => {
// do something with the data
})
.catch(error => {
console.error('Error:', error);
});

Also, note that the fetch() API is relatively new and not all browsers
support it. If you need to support older browsers, you may need to use an
older API like XMLHttpRequest or a library like axios or jQuery.

Q19 : write pseudo code of swap two numbers without using


temporary variable in Js?

Here is an example of how you might swap the values of two variables a
and b in JavaScript without using a temporary variable:

// Initial values of a and b


a = 10;
b = 20;

// Swapping the values of a and b


a = a + b; // a = 10 + 20 = 30
b = a - b; // b = 30 - 20 = 10
a = a - b; // a = 30 - 10 = 20

// Final values of a and b


console.log(a); // 20
console.log(b); // 10

In this example, the values of a and b are swapped by using the following
three steps:

Adding the values of a and b and storing the result in a


Subtracting the original value of b from a and storing the result in b
Subtracting the new value of b from a and storing the result in a.

This approach uses the mathematical properties of addition and


subtraction to swap the values of a and b without the need for a
temporary variable. It can be used to swap values of any number of
variables.

Please note that this is a pseudo-code, in practice you don't need to use
console.log and can just swap the variables.

Q20 : What do you understand about "strictmode" in


Javascript?

"strict mode" is a feature of JavaScript that allows you to place a


program or a function in a "strict" operating context. This means that
some of the JavaScript's "unsafe" features are disabled and certain errors
will throw in strict mode which would have been ignored in non-strict
mode. This helps to catch and prevent errors in your code, and makes it
easier to write secure and high-quality code.

When you use strict mode, you must use the string "use strict" at the
beginning of a file (global scope) or a function.

For example:

"use strict";
// code here will run in strict mode

Or

function example() {
"use strict";
// code here will run in strict mode
}
Here are some of the features that are changed or disabled in strict
mode:

 Variables that are declared but not initialized will not be created as
properties of the global object.
 The value of 'this' is undefined in function in strict mode.
 It prohibits the use of some of the less-than-ideal language features
and practices.
 It makes it impossible to accidentally create global variables.
 It eliminates some silent type-conversion errors.
It makes certain assignments that were previously allowed to throw
errors.
It disallows the use of 'eval' and 'arguments' as variable or function
names.

Strict mode is not recommended to be used in production code as it can


break some existing code and make it difficult to debug. But it is useful
while developing and testing the code.

Please note that strict mode only affects the code in the scope it is
declared, it doesn't affect the code in the other scopes.

Q21 : What is Event Looping? Can you show an example for


your explanation?

JavaScript runs on a single thread, which means that it can only execute
one task at a time. In order to handle asynchronous operations like
timers or user interactions, JavaScript uses an event loop mechanism.

The event loop continuously checks for new tasks to execute. When a
new task is added to the queue, it is processed in a First-In-First-Out
(FIFO) order. However, tasks that take longer to complete will block the
event loop and prevent other tasks from executing.
for(var i=0;i<5;i++){
setTimeout(()=>console.log(i),1000)
}

output:
5
5
5
5
5

In the given code example, a for loop is used to schedule five timer tasks
using the setTimeout function. Each timer task logs the value of i after a
delay of 1000 milliseconds (1 second).

When the loop runs, it schedules five timer tasks with the same callback
function. The delay of 1000 milliseconds ensures that the tasks are not
executed immediately. Instead, they are added to the event loop queue
and will be executed in approximately 1 second.

After the for loop finishes executing, the value of i is 5. When each timer
task is finally executed, the callback function logs the value of i.
However, since the value of i is now 5, each timer task logs 5 instead of
the expected values 0, 1, 2, 3, and 4.

Therefore, the output of the code is five lines of 5.

To avoid this behavior, you can use let instead of var to declare i, as let
creates a new binding for each iteration of the loop:

for (let i = 0; i < 5; i++) {


setTimeout(() => console.log(i), 1000);
}

This will result in the expected output of five lines, each with a value
from 0 to 4.

You might also like