Showing 50 question(s)
Answer:
JavaScript is a high-level, interpreted programming language primarily used to create interactive web applications. It supports object-oriented, functional, and event-driven programming and runs in browsers as well as on servers using Node.js.
Code Example:
console.log("Hello, JavaScript!");Answer:
var is function-scoped and can be redeclared. let is block-scoped and can be reassigned but not redeclared. const is block-scoped and cannot be reassigned after initialization.
Code Example:
var a = 10;
let b = 20;
b = 30;
const PI = 3.14;
// PI = 4; // ErrorAnswer:
JavaScript has seven primitive data types: String, Number, BigInt, Boolean, Undefined, Null, and Symbol.
Code Example:
let name = "John";
let age = 25;
let isActive = true;
let salary = 100n;
let value = null;
let data;
let id = Symbol("id");Answer:
Hoisting is JavaScript's default behavior of moving declarations to the top of their scope before execution. Only declarations are hoisted, not initializations.
Code Example:
console.log(a);
var a = 10;
// Equivalent to:
// var a;
// console.log(a);
// a = 10;Answer:
Function declarations are hoisted completely, while function expressions are assigned to variables and are not fully hoisted.
Code Example:
// Function Declaration
function greet() {
console.log("Hello");
}
// Function Expression
const welcome = function() {
console.log("Welcome");
};Answer:
Arrow functions were introduced in ES6. They provide a shorter syntax for writing functions and do not have their own this value.
Code Example:
const add = (a, b) => {
return a + b;
};
console.log(add(5, 3));Answer:
Variables declared outside functions belong to the global scope, while variables declared inside functions or blocks belong to the local scope.
Code Example:
let message = "Global";
function display() {
let text = "Local";
console.log(text);
}
display();
console.log(message);Answer:
The == operator compares values after type conversion, whereas === compares both value and data type without type coercion.
Code Example:
console.log(5 == "5"); // true
console.log(5 === "5"); // falseAnswer:
A callback is a function passed as an argument to another function. It is executed after the completion of a specific task.
Code Example:
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
greet("John", () => {
console.log("Completed");
});Answer:
Objects are collections of key-value pairs used to store related data and functionality.
Code Example:
const employee = {
name: "Alice",
age: 28,
display() {
console.log(this.name);
}
};
employee.display();Answer:
map() transforms every element and returns a new array, filter() returns elements that satisfy a condition, and reduce() combines all elements into a single value.
Code Example:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
const even = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(doubled);
console.log(even);
console.log(sum);Answer:
forEach() executes a function for each array element without returning a new array, whereas map() returns a new transformed array.
Code Example:
const numbers = [1, 2, 3];
numbers.forEach(n => console.log(n));
const squares = numbers.map(n => n * n);
console.log(squares);Answer:
A string can be reversed by converting it into an array, reversing the array, and joining it back into a string.
Code Example:
const text = "JavaScript";
const reversed = text
.split("")
.reverse()
.join("");
console.log(reversed);Answer:
Object destructuring is an ES6 feature that extracts properties from an object into variables.
Code Example:
const person = {
name: "John",
age: 30
};
const { name, age } = person;
console.log(name);
console.log(age);Answer:
Array destructuring extracts array values into separate variables using ES6 syntax.
Code Example:
const colors = ["Red", "Green", "Blue"];
const [first, second] = colors;
console.log(first);
console.log(second);Answer:
The spread operator expands arrays or objects, while the rest operator collects multiple values into a single array.
Code Example:
const nums = [1,2,3];
const copy = [...nums];
function sum(...values){
return values.reduce((a,b)=>a+b);
}
console.log(copy);
console.log(sum(10,20,30));Answer:
Default parameters allow function parameters to have predefined values when no argument is passed.
Code Example:
function greet(name = "Guest"){
console.log("Hello " + name);
}
greet();
greet("Alice");Answer:
Template literals use backticks (`) and allow embedded expressions using ${}. They support multi-line strings and string interpolation.
Code Example:
const name = "John";
const age = 25;
console.log(`${name} is ${age} years old.`);Answer:
The this keyword refers to the object that is currently executing the function. Its value depends on how the function is called.
Code Example:
const user = {
name: "Alice",
greet() {
console.log(this.name);
}
};
user.greet();Answer:
An IIFE is a function that executes immediately after it is defined. It is commonly used to create a private scope.
Code Example:
(function () {
console.log("IIFE executed");
})();Answer:
A Promise represents the eventual completion or failure of an asynchronous operation. It has three states: Pending, Fulfilled, and Rejected.
Code Example:
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation Successful");
} else {
reject("Operation Failed");
}
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));Answer:
async/await provides a cleaner syntax for working with Promises. An async function always returns a Promise, and await pauses execution until the Promise resolves.
Code Example:
function fetchData() {
return Promise.resolve("Data Loaded");
}
async function loadData() {
const result = await fetchData();
console.log(result);
}
loadData();Answer:
The Event Loop allows JavaScript to perform non-blocking asynchronous operations by handling the call stack, callback queue, and microtask queue.
Code Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
// Output:
// Start
// End
// Promise
// TimeoutAnswer:
The Document Object Model (DOM) is a tree-like representation of an HTML document that allows JavaScript to access and manipulate web page elements.
Code Example:
const heading = document.getElementById("title");
heading.textContent = "Welcome to JavaScript";Answer:
Event delegation is a technique where a parent element handles events for its child elements using event bubbling.
Code Example:
document.getElementById("list")
.addEventListener("click", function(event) {
if(event.target.tagName === "LI"){
console.log(event.target.textContent);
}
});Answer:
localStorage stores data permanently until removed, while sessionStorage stores data only for the current browser session.
Code Example:
localStorage.setItem("user", "John");
sessionStorage.setItem("theme", "dark");
console.log(localStorage.getItem("user"));Answer:
JSON (JavaScript Object Notation) is a lightweight data-interchange format commonly used to exchange data between a client and server.
Code Example:
const person = {
name: "John",
age: 25
};
const json = JSON.stringify(person);
const obj = JSON.parse(json);
console.log(obj);Answer:
The Fetch API is used to make HTTP requests and returns a Promise containing the server response.
Code Example:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));Answer:
A closure is created when a function remembers variables from its outer scope even after the outer function has finished executing.
Code Example:
function counter() {
let count = 0;
return function () {
count++;
return count;
};
}
const increment = counter();
console.log(increment());
console.log(increment());Answer:
Every JavaScript object has a prototype. Objects inherit properties and methods from their prototype, enabling prototype-based inheritance.
Code Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log("Hello " + this.name);
};
const user = new Person("Alice");
user.greet();Answer:
JavaScript modules allow code to be split into reusable files. ES6 modules use export to expose functionality and import to use it in other files.
Code Example:
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from "./math.js";
console.log(add(5, 10));Answer:
Named exports allow exporting multiple members from a module, while a default export exports only one primary value from the module.
Code Example:
// utils.js
export const PI = 3.14;
export function square(x) {
return x * x;
}
export default function greet() {
console.log("Hello");
}Answer:
Object.freeze() prevents adding, removing, or modifying properties of an object, making it immutable.
Code Example:
const person = {
name: "John"
};
Object.freeze(person);
// person.name = "David"; // Ignored
console.log(person);Answer:
Object.seal() prevents adding or deleting object properties, but existing properties can still be modified.
Code Example:
const car = {
brand: "BMW"
};
Object.seal(car);
car.brand = "Audi";
console.log(car);Answer:
ES6 introduced the class keyword as syntactic sugar over prototype-based inheritance, making object-oriented programming easier.
Code Example:
class Employee {
constructor(name) {
this.name = name;
}
display() {
console.log(this.name);
}
}
const emp = new Employee("Alice");
emp.display();Answer:
Inheritance allows one class to inherit properties and methods from another class using the extends keyword.
Code Example:
class Animal {
speak() {
console.log("Animal speaks");
}
}
class Dog extends Animal {
bark() {
console.log("Dog barks");
}
}
const dog = new Dog();
dog.speak();
dog.bark();Answer:
JavaScript uses try, catch, finally, and throw to handle runtime errors gracefully.
Code Example:
try {
throw new Error("Something went wrong");
}
catch(error) {
console.log(error.message);
}
finally {
console.log("Execution completed");
}Answer:
Map allows keys of any type, maintains insertion order, and provides better performance for frequent additions/removals. Objects mainly use string or symbol keys.
Code Example:
const map = new Map();
map.set("name", "John");
map.set(1, "One");
console.log(map.get("name"));Answer:
A Set is a collection of unique values. Duplicate values are automatically ignored.
Code Example:
const numbers = new Set();
numbers.add(10);
numbers.add(20);
numbers.add(10);
console.log(numbers);Answer:
JavaScript automatically frees memory occupied by objects that are no longer reachable. Modern JavaScript engines use the Mark-and-Sweep algorithm for garbage collection.
Code Example:
let person = {
name: "John"
};
person = null;
// The original object becomes eligible
// for garbage collection.Answer:
A Map allows keys of any type and can be iterated. A WeakMap only accepts objects as keys, holds weak references to them, and is not iterable.
Code Example:
const user = {};
const weakMap = new WeakMap();
weakMap.set(user, "Admin");
console.log(weakMap.get(user));Answer:
A Set can store any value and is iterable, while a WeakSet stores only objects, is not iterable, and allows garbage collection of its elements.
Code Example:
const obj = {};
const weakSet = new WeakSet();
weakSet.add(obj);
console.log(weakSet.has(obj));Answer:
Generator functions can pause and resume execution using the yield keyword. They return an iterator object.
Code Example:
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const iterator = numbers();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());Answer:
Promise.all() executes multiple promises in parallel and resolves only when all promises are fulfilled. If any promise rejects, the entire operation fails.
Code Example:
const p1 = Promise.resolve("A");
const p2 = Promise.resolve("B");
Promise.all([p1, p2])
.then(result => console.log(result));Answer:
Promise.race() returns the result of the first promise that settles, whether it resolves or rejects.
Code Example:
const p1 = new Promise(resolve =>
setTimeout(() => resolve("First"), 1000)
);
const p2 = new Promise(resolve =>
setTimeout(() => resolve("Second"), 2000)
);
Promise.race([p1, p2])
.then(result => console.log(result));Answer:
slice() returns a new array without modifying the original array, whereas splice() modifies the original array by adding, removing, or replacing elements.
Code Example:
const numbers = [1,2,3,4,5];
console.log(numbers.slice(1,3));
numbers.splice(2,1);
console.log(numbers);Answer:
These ES6 string methods check whether a string starts with, ends with, or contains a specified substring.
Code Example:
const text = "JavaScript";
console.log(text.startsWith("Java"));
console.log(text.endsWith("Script"));
console.log(text.includes("Script"));Answer:
Optional chaining safely accesses nested object properties without throwing an error if an intermediate property is null or undefined.
Code Example:
const user = {
profile: {
name: "Alice"
}
};
console.log(user.profile?.name);
console.log(user.address?.city);Answer:
The nullish coalescing operator returns the right-hand value only when the left-hand value is null or undefined.
Code Example:
const username = null;
const name = username ?? "Guest";
console.log(name);Answer:
Use let and const instead of var, write modular code, avoid global variables, handle errors properly, use strict equality (===), prefer async/await over callbacks, validate user input, and follow consistent coding standards.
Code Example:
// Good Practices
const API_URL = "https://api.example.com";
async function fetchUsers() {
try {
const response = await fetch(API_URL);
const users = await response.json();
console.log(users);
}
catch (error) {
console.error(error);
}
}