Ans. The basic syntax of JavaScript consists of statements that are executed in order. A statement can be a variable declaration, a function call, or a control structure. JavaScript statements end with a semicolon (;
). For example:
let x = 5; // Variable declaration
console.log(x); // Function call
Ans. JavaScript has several data types, which can be categorized into two groups:
String
: Represents text, e.g., "Hello"
.Number
: Represents numeric values, e.g., 42
.Boolean
: Represents true or false values.Undefined
: A variable that has been declared but not assigned a value.Null
: Represents the intentional absence of any object value.Symbol
: A unique and immutable value, introduced in ES6.Object
: A collection of key-value pairs.Array
: A special type of object used to store ordered collections.Ans. You can define a function in JavaScript using the function
keyword. Functions can be defined in several ways, including function declarations and function expressions. For example:
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Outputs: Hello, Alice
Ans. JavaScript provides several types of loops for iterating over data:
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value); // Outputs: 1, 2, 3
}
const obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key + ": " + obj[key]); // Outputs: a: 1, b: 2
}
let
, const
, and var
?Ans. The differences between let
, const
, and var
are:
var
: Function-scoped or globally-scoped, can be re-declared and updated.let
: Block-scoped, can be updated but not re-declared in the same scope.const
: Block-scoped, cannot be updated or re-declared. It must be initialized at the time of declaration.Ans. You can handle errors in JavaScript using try...catch
statements. This allows you to catch exceptions and handle them gracefully. For example:
try {
// Code that may throw an error
throw new Error("Something went wrong!");
} catch (error) {
console.error(error.message); // Outputs: Something went wrong!
}
Ans. ==
is the equality operator that compares values after performing type coercion. ===
is the strict equality operator that checks both value and type.
console.log(5 == '5'); // true
console.log(5 === '5'); // false
Ans. Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. Only declarations are hoisted, not initializations.
console.log(x); // undefined
var x = 5;
Ans. A closure is a function that has access to its own scope, the scope of the outer function, and the global scope.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Ans. The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page as a tree structure where each node is an object.
Ans. A JavaScript Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It has three states: pending, fulfilled, and rejected.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 1000);
});
promise.then(result => console.log(result)); // Outputs: Success!
Ans. async
and await
are syntactic sugar built on Promises that make asynchronous code look and behave more like synchronous code.
async function fetchData() {
try {
const response = await fetch("https://api.example.com");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Ans. Event bubbling means the event propagates from the target element up to the root, while capturing (or trickling) means it goes from the root down to the target. You can control this with the third argument in addEventListener
.
Ans. undefined
means a variable has been declared but not assigned a value. null
is an assignment value that represents no value or object.
Ans. A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete a task.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
greet("Alice", () => console.log("Callback executed"));
Ans. An IIFE is a function that runs as soon as it is defined.
(function() {
console.log("IIFE executed!");
})();
this
keyword work in JavaScript?Ans. this
refers to the object from where it was called. Its value depends on the context in which it is used (global, object, strict mode, etc.).
Ans. Higher-order functions are functions that can take other functions as arguments or return them.
function higherOrder(fn) {
return function(value) {
return fn(value);
};
}
Ans. JavaScript modules allow you to split code into separate files and import/export them. This improves maintainability and reusability.
// module.js
export const greet = () => console.log("Hello");
// main.js
import { greet } from './module.js';
greet();
Ans. All three methods change the context of this
:
call()
: calls the function immediately with arguments listed.apply()
: same as call, but arguments are passed as an array.bind()
: returns a new function with a bound context.Ans. Event delegation is a technique in which a parent element handles events for its child elements using event bubbling. This is useful for dynamically added elements.
document.getElementById("parent").addEventListener("click", function(e) {
if (e.target && e.target.matches("button.classname")) {
console.log("Button clicked!");
}
});
Ans. Arrow functions are a shorter syntax for writing functions and do not bind their own this
. They are best used for callbacks or methods that don’t require their own context.
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
Ans. In JavaScript, objects inherit from other objects via the prototype chain. This allows sharing methods and properties between objects.
const parent = {
greet() {
console.log("Hello from parent");
}
};
const child = Object.create(parent);
child.greet(); // Outputs: Hello from parent
Ans. Synchronous code runs line-by-line, blocking the next operation until the current one finishes. Asynchronous code can execute non-blocking operations using callbacks, promises, or async/await.
new
keyword?Ans. The new
keyword creates an instance of an object with a constructor function and sets up the prototype chain.
function Person(name) {
this.name = name;
}
const person1 = new Person("Alice");
Object.freeze()
?Ans. Object.freeze()
makes an object immutable, preventing new properties from being added or existing properties from being changed or removed.
const obj = Object.freeze({ name: "John" });
obj.name = "Doe"; // No effect
Ans. Template literals are strings that allow embedded expressions and multi-line strings using backticks (`
).
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting);
Ans. The spread operator (...
) expands elements of an iterable (like an array) into individual elements.
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
Ans. Destructuring is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.
// Array destructuring
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
// Object destructuring
const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name); // Alice
console.log(age); // 25
Ans. There are several ways to create objects in JavaScript:
const obj = { name: "Alice" };
new Object()
syntax:const obj = new Object();
obj.name = "Alice";
function Person(name) {
this.name = name;
}
const person = new Person("Alice");
Object.create()
:const parent = { greet() { console.log("Hello"); } };
const child = Object.create(parent);
child.greet(); // Hello
class Person {
constructor(name) {
this.name = name;
}
}
const p = new Person("Alice");
Ans. ==
compares values after type conversion (loose equality), while ===
compares both value and type (strict equality).
console.log(5 == "5"); // true
console.log(5 === "5"); // false
Ans. A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
const promise = new Promise((resolve, reject) => {
resolve("Success");
});
promise.then(result => console.log(result));
Ans. null
is an assigned value representing no value, while undefined
means a variable has been declared but not assigned a value.
let a;
console.log(a); // undefined
let b = null;
console.log(b); // null
Ans. The spread operator (...)
allows an iterable to be expanded into individual elements.
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]
Ans. Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
console.log(a); // undefined
var a = 5;
Ans. A callback function is passed as an argument to another function and is executed after the completion of that function.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
greet("Alice", () => console.log("Callback called!"));
Ans. var
is function-scoped, while let
and const
are block-scoped. const
cannot be reassigned.
var x = 10;
let y = 20;
const z = 30;
Ans. Event bubbling is a type of event propagation where the event starts from the deepest element and propagates up to the parent elements.
element.addEventListener('click', function() {
console.log('Clicked!');
}, false);
Ans. Arrow functions provide a concise syntax for writing functions and do not have their own this
.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
Ans. The bind()
method creates a new function with a specified this
value.
const obj = { name: "Alice" };
function greet() {
console.log(this.name);
}
const boundGreet = greet.bind(obj);
boundGreet(); // Alice
Ans. The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page structure as a tree of objects.
Ans. A closure is a function that retains access to its lexical scope even when executed outside that scope.
function outer() {
let x = 10;
return function inner() {
console.log(x);
};
}
const fn = outer();
fn(); // 10
Ans. Template literals are strings enclosed in backticks (`) that allow embedded expressions using ${}
.
const name = "Alice";
console.log(`Hello, ${name}`);
Ans. async
and await
are used to handle asynchronous operations in a more readable and synchronous-looking way.
async function getData() {
let data = await fetch('url');
console.log(data);
}
Ans. slice()
returns a shallow copy of an array, while splice()
modifies the original array.
let arr = [1, 2, 3, 4];
arr.slice(1, 3); // [2, 3]
arr.splice(1, 2); // [2, 3], arr becomes [1, 4]
Ans. The typeof
operator returns a string indicating the type of a variable.
console.log(typeof "Hello"); // string
console.log(typeof 5); // number
Ans. An IIFE is a function that runs as soon as it is defined.
(function() {
console.log("IIFE executed");
})();
Ans. Higher-order functions are functions that take other functions as arguments or return functions as results.
function greet(fn) {
fn();
}
greet(() => console.log("Hello!"));
Ans. map()
returns a new array with the results, while forEach()
executes a function but returns undefined.
const arr = [1, 2, 3];
const mapped = arr.map(x => x * 2); // [2, 4, 6]
arr.forEach(x => console.log(x)); // Logs 1 2 3
Ans. Function declarations are hoisted, while function expressions are not.
// Function Declaration
function greet() {
return "Hello";
}
// Function Expression
const greet = function() {
return "Hello";
};
Ans. Event delegation refers to the practice of attaching a single event listener to a parent element to handle events for child elements.
document.querySelector("#parent").addEventListener('click', function(event) {
if (event.target && event.target.matches("button.classname")) {
console.log("Button clicked");
}
});
Ans. The this
keyword refers to the context in which a function is called. It can refer to an object, global context, or the calling function itself.
function greet() {
console.log(this);
}
const obj = { greet };
obj.greet(); // 'this' refers to 'obj'
Ans. Synchronous code runs sequentially, blocking further execution until the current task completes. Asynchronous code allows other operations to run while waiting for an operation to complete.
// Synchronous
console.log("Start");
console.log("End");
// Asynchronous
console.log("Start");
setTimeout(() => console.log("End"), 1000);
Ans. The call()
method allows a function to be invoked with a specified this
value and arguments passed individually.
function greet(name) {
console.log(`Hello, ${name}`);
}
greet.call(null, "Alice"); // Hello, Alice
Ans. A generator function is a function that can be paused and resumed, using the yield
keyword to produce a sequence of values.
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const gen = numbers();
console.log(gen.next().value); // 1
Ans. The setTimeout()
method is used to execute a function after a specified delay (in milliseconds).
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
Ans. The eval()
function evaluates JavaScript code represented as a string.
eval("console.log('Hello from eval')");
Ans. localStorage
stores data with no expiration time, whereas sessionStorage
stores data for the duration of the page session.
localStorage.setItem("key", "value");
sessionStorage.setItem("key", "value");
Ans. A module in JavaScript is a file that contains code which can be exported and imported to use in other files.
// module.js
export const greet = () => "Hello";
// main.js
import { greet } from './module';
console.log(greet());
Ans. let
is block-scoped and does not allow redeclaration in the same scope, while var
is function-scoped and allows redeclaration.
let a = 10;
var b = 20;
console.log(a, b);
Ans. Errors can be handled using try...catch
blocks. The finally
block can be used to execute code regardless of success or failure.
try {
throw new Error("Something went wrong");
} catch (error) {
console.log(error.message);
} finally {
console.log("Always runs");
}
Ans. Default parameters allow you to set default values for function parameters if no value or undefined is passed.
function greet(name = "World") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, World
Ans. A promise chain is a sequence of promise handlers that are executed in order, where each handler returns a new promise.
fetch('/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
Ans. Object.assign()
is used to copy values from one or more source objects to a target object.
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = Object.assign({}, obj1, obj2);
console.log(merged); // { a: 1, b: 2 }
Ans. Destructuring allows unpacking values from arrays or properties from objects into distinct variables.
const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name, age); // Alice 25
Ans. Regular expressions are patterns used to match character combinations in strings.
const regex = /\d+/;
console.log(regex.test("123")); // true
Ans. The setInterval()
method calls a function or evaluates an expression at specified intervals (in milliseconds).
setInterval(() => {
console.log("Executed every 1 second");
}, 1000);
Ans. clearTimeout()
clears a timeout set with setTimeout()
, and clearInterval()
clears an interval set with setInterval()
.
const timeout = setTimeout(() => console.log("Hello"), 1000);
clearTimeout(timeout);
Ans. The apply()
method calls a function with a specified this
value and an array of arguments.
function greet(name) {
console.log(`Hello, ${name}`);
}
greet.apply(null, ["Alice"]); // Hello, Alice
Ans. ==
compares values after type conversion, while Object.is()
compares values without type conversion.
console.log(0 == -0); // true
console.log(Object.is(0, -0)); // false
Ans. An IIFE is a function that is defined and invoked immediately after its creation. It's typically used to create a private scope.
(function() {
console.log("I am an IIFE");
})();
Ans. The bind()
method creates a new function that, when invoked, has its this
value set to the provided value, and prepends the given arguments to the function.
function greet(name) {
console.log(`Hello, ${name}`);
}
const greetAlice = greet.bind(null, "Alice");
greetAlice(); // Hello, Alice
Ans. A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
Ans. The event loop is a mechanism that continuously checks if the call stack is empty and, if so, pushes messages from the event queue to the stack for execution.
console.log("Start");
setTimeout(() => console.log("Inside Timeout"), 0);
console.log("End");
Ans. The new
keyword is used to create a new instance of a constructor function or class.
function Person(name) {
this.name = name;
}
const john = new Person("John");
console.log(john.name); // John
Ans. Template literals are a way to define strings with embedded expressions. They are defined using backticks (`
) and support multi-line strings and string interpolation.
const name = "Alice";
console.log(`Hello, ${name}`); // Hello, Alice
Ans. The spread operator (...
) is used to unpack elements from an array or properties from an object into a new array or object.
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]
Ans. undefined
indicates that a variable has been declared but not assigned a value, while null
is a value that represents the intentional absence of any object value.
let x;
console.log(x); // undefined
let y = null;
console.log(y); // null
Ans. The Object.freeze()
method prevents modification of an object, including adding, deleting, or modifying its properties.
const obj = { a: 1 };
Object.freeze(obj);
obj.a = 2;
console.log(obj.a); // 1
Ans. Function declarations are hoisted to the top of their scope, while function expressions are not. Function expressions are created and assigned at runtime.
function declaration() { console.log("declaration"); } // Hoisted
const expression = function() { console.log("expression"); }; // Not hoisted
Ans. A shallow copy copies the references of objects, whereas a deep copy copies the objects and their nested properties.
const obj1 = { a: 1, b: { c: 2 } };
const shallowCopy = { ...obj1 };
const deepCopy = JSON.parse(JSON.stringify(obj1));
obj1.b.c = 3;
console.log(shallowCopy.b.c); // 3 (shallow copy)
console.log(deepCopy.b.c); // 2 (deep copy)
Ans. slice()
returns a shallow copy of a portion of an array, while splice()
modifies the original array by removing or adding elements.
const arr = [1, 2, 3, 4];
const slicedArr = arr.slice(1, 3); // [2, 3]
arr.splice(1, 2); // Removes 2 and 3, arr becomes [1, 4]
Ans. The map()
method creates a new array populated with the results of applying a given function to each element of the array.
const arr = [1, 2, 3];
const doubled = arr.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
Ans. The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
const arr = [1, 2, 3, 4];
const even = arr.filter(num => num % 2 === 0);
console.log(even); // [2, 4]
Ans. The reduce()
method applies a function to each element in an array (from left to right) to reduce it to a single value.
const arr = [1, 2, 3];
const sum = arr.reduce((acc, num) => acc + num, 0);
console.log(sum); // 6
Ans. The find()
method returns the first element in the array that satisfies the provided testing function.
const arr = [1, 2, 3, 4];
const found = arr.find(num => num > 2);
console.log(found); // 3
Ans. The every()
method checks if all elements in an array pass the test implemented by the provided function.
const arr = [1, 2, 3];
const allPositive = arr.every(num => num > 0);
console.log(allPositive); // true
Ans. The some()
method checks if at least one element in the array passes the test implemented by the provided function.
const arr = [1, 2, 3];
const somePositive = arr.some(num => num < 0);
console.log(somePositive); // false
Ans. The includes()
method checks if an array contains a certain element, returning true or false accordingly.
const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
Ans. The sort()
method sorts the elements of an array in place and returns the sorted array.
const arr = [3, 1, 2];
arr.sort();
console.log(arr); // [1, 2, 3]
Ans. The concat()
method is used to merge two or more arrays into one new array.
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]
Ans. The for...in
loop iterates over the keys of an object, while the for...of
loop iterates over the values of an iterable object like an array.
const arr = [1, 2, 3];
for (let value of arr) {
console.log(value); // 1 2 3
}
for (let key in arr) {
console.log(key); // 0 1 2
}
Ans. The try...catch
block is used to handle errors. The try
block contains the code that may throw an error, while the catch
block handles the error.
try {
throw new Error("Oops!");
} catch (error) {
console.log(error.message); // Oops!
}
Ans. You can use Array.isArray()
to check if a variable is an array.
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray({ a: 1 })); // false
Ans. The slice()
method returns a shallow copy of a portion of an array, while splice()
modifies the original array by adding/removing elements.
const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3); // [2, 3]
arr.splice(1, 2); // arr becomes [1, 4]
Ans. The async/await
syntax is used for handling asynchronous code in a more readable way. async
makes a function return a promise, and await
pauses the function execution until the promise is resolved.
async function fetchData() {
const response = await fetch("/data");
const data = await response.json();
console.log(data);
}
Ans. A debounce function limits the rate at which a function is invoked, ensuring that the function is not executed too frequently within a specified interval.
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), delay);
};
}
Ans. JavaScript handles asynchronous operations using callbacks, promises, and async/await. These mechanisms allow the program to continue executing while waiting for a response from an asynchronous operation.
Ans. A promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three states: pending, resolved, and rejected.
let promise = new Promise((resolve, reject) => {
resolve("Success");
});
promise.then(result => console.log(result)); // Success
Ans. A class in JavaScript is created using the class
keyword. A class can have a constructor and methods.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
const person = new Person("Alice");
person.greet(); // Hello, Alice