JavaScript

1. What is the difference between == and === in JavaScript?

Answer:

== is the equality operator that compares two values for equality after performing type coercion. So, 2 == "2" is true.

=== is the strict equality operator that compares both the values and their types without type conversion. So, 2 === "2" is false.


2. Explain what closures are in JavaScript.

Answer: A closure is a function that retains access to its outer scope, even after the outer function has executed. It allows a function to have "private" variables.

Example:

function outer() {

    let count = 0;

    return function inner() {

        count++;

        console.log(count);

    };

}

const counter = outer();

counter(); // 1

counter(); // 2


3. What is the difference between let, var, and const?

Answer:

var: Function-scoped or globally scoped if not inside a function. It can be redeclared and updated.

let: Block-scoped (inside {}). It can be updated but not redeclared in the same scope.

const: Block-scoped like let, but it cannot be updated or redeclared. The value must be assigned during declaration.


4. How would you handle asynchronous code in JavaScript?

Answer: There are multiple ways to handle asynchronous code in JavaScript:

Callbacks: Functions passed as arguments to be executed later.

Promises: Objects representing eventual completion or failure of an asynchronous operation.

async/await: Modern syntax for handling promises more cleanly.

Example with Promises:

fetch('api/data')

  .then(response => response.json())

  .then(data => console.log(data))

  .catch(error => console.error(error));

  

5. What is the difference between null and undefined?

Answer:

undefined: A variable that has been declared but not assigned a value yet.

null: An assignment value that represents "no value" or "empty".


6. How does this keyword work in JavaScript?

Answer: The value of this depends on how a function is called:

Global Context: In the global context, this refers to the global object (window in browsers).

Object Method: Inside a method of an object, this refers to the object the method is called on.

Arrow Functions: this in arrow functions is lexically scoped, meaning it takes this from the surrounding code where the arrow function was defined.


7. Explain the concept of hoisting in JavaScript.

Answer: Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope before code execution. Only declarations are hoisted, not initializations.

console.log(a); // undefined

var a = 5;


8. What is the purpose of the Promise.all() method?

Answer: Promise.all() takes an array of promises and returns a new promise that resolves when all promises resolve or rejects when any promise rejects.

Example:

Promise.all([promise1, promise2, promise3])

  .then(results => console.log(results))

  .catch(error => console.log(error));

 

9. What are the different ways to define a function in JavaScript?

Answer:

Function Declaration:

function myFunction() { }

Function Expression:

const myFunction = function() { };

Arrow Function:

const myFunction = () => { };


10. What is event bubbling and event capturing in JavaScript?

Answer:

Event Bubbling: When an event occurs in an element, it first triggers on that element and then bubbles up to its ancestors (from child to parent).

Event Capturing: The event is first captured by the outermost element and then propagated to the target element (from parent to child).

You can control this behavior using addEventListener()'s third argument:

element.addEventListener('click', handler, true); // for capturing phase


11. What is the difference between map(), forEach(), filter(), and reduce()?

Answer:

map(): Returns a new array with the result of applying a function to every element.

forEach(): Executes a function for each element, but does not return a new array.

filter(): Returns a new array containing only the elements that satisfy a condition.

reduce(): Reduces an array to a single value by applying a function to each element and accumulating the result.

1. map()

The map() method creates a new array by applying a given function to every element in the original array. It does not change the original array.

Example:

const numbers = [1, 2, 3, 4];

const squaredNumbers = numbers.map(num => num * num);

console.log(squaredNumbers);  // Output: [1, 4, 9, 16]

Explanation: The map() function applies the square operation (num * num) to each element of the numbers array, returning a new array with the squared values.


2. forEach()

The forEach() method executes a provided function once for each array element. Unlike map(), it does not return a new array but allows you to perform side-effects such as logging or modifying external variables.

Example:

const numbers = [1, 2, 3, 4];

numbers.forEach(num => console.log(num * 2));

// Output: 2, 4, 6, 8

Explanation: forEach() multiplies each element by 2 and logs it. However, it doesn’t return a new array—just performs the operation on each element.


3. filter()

The filter() method creates a new array with all elements that pass the condition specified in the provided function.

Example:

const numbers = [1, 2, 3, 4, 5, 6];

const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers);  // Output: [2, 4, 6]

