JavaScript Practice Questions and Answers
1) Question: What is the difference between var, let, and const?
Answer:
var -> Function scoped, can be re-declared and updated.
let -> Block scoped, can be updated but not re-declared in same scope.
const -> Block scoped, cannot be updated or re-declared.
--------------------------------------------
2) Question: Write a function to reverse a string.
Answer:
function reverseString(str) {
return [Link]('').reverse().join('');
}
--------------------------------------------
3) Question: What is a closure in JavaScript?
Answer:
A closure is a function that remembers variables from its outer scope
even after the outer function has finished executing.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
}
}
--------------------------------------------
4) Question: What is the difference between == and === ?
Answer:
== -> Compares values after type conversion.
=== -> Compares both value and type (strict equality).
--------------------------------------------
5) Question: Write a program to find the largest number in an array.
Answer:
function findMax(arr) {
return [Link](...arr);
}
--------------------------------------------
6) Question: What is event bubbling?
Answer:
Event bubbling is a mechanism where an event starts from the target element
and bubbles up to its parent elements in the DOM hierarchy.
--------------------------------------------
7) Question: Write a function to check if a number is prime.
Answer:
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return true;
}
--------------------------------------------
8) Question: What is async/await?
Answer:
async/await is used to handle asynchronous operations in a cleaner way
than promises. It makes asynchronous code look synchronous.
Example:
async function fetchData() {
const response = await fetch('[Link]
const data = await [Link]();
[Link](data);
}
--------------------------------------------
Practice Exercise:
1. Create a function that counts vowels in a string.
2. Create a program to remove duplicates from an array.
3. Create a simple calculator using functions.
4. Create a counter using closure.