Variables and Data Types
- Question: How do you declare a variable in JavaScript?
Answer:
let x;
- Question: What is the difference between
let
andconst
?
Answer:
// `let` allows you to reassign values to a variable.
let a = 10;
a = 20; // No error
// `const` does not allow reassignment.
const b = 10;
// b = 20; // Error
- Question: What are the primitive data types in JavaScript?
Answer:
// Number, String, Boolean, Undefined, Null, Symbol, BigInt
- Question: How do you check the type of a variable?
Answer:
console.log(typeof 42); // "number"
- Question: What will
console.log(typeof null)
output?
Answer:
console.log(typeof null); // "object"
- Question: How do you convert a string to a number in JavaScript?
Answer:
let num = Number("123"); // 123
- Question: How do you declare a constant in JavaScript?
Answer:
const PI = 3.14;
- Question: What is
undefined
in JavaScript?
Answer:
// A variable that has been declared but not assigned a value is `undefined`.
let a;
console.log(a); // undefined
- Question: What is the difference between
null
andundefined
?
Answer:
// `undefined` means a variable has been declared but not assigned a value.
// `null` is an assignment value that represents no value or no object.
- Question: How do you concatenate two strings in JavaScript?
Answer:javascript let str1 = "Hello, "; let str2 = "World!"; let result = str1 + str2; // "Hello, World!"
Operators and Expressions
- Question: What is the difference between
==
and===
?
Answer:
// `==` checks for equality with type coercion.
console.log(5 == '5'); // true
// `===` checks for equality without type coercion.
console.log(5 === '5'); // false
- Question: What will
console.log(10 % 3)
output?
Answer:
console.log(10 % 3); // 1
- Question: How do you increment and decrement a variable?
Answer:
let x = 10;
x++; // 11
x--; // 10
- Question: What is the result of
true && false
?
Answer:
console.log(true && false); // false
- Question: What is the result of
true || false
?
Answer:
console.log(true || false); // true
- Question: How do you use the ternary operator in JavaScript?
Answer:
let age = 18;
let canVote = age >= 18 ? 'Yes' : 'No';
console.log(canVote); // "Yes"
- Question: What does
!true
evaluate to?
Answer:
console.log(!true); // false
- Question: How do you add two numbers in JavaScript?
Answer:
let sum = 5 + 10; // 15
- Question: How do you multiply two numbers in JavaScript?
Answer:
let product = 5 * 10; // 50
- Question: What is the result of
2 ** 3
in JavaScript?
Answer:javascript console.log(2 ** 3); // 8
Functions and Scope
- Question: How do you declare a function in JavaScript?
Answer:
function greet() {
console.log("Hello!");
}
- Question: What is a function expression?
Answer:
const greet = function() {
console.log("Hello!");
};
- Question: What is the difference between function declarations and function expressions?
Answer:
// Function declarations are hoisted to the top of their scope.
function greet() {
console.log("Hello!");
}
// Function expressions are not hoisted.
const greet = function() {
console.log("Hello!");
};
- Question: How do you create an immediately invoked function expression (IIFE)?
Answer:
(function() {
console.log("This is an IIFE");
})();
- Question: What is the scope of a variable declared with
var
?
Answer:
// Variables declared with `var` are function-scoped.
function test() {
var x = 10;
if (true) {
var y = 20;
}
console.log(y); // 20
}
- Question: What is the scope of a variable declared with
let
orconst
?
Answer:
// Variables declared with `let` and `const` are block-scoped.
function test() {
let x = 10;
if (true) {
let y = 20;
}
// console.log(y); // Error: y is not defined
}
- Question: How do you return a value from a function?
Answer:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
- Question: How do you pass arguments to a function?
Answer:
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice"); // "Hello, Alice"
- Question: What is a closure in JavaScript?
Answer:
// A closure is a function that has access to its own scope, the outer function's scope, and the global scope.
function outer() {
let outerVar = "Outer";
function inner() {
console.log(outerVar);
}
return inner;
}
let innerFunc = outer();
innerFunc(); // "Outer"
- Question: What is a higher-order function?
Answer:javascript // A higher-order function is a function that takes another function as an argument or returns a function. function higherOrder(func) { func(); } higherOrder(function() { console.log("Hello from the higher-order function"); });
Arrays and Objects
- Question: How do you create an array in JavaScript?
Answer:
let arr = [1, 2, 3];
- Question: How do you access the first element of an array?
Answer:
let arr = [1, 2, 3];
console.log(arr[0]); // 1
- Question: How do you add an element to the end of an array?
Answer:
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
- Question: How do you remove the last element of an array?
Answer:
let arr = [1, 2, 3];
arr.pop();
console.log(arr); // [1, 2, 3]
- Question: How do you create an object in JavaScript?
Answer:
let obj = {
name: "Alice",
age: 25
};
- Question: How do you access the value of a property in an object?
Answer:
let obj = {
name: "Alice",
age: 25
};
console.log(obj.name); // "Alice"
- Question: How do you add a property to an object?
Answer:
let obj = {
name: "Alice",
age: 25
};
obj.job = "Developer";
console.log(obj); // { name: "Alice", age: 25, job: "Developer" }
- Question: How do you remove a property from an object?
Answer:
let obj = {
name: "Alice",
age: 25
};
delete obj.age;
console.log(obj); // { name: "Alice" }
- Question: What method can be used to find the length of an array?
Answer:
let arr = [1, 2, 3];
console.log(arr.length); // 3
- Question: How do you iterate over an array using a
for
loop?
Answer:javascript let arr = [1, 2, 3]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
DOM Manipulation
- Question: How do you select an element by its ID?
Answer:
let element = document.getElementById('myElement');
- Question: How do you select elements by their class name?
Answer:
let elements = document.getElementsByClassName('myClass');
- Question: How do you select elements using a CSS selector?
Answer:
let elements = document.querySelectorAll('.myClass');
- Question: How do you change the text content of an element?
Answer:
let element = document.getElementById('myElement');
element.textContent = 'New Text';
- Question: How do you change the HTML content of an element?
Answer:
let element = document.getElementById('myElement');
element.innerHTML = '<strong>New HTML</strong>';
- Question: How do you add a class to an element?
Answer:
let element = document.getElementById('myElement');
element.classList.add('newClass');
- Question: How do you remove a class from an element?
Answer:
let element = document.getElementById('myElement');
element.classList.remove('oldClass');
- Question: How do you add an event listener to an element?
Answer:
let button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log('Button clicked');
});
- Question: How do you prevent the default action of an event?
Answer:
let link = document.getElementById('myLink');
link.addEventListener('click', function(event) {
event.preventDefault();
});
- Question: How do you stop event propagation?
Answer:javascript let button = document.getElementById('myButton'); button.addEventListener('click', function(event) { event.stopPropagation(); });
Promises and Asynchronous JavaScript
- Question: What is a promise in JavaScript?
Answer:
// A promise is an object that represents the eventual completion (or failure) of an asynchronous operation.
- Question: How do you create a new promise?
Answer:
let promise = new Promise((resolve, reject) => {
// Asynchronous operation
if (success) {
resolve(result);
} else {
reject(error);
}
});
- Question: How do you handle a fulfilled promise?
Answer:
promise.then(result => {
console.log(result);
});
- Question: How do you handle a rejected promise?
Answer:
promise.catch(error => {
console.log(error);
});
- Question: How do you execute code after a promise is settled, regardless of its outcome?
Answer:
promise.finally(() => {
console.log('Promise settled');
});
- Question: What does the
async
keyword do?
Answer:
// The `async` keyword makes a function return a promise.
async function fetchData() {
return "data";
}
- Question: What does the
await
keyword do?
Answer:
// The `await` keyword pauses the execution of an async function until the promise is resolved.
async function fetchData() {
let data = await fetch('url');
console.log(data);
}
- Question: How do you handle multiple promises in parallel?
Answer:
Promise.all([promise1, promise2]).then(results => {
console.log(results);
});
- Question: What does
Promise.race()
do?
Answer:
// `Promise.race()` returns a promise that resolves or rejects as soon as one of the promises in the array resolves or rejects.
Promise.race([promise1, promise2]).then(result => {
console.log(result);
});
- Question: How do you create a promise that resolves after a certain amount of time?
Answer:javascript function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } delay(1000).then(() => console.log('Resolved after 1 second'));
These questions and answers should provide a comprehensive review of fundamental and intermediate JavaScript concepts across various topics.