Explanation: filter() checks each element to see if it's even (num % 2 === 0). Only the elements that meet this condition are included in the new array.


4. reduce()

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value (e.g., sum, product, etc.).

Example:

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum);  // Output: 10

The second argument to reduce (0) sets the initial value of the accumulator


12. What is a promise in JavaScript, and why is it used?

Answer: A promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises are used to handle asynchronous operations more cleanly, avoiding "callback hell."

Example:

let promise = new Promise((resolve, reject) => {

    if (successful) 

resolve("Success!");

    else 

reject("Failure!");

});

promise

  .then(result => console.log(result))

  .catch(error => console.log(error));

  

13. How can you optimize a large DOM manipulation process in JavaScript?

Answer:

Minimize DOM access.

Use document fragments to batch changes and append them once.

Use innerHTML instead of multiple appendChild() calls for efficiency.

Debounce or throttle user-driven events.


14. What are the advantages of using async/await over Promises?

Answer: async/await allows you to write asynchronous code in a more synchronous, readable manner. It avoids the need for chaining .then() and handles errors with try/catch blocks, making the code easier to maintain.

Example:

async function fetchData() {

    try {

        let response = await fetch(url);

        let data = await response.json();

        console.log(data);

    } catch (error) {

        console.log(error);

    }

}


Q : what are the function to perform action on array or string

Ans:

push()

Adds one or more elements to the end of an array.

Example:


let arr = [1, 2];

arr.push(3);  // arr becomes [1, 2, 3]


pop()

Removes the last element from an array and returns that element.

Example:

let arr = [1, 2, 3];

arr.pop();  // arr becomes [1, 2]


shift()

Removes the first element from an array and returns that element.

Example:

let arr = [1, 2, 3];

arr.shift();  // arr becomes [2, 3]


unshift()

Adds one or more elements to the beginning of an array.

Example:

let arr = [2, 3];

arr.unshift(1);  // arr becomes [1, 2, 3]


map()

Creates a new array by applying a function to each element of the original array.

Example:

let arr = [1, 2, 3];

let squared = arr.map(num => num * num);  // squared becomes [1, 4, 9]


forEach()

Executes a provided function once for each array element.

Example:

let arr = [1, 2, 3];

arr.forEach(num => console.log(num));  // Logs 1, 2, 3


filter()

Creates a new array with all elements that pass the condition in the provided function.

Example:

let arr = [1, 2, 3, 4];

let evens = arr.filter(num => num % 2 === 0);  // evens becomes [2, 4]


reduce()

Applies a function to each element in the array to reduce the array to a single value.

Example:

let arr = [1, 2, 3, 4];

let sum = arr.reduce((acc, num) => acc + num, 0);  // sum becomes 10


concat()

Merges two or more arrays into a new array.

let arr1 = [1, 2];

let arr2 = [3, 4];

let combined = arr1.concat(arr2);  // combined becomes [1, 2, 3, 4]


slice()

Returns a shallow copy of a portion of an array into a new array.

Example:

let arr = [1, 2, 3, 4];

let sliced = arr.slice(1, 3);  // sliced becomes [2, 3]


splice()

Adds/removes elements from an array at a specific index.

Example:

let arr = [1, 2, 3];

arr.splice(1, 1, 4);  // arr becomes [1, 4, 3] (replaces 2 with 4)


indexOf()

Returns the first index at which a given element is found, or -1 if it is not found.

Example:

let arr = [1, 2, 3];

arr.indexOf(2);  // Output: 1


join()

Joins all elements of an array into a string.

Example:

let arr = ['a', 'b', 'c'];

arr.join('-');  // Output: "a-b-c"


reverse()

Reverses the order of the elements in an array.

Example:

let arr = [1, 2, 3];

arr.reverse();  // arr becomes [3, 2, 1]


sort()

Sorts the elements of an array.

Example:

let arr = [3, 1, 2];

arr.sort();  // arr becomes [1, 2, 3]


String Methods:


charAt()

Returns the character at a specified index in a string.

Example:

let str = "Hello";

str.charAt(0);  // Output: "H"


concat()

Combines two or more strings.

Example:

let str1 = "Hello";

let str2 = "World";

let combined = str1.concat(' ', str2);  // Output: "Hello World"


