Under construction
Write a program to find element occurrence in an array
Input:
Output:
Answer
The code iterates through the array and uses an object count
to keep track of the occurrences of each element. The final output is {1: 3, 2: 1, 3: 1, 4: 1}
, indicating how many times each number appears in the array.
Write a program to remove duplicate items from an array
Input:
Output:
Answer
or just do
The code iterates through the array and pushes each element into the new array b
only if it is not already present in b
. This removes duplicate elements and results in [1, 2, 3, 4]
.
Flatten a nested array to a specified depth.
Write a function that takes two arguments: a nested array and a number representing the depth to flatten. The function should return a new array that is flattened up to the specified depth.
Answer
explanation
Write a program for the following output using arrow function
Input:
Output:
Answer
The arrow function syntax achieves the same result as the normal function, where call(2)(4)(6)
multiplies the three numbers together, resulting in 48
.
Write a program to return resolve if value is less than 7 using Promise
Input:
Output:
Answer
OR this way also possible
Explain await
key word in Javascript
Answer
The await
keyword in JavaScript is used to pause the execution of an asynchronous function until a Promise is resolved or rejected. It can only be used inside an async
function.
Key Points:
-
Asynchronous Functions:
await
is used within functions declared with theasync
keyword.- An
async
function always returns a Promise.
-
Pausing Execution:
- When
await
is used with a Promise, it pauses the execution of theasync
function until the Promise is settled (either resolved or rejected).
- When
-
Simplifying Promise Handling:
await
makes asynchronous code look and behave more like synchronous code, reducing the complexity of chainingthen()
methods.
Example:
Without await
:
With await
:
Error Handling:
You can use try...catch
blocks to handle errors when using await
.
Example:
Write an async function using promises in JavaScript
Answer
Write a program to multiply two numbers without using the multiply sign in JavaScript
Input:
Expected Output:
Answer
Write a program to sort an array in ascending order
Input:
Expected Output:
Answer
or