
- World-Wide-Web Codes:
- JavaScript
- JS Introduction
- JS New Features
- Stylish Calculator
- JS-Calculator-Project
- Discover How to Benefit Devtools

Front End Developers-Lab

(JS) JavaScript
Top 6 Interview Questions and Anwsers
How it works setTimeout() in JavaScript?
In JavaScript, setTimeout() is a function that allows you to execute a piece of code after a specified delay.
How it works:
setTimeout(() => {
console.log("Hello, World!");
}, 2000); // 2000 milliseconds (2 seconds)
Explanation:
The first argument to setTimeout() is the function to be executed.
It can be an anonymous function like in the example or a named function.
The second argument is the delay, in milliseconds.
The function will be executed once after the specified delay.
Important Points:
Asynchronous behavior:
setTimeout() is asynchronous, meaning it does not block the execution of other code while waiting for the delay to expire.
Returning a timer ID:
setTimeout() returns a unique identifier that can be used to cancel the timeout using the clearTimeout() function.
Passing arguments to the function:
You can pass arguments to the function by including them after the delay argument:
JavaScript:::code
function greet(name) {
console.log(`Hello, ${name}!`);
}
setTimeout(greet, 1000, "Alice"); // Output: Hello, Alice!
::::::::::::::::ex-2::::::
Callback Function:
You pass a function (or a reference to a function) as the first argument to setTimeout(). This is the code that you want to execute after the delay.
Delay:
The second argument is the delay in milliseconds (1000 milliseconds = 1 second). This determines how long the browser should wait before executing the callback function.
Asynchronous Execution:
setTimeout() is an asynchronous function, meaning that it doesn't block the execution of other code. Instead, it schedules the callback function to be executed at a later time.
Event Loop:
When you call setTimeout(), the browser's JavaScript engine adds the callback function and delay to a queue. The engine then continues executing the rest of the code without waiting for the delay to expire.
Execution:
Once the specified delay has passed, the JavaScript engine takes the callback function from the queue and executes it.
Example: JavaScript
How it works:
setTimeout(() => {
console.log("Hello, World!");
}, 2000); // 2000 milliseconds (2 seconds)
Explanation:
The first argument to setTimeout() is the function to be executed.
It can be an anonymous function like in the example or a named function.
The second argument is the delay, in milliseconds.
The function will be executed once after the specified delay.
Important Points:
Asynchronous behavior:
setTimeout() is asynchronous, meaning it does not block the execution of other code while waiting for the delay to expire.
Returning a timer ID:
setTimeout() returns a unique identifier that can be used to cancel the timeout using the clearTimeout() function.
Passing arguments to the function:
You can pass arguments to the function by including them after the delay argument:
JavaScript:::code
function greet(name) {
console.log(`Hello, ${name}!`);
}
setTimeout(greet, 1000, "Alice"); // Output: Hello, Alice!
::::::::::::::::ex-2::::::
Callback Function:
You pass a function (or a reference to a function) as the first argument to setTimeout(). This is the code that you want to execute after the delay.
Delay:
The second argument is the delay in milliseconds (1000 milliseconds = 1 second). This determines how long the browser should wait before executing the callback function.
Asynchronous Execution:
setTimeout() is an asynchronous function, meaning that it doesn't block the execution of other code. Instead, it schedules the callback function to be executed at a later time.
Event Loop:
When you call setTimeout(), the browser's JavaScript engine adds the callback function and delay to a queue. The engine then continues executing the rest of the code without waiting for the delay to expire.
Execution:
Once the specified delay has passed, the JavaScript engine takes the callback function from the queue and executes it.
Example: JavaScript
function greet(name) {
console.log("Hello, " + name + "!");
}
setTimeout(greet, 2000, "John");
// Call greet after 2 seconds
console.log("This line executes immediately.");
:::::::::::::::Output:
Code
This line executes immediately.
Hello, John! // After 2 seconds
Important Points:
Clearing Timeout:
You can cancel a setTimeout()
call using the clearTimeout() function,
passing the timeout ID returned
by setTimeout() as an argument.
Arguments:
You can pass additional arguments to
the callback function after
the delay argument.
Multiple Timeouts:
You can use multiple setTimeout()
calls to schedule different functions
to execute at different times.
Use Cases:
setTimeout() is commonly used for things
like:Delayed animations Showing messages
after a certain period Simulating
network delays for testing purposes
Example of Multiple Timeouts
setTimeout(gfg1, 2000);
function gfg1() {
console.log("gfg1");
}
function gfg() {
console.log("gfg");
}
setInterval(gfg, 1000);
Output:
gfg
gfg1
gfg
......
1- What is this , bind?
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Example
Example
//JavaScript Demo: Function.bind() var module = { x: 42, getX: function() { return this.x; } } var unboundGetX = module.getX; console.log(unboundGetX()); //The function gets invoked at the global scope // expected output: undefined var boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // expected output: 42
2- What Are Javascript Data Types?
JavaScript supports three Primary, two Composite and two Special data types.
Next, we list down the data types in each of the categories.
Primary Data Types.
String
Number
Boolean
Composite Data Types.
Object
Array
Special Data Types.
Null
Undefined
Next, we list down the data types in each of the categories.
Primary Data Types.
String
Number
Boolean
Composite Data Types.
Object
Array
Special Data Types.
Null
Undefined
3- What Are The Different Ways To Create An Array In Javascript?
There are two main ways to create an array in JavaScript.
1. Using An Array Initializer (Array Literal). The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square brackets.
Let's see some examples.
The Array constructor method has three different syntaxes. If we call the constructor with two or more arguments, it declares an array with array elements also initialized. If we provide only one argument to the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the constructor without any argument creates an array with its length set to zero with elements not initialized.
Let's see some examples.
1. Using An Array Initializer (Array Literal). The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square brackets.
Let's see some examples.
var myArray1 = [1,2,3,4,5] // an array with 5 elements var myArray2 = [5] // an array with 1 element var myArray3 = [true,'Hi',[7]] // element types need not be the same.2. Using The Array Constructor.
The Array constructor method has three different syntaxes. If we call the constructor with two or more arguments, it declares an array with array elements also initialized. If we provide only one argument to the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the constructor without any argument creates an array with its length set to zero with elements not initialized.
Let's see some examples.
var myArray4 = new Array(1,2,3,4,5) // an array with 5 elements var myArray5 = new Array(20) // an empty array of length 20 var myArray6 = new Array() // an empty array of length 0
4- What Are Javascript Cookies?
A cookie is a piece of data which is sent from a website (that owns the requested web page) and gets stored locally by the browser at the user end. Cookies are needed because HTTP protocol which arranges for the transfer of web pages to your browser, is stateless. It means that HTTP has no way to keep track of the activities performed by the user at an earlier point in time. One way to resolve this issue is by using cookies. It contains the following data.
* A name-value pair containing the actual data
* An expiry date after which the cookie is no longer valid
* The domain and path of the server it should be sent to
When a request arrives at the server for a web page that maintains a cookie, the server appends the cookie to the HTTP header to send it across. The server-side programs can then read out the information included in it and decide that you have the right to view the page or not and other user preferences. Thus, every time you visit the site that maintains the cookies, your information is available there.
* A name-value pair containing the actual data
* An expiry date after which the cookie is no longer valid
* The domain and path of the server it should be sent to
When a request arrives at the server for a web page that maintains a cookie, the server appends the cookie to the HTTP header to send it across. The server-side programs can then read out the information included in it and decide that you have the right to view the page or not and other user preferences. Thus, every time you visit the site that maintains the cookies, your information is available there.
5- Write a function in ES6 which takes id as argument and find the name based on id
var findUser = function(id) {
var theData = {
"users": [{
"id": "661", "name": "ford" },
{ "id": "11", "name": "Jama", },
{ "id": "100", "name": "Jay", },
{ "id": "110", "name": "amina",},
{ "id": "120", "name": "Joe",},
{ "id": "1", "name": "cali", },
{ "id": "657", "name": "ruun", },
{ "id": "654", "name": "layla", },
{ "id": "653", "name": "Mj", },
{ "id": "650", "name": "queen", }
]
};
for (var i = 0; i < theData.users.length; i++) {
var user = theData.users[i];
if (user.id === id)
return user.name;
}
}
console.log(findUser("11"));
//output jama
var theData = {
"users": [{
"id": "661", "name": "ford" },
{ "id": "11", "name": "Jama", },
{ "id": "100", "name": "Jay", },
{ "id": "110", "name": "amina",},
{ "id": "120", "name": "Joe",},
{ "id": "1", "name": "cali", },
{ "id": "657", "name": "ruun", },
{ "id": "654", "name": "layla", },
{ "id": "653", "name": "Mj", },
{ "id": "650", "name": "queen", }
]
};
for (var i = 0; i < theData.users.length; i++) {
var user = theData.users[i];
if (user.id === id)
return user.name;
}
}
console.log(findUser("11"));
//output jama
6- Write javascript code to deeply clone an object.
Fast cloning with data loss - JSON.parse/stringify
If you do not use Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object,
a very simple one liner to deep clone an object is:
JSON.parse(JSON.stringify(object))
const a = {
string: 'string',
number: 123,
bool: false,
nul: null,
date: new Date(), // stringified
undef: undefined, // lost
inf: Infinity, // forced to 'null'
re: /.*/, // lost }
console.log(a);
console.log(typeof a.date); // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date);
// result of .toISOString()
If you do not use Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object,
a very simple one liner to deep clone an object is:
JSON.parse(JSON.stringify(object))
const a = {
string: 'string',
number: 123,
bool: false,
nul: null,
date: new Date(), // stringified
undef: undefined, // lost
inf: Infinity, // forced to 'null'
re: /.*/, // lost }
console.log(a);
console.log(typeof a.date); // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date);
// result of .toISOString()