includes()

Checks if a string contains a specified substring.

Example:

let str = "Hello World";

str.includes("World");  // Output: true


indexOf()

Returns the index of the first occurrence of a specified value in a string.

Example:

let str = "Hello World";

str.indexOf("World");  // Output: 6


toLowerCase()

Converts the string to lowercase.

Example:

let str = "Hello";

str.toLowerCase();  // Output: "hello"


toUpperCase()

Converts the string to uppercase.

Example:

let str = "Hello";

str.toUpperCase();  // Output: "HELLO"


split()

Splits a string into an array based on a delimiter.

Example:

let str = "Hello World";

let arr = str.split(' ');  // Output: ["Hello", "World"]


substring()

Extracts characters from a string between two specified indices.

Example:

let str = "Hello World";

str.substring(0, 5);  // Output: "Hello"


trim()

Removes whitespace from both ends of a string.

Example:

let str = "  Hello World  ";

str.trim();  // Output: "Hello World"


replace()

Replaces a substring with a new value.

Example:

let str = "Hello World";

let newStr = str.replace("World", "Everyone");  // Output: "Hello Everyone"


charCodeAt()

Returns the Unicode value of the character at a specific index.

Example:

let str = "Hello";

str.charCodeAt(0);  // Output: 72 (Unicode for 'H')


slice()

Extracts a part of a string and returns a new string.

Example:

let str = "Hello World";

str.slice(0, 5);  // Output: "Hello"


Q: Write programs related to String.

Ans:

1. Reverse a String


function reverseString(str) {

    return str.split('').reverse().join('');

}

console.log(reverseString("hello")); // "olleh"


2. Check if a String is a Palindrome


function isPalindrome(str) {

    const cleanedStr = str.replace(/[^a-z0-9]/gi, '').toLowerCase();

    return cleanedStr === cleanedStr.split('').reverse().join('');

}

console.log(isPalindrome("A man, a plan, a canal, Panama")); // true


3. Count Vowels in a String


function countVowels(str) {

    return (str.match(/[aeiou]/gi) || []).length;

}

console.log(countVowels("hello world")); // 3


4. Capitalize the First Letter of Each Word


function capitalizeWords(str) {

    return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

}

console.log(capitalizeWords("hello world")); // "Hello World"


5. Find the Longest Word in a String


function findLongestWord(str) {

    return str.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest, '');

}

console.log(findLongestWord("The quick brown fox jumped over the lazy dog")); // "jumped"


6. Remove Duplicates from a String


function removeDuplicates(str) {

    return [...new Set(str)].join('');

}

console.log(removeDuplicates("hello world")); // "helo wrd"


7. Count the Number of Words in a String


function countWords(str) {

    return str.trim().split(/\s+/).length;

}

console.log(countWords("Hello, how are you?")); // 5


8. Replace All Occurrences of a Substring


function replaceAll(str, target, replacement) {

    const regex = new RegExp(target, 'g');

    return str.replace(regex, replacement);

}

console.log(replaceAll("Hello world", "world", "JavaScript")); // "Hello JavaScript"


9. Check if a String Contains Another String


function containsSubstring(str, substring) {

    return str.includes(substring);

}

console.log(containsSubstring("Hello world", "world")); // true


10. Convert a String to Title Case


function toTitleCase(str) {

    return str.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

}

console.log(toTitleCase("hello world")); // "Hello World"


11. Trim Whitespace from Both Ends of a String


function trimString(str) {

    return str.trim();

}

console.log(trimString("   Hello world   ")); // "Hello world"


12. Convert a String to a URL-friendly Format

function toSlug(str) {

    return str.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');

}

console.log(toSlug("Hello World! How are you?")); // "hello-world-how-are-you"


13. Get the Character at a Specific Index

function charAtIndex(str, index) {

    return str.charAt(index);

}

console.log(charAtIndex("hello", 1)); // "e"


14. Get All Unique Characters in a String

function uniqueChars(str) {

    return [...new Set(str)].join('');

}

console.log(uniqueChars("hello world")); // "helo wrd"


15. Split a String into an Array of Characters

function splitIntoArray(str) {

    return str.split('');

}

console.log(splitIntoArray("hello")); // ["h", "e", "l", "l", "o"]


Comments