Faq JS 2
Faq JS 2
Faq JS 2
_____________________________________________
__
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.
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"
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?
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.
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.
In this example, when the button is clicked, the alert function will be
called and the message "Button clicked!" will be displayed.
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.
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.
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.
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 .
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.
for...of loop is not just limited to arrays, it can also be used with any
other object that implements the iterable interface.
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):
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:
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.
JavaScript objects and JSON (JavaScript Object Notation) are both used
to represent data in JavaScript, but they have some key differences.
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
{
"firstName": "John",
"lastName": "Doe",
"age": 30
}
for(var i=0;i<10;i++) {
setTimeout(function() {
console.log(i);
}, 1000)
}
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
for(var i=0;i<10;i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 1000 * i)
})(i);
}
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)
}
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.
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(data => {
})
.catch(error => {
console.error('Error:', error);
});
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
If there is any error in fetching the file it will be caught by the catch
block.
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.
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.
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.
Here is an example of how you might swap the values of two variables a
and b in JavaScript without using a temporary variable:
In this example, the values of a and b are swapped by using the following
three steps:
Please note that this is a pseudo-code, in practice you don't need to use
console.log and can just swap the variables.
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.
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.
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.
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:
This will result in the expected output of five lines, each with a value
from 0 to 4.