docs

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

console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (different types)

2. What is a closure in JavaScript?

function makeCounter() {
  let count = 0; // private variable
  return function () {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

3. What are Promises in JavaScript?

const myPromise = new Promise((resolve, reject) => {
  // Simulate an asynchronous operation
  setTimeout(() => {
    const success = true; // change to false to simulate error
    if (success) {
      resolve("Operation successful!");
    } else {
      reject("Operation failed.");
    }
  }, 1000);
});

myPromise
  .then((result) => console.log(result)) // Operation successful!
  .catch((error) => console.error(error));

4. What is the difference between null and undefined?

let a;
let b = null;

console.log(a); // undefined
console.log(b); // null
console.log(typeof a); // undefined
console.log(typeof b); // object

5. What is the Event Loop in JavaScript?

console.log("Start");

setTimeout(() => {
  console.log("Timeout");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("End");

// Output:
// Start
// End
// Promise
// Timeout

6. Explain the concept of this in JavaScript.

const obj = {
  value: 42,
  method: function () {
    console.log(this.value);
  },
};

obj.method(); // 42

const method = obj.method;
method(); // undefined (or throws an error in strict mode)

const arrowMethod = () => {
  console.log(this.value);
};

arrowMethod(); // undefined (in global scope)

7. What are the different ways to create objects in JavaScript?

// Object Literal
const obj1 = {
  name: "Alice",
  age: 25,
};

// Constructor Function
function Person(name, age) {
  this.name = name;
  this.age = age;
}
const obj2 = new Person("Bob", 30);

// Object.create()
const proto = {
  greet() {
    console.log("Hello!");
  },
};
const obj3 = Object.create(proto);
obj3.name = "Charlie";

// ES6 Class
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}
const obj4 = new Animal("Dog");

8. Explain how prototypal inheritance works in JavaScript.

const animal = {
  speak() {
    console.log("Animal speaks");
  },
};

const dog = Object.create(animal);
dog.speak = function () {
  console.log("Dog barks");
};

dog.speak(); // Dog barks
animal.speak(); // Animal speaks

9. What is the purpose of the bind, call, and apply methods?

function greet(greeting) {
  console.log(`${greeting}, my name is ${this.name}.`);
}

const person = { name: "Alice" };

const boundGreet = greet.bind(person);
boundGreet("Hello"); // Hello, my name is Alice.

greet.call(person, "Hi"); // Hi, my name is Alice.
greet.apply(person, ["Hey"]); // Hey, my name is Alice.

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

var x = 1;
if (true) {
  var x = 2; // same variable
  console.log(x); // 2
}
console.log(x); // 2

let y = 1;
if (true) {
  let y = 2; // different variable
  console.log(y); // 2
}
console.log(y); // 1

const z = 1;
// z = 2; // Error: Assignment to constant variable.

11. What are template literals in JavaScript?

const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!

const multiLine = `This is a string
that spans multiple lines.`;
console.log(multiLine);

12. Explain the concept of the “this” keyword in JavaScript.

const obj = {
  name: "Alice",
  greet: function () {
    console.log(`Hello, my name is ${this.name}`);
  },
};
obj.greet(); // Hello, my name is Alice

const greetFunc = obj.greet;
greetFunc(); // Hello, my name is undefined (in non-strict mode)

const arrowGreet = () => {
  console.log(`Hello, my name is ${this.name}`);
};
arrowGreet(); // Hello, my name is undefined (in global scope)

13. What is event delegation in JavaScript?

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  document.getElementById("myList").addEventListener("click", function (e) {
    if (e.target.tagName === "LI") {
      alert(`You clicked on ${e.target.textContent}`);
    }
  });
</script>

14. What are higher-order functions in JavaScript?

function greet(name) {
  return `Hello, ${name}!`;
}

function processUserInput(callback) {
  const name = "Alice";
  console.log(callback(name));
}

processUserInput(greet); // Hello, Alice!

15. What is the setTimeout function, and how does it work?

console.log("Start");

const timeoutId = setTimeout(() => {
  console.log("This runs after 1 second");
}, 1000);

console.log("End");

// To cancel the timeout
clearTimeout(timeoutId);

16. What is the purpose of the async and await keywords?

function getData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Data received");
    }, 1000);
  });
}

async function fetchData() {
  const result = await getData();
  console.log(result); // Data received
}

fetchData();

17. What is the difference between synchronous and asynchronous programming?

// Synchronous
console.log("Start");
console.log("End"); // 'End' is logged after 'Start'

// Asynchronous
console.log("Start");
setTimeout(() => {
  console.log("Timeout"); // 'Timeout' is logged after 1 second
}, 1000);
console.log("End"); // 'End' is logged immediately after 'Start'

18. What are modules in JavaScript, and why are they used?

// math.js (module)
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

// main.js
import { add, subtract } from "./math.js";

console.log(add(2, 3)); // 5
console.log(subtract(5, 2)); // 3

19. Explain the concept of hoisting in JavaScript.

console.log(x); // undefined
var x = 5;

function sayHello() {
  console.log("Hello");
}

sayHello(); // Hello

20. What is the typeof operator?

console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof null); // "object" (this is a known quirk)
console.log(typeof undefined); // "undefined"
console.log(typeof function () {}); // "function"

21. What is the difference between Object.freeze() and Object.seal()?

const obj = { name: "Alice", age: 25 };

Object.freeze(obj);
obj.age = 30; // No effect
obj.gender = "female"; // No effect
console.log(obj); // { name: 'Alice', age: 25 }

const sealedObj = { name: "Bob", age: 30 };
Object.seal(sealedObj);
sealedObj.age = 35; // Allowed
sealedObj.gender = "male"; // No effect
console.log(sealedObj); // { name: 'Bob', age: 35 }

22. What are the differences between apply(), call(), and bind()?

function greet(greeting) {
  console.log(`${greeting}, my name is ${this.name}`);
}

const person = { name: "Alice" };

greet.call(person, "Hello"); // Hello, my name is Alice
greet.apply(person, ["Hi"]); // Hi, my name is Alice

const boundGreet = greet.bind(person, "Hey");
boundGreet(); // Hey, my name is Alice

23. Explain the concept of “debouncing” and “throttling”.

function debounce(func, delay) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}

const handleResize = debounce(() => {
  console.log("Resized!");
}, 500);

window.addEventListener("resize", handleResize);
function throttle(func, limit) {
  let lastFunc;
  let lastRan;
  return function (...args) {
    if (!lastRan) {
      func.apply(this, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(() => {
        if (Date.now() - lastRan >= limit) {
          func.apply(this, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

const logScroll = throttle(() => {
  console.log("Scrolled!");
}, 1000);

window.addEventListener("scroll", logScroll);

24. What is the purpose of the JSON.stringify() and JSON.parse() methods?

const obj = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"Alice","age":25}'

const parsedObj = JSON.parse(jsonString);
console.log(parsedObj); // { name: 'Alice', age: 25 }

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

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "foo");
});
const promise3 = 42;

Promise.all([promise1, promise2, promise3])
  .then((values) => {
    console.log(values); // [3, 'foo', 42]
  })
  .catch((error) => {
    console.error(error);
  });

26. Explain the concept of the “fetch” API.

fetch("https://jsonplaceholder.typicode.com/posts")
  .then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) =>
    console.error("There has been a problem with your fetch operation:", error)
  );

27. What are symbols in JavaScript?

const mySymbol = Symbol("description");
const obj = {
  [mySymbol]: "value",
};
console.log(obj[mySymbol]); // value
console.log(obj["mySymbol"]); // undefined (not accessible)

28. What is the difference between splice() and slice() methods in arrays?

const arr = [1, 2, 3, 4, 5];

// Using splice
const removed = arr.splice(2, 2); // Removes 2 elements from index 2
console.log(arr); // [1, 2, 5]
console.log(removed); // [3, 4]

// Using slice
const newArr = arr.slice(1, 3); // Returns elements from index 1 to 3 (exclusive)
console.log(newArr); // [2, 5]

29. What are the differences between an arrow function and a regular function?

const obj = {
  value: 42,
  regularFunction: function () {
    console.log(this.value); // 42
  },
  arrowFunction: () => {
    console.log(this.value); // undefined (in global scope)
  },
};

obj.regularFunction(); // 42
obj.arrowFunction(); // undefined

30. What are iterators and generators in JavaScript?

function* generatorFunction() {
  yield 1;
  yield 2;
  yield 3;
}

const iterator = generatorFunction();

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

31. What is the difference between map() and forEach()?

const numbers = [1, 2, 3];

const squared = numbers.map((num) => num * num);
console.log(squared); // [1, 4, 9]

numbers.forEach((num) => {
  console.log(num); // Prints each number: 1, 2, 3
});

32. What is the purpose of reduce() method?

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

const sum = numbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  0
);
console.log(sum); // 10

33. How do you remove duplicates from an array?

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

// Using Set
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

// Using filter() and indexOf()
const uniqueNumbers2 = numbers.filter(
  (value, index) => numbers.indexOf(value) === index
);
console.log(uniqueNumbers2); // [1, 2, 3, 4, 5]

34. What is the find() method in arrays?

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

const found = numbers.find((num) => num > 3);
console.log(found); // 4

35. What is the difference between splice() and slice()?

const arr = [1, 2, 3, 4, 5];

// Using splice
const removed = arr.splice(2, 2); // Removes 2 elements from index 2
console.log(arr); // [1, 2, 5]
console.log(removed); // [3, 4]

// Using slice
const newArr = arr.slice(1, 3); // Returns elements from index 1 to 3 (exclusive)
console.log(newArr); // [2, 5]

36. How do you reverse an array?

const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // [5, 4, 3, 2, 1]

37. What is the difference between shallow copy and deep copy?

const original = { a: 1, b: { c: 2 } };

// Shallow copy
const shallowCopy = { ...original };
shallowCopy.b.c = 3;
console.log(original.b.c); // 3 (affected)

// Deep copy
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.b.c = 4;
console.log(original.b.c); // 3 (not affected)

38. How do you concatenate two arrays?

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

const combined = arr1.concat(arr2);
console.log(combined); // [1, 2, 3, 4, 5, 6]

39. What is the every() method in arrays?

const numbers = [2, 4, 6, 8];

const allEven = numbers.every((num) => num % 2 === 0);
console.log(allEven); // true

40. How do you flatten an array?

const nestedArr = [1, [2, [3, 4]], 5];

const flatArr = nestedArr.flat(2); // Flattens up to 2 levels deep
console.log(flatArr); // [1, 2, 3, 4, 5]

41. What is the some() method in arrays?

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

const hasEven = numbers.some((num) => num % 2 === 0);
console.log(hasEven); // true (because 2 and 4 are even)

42. What is the fill() method in arrays?

const arr = [1, 2, 3, 4, 5];

arr.fill(0, 1, 4); // Fill from index 1 to index 4 (exclusive)
console.log(arr); // [1, 0, 0, 0, 5]

43. What is the includes() method in arrays?

const fruits = ["apple", "banana", "orange"];

const hasBanana = fruits.includes("banana");
console.log(hasBanana); // true

const hasGrapes = fruits.includes("grapes");
console.log(hasGrapes); // false

44. What is the indexOf() method in arrays?

const colors = ["red", "green", "blue"];

const index = colors.indexOf("green");
console.log(index); // 1

const notFound = colors.indexOf("yellow");
console.log(notFound); // -1

45. What is the join() method in arrays?

const words = ["Hello", "World"];

const sentence = words.join(" ");
console.log(sentence); // "Hello World"

const csv = words.join(",");
console.log(csv); // "Hello,World"

46. What is the sort() method in arrays?

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

const sorted = numbers.sort(); // Sorts as strings by default
console.log(sorted); // [1, 2, 3, 4]

const sortedNumbers = numbers.sort((a, b) => a - b); // Sorts numerically
console.log(sortedNumbers); // [1, 2, 3, 4]

47. What is the reverse() method in arrays?

const arr = [1, 2, 3];

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

48. What is the slice() method in arrays?

const fruits = ["apple", "banana", "orange", "grape"];

const citrus = fruits.slice(1, 3); // Returns elements from index 1 to 3 (exclusive)
console.log(citrus); // ['banana', 'orange']

49. What is the flatMap() method in arrays?

const arr = [1, 2, 3];

const result = arr.flatMap((num) => [num, num * 2]);
console.log(result); // [1, 2, 2, 4, 3, 6]

50. What is the splice() method in arrays?

const arr = ["apple", "banana", "orange"];

const removed = arr.splice(1, 1, "grape"); // Removes 1 element at index 1 and adds 'grape'
console.log(arr); // ['apple', 'grape', 'orange']
console.log(removed); // ['banana']

51. What is the filter() method in arrays?

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

const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

52. What is the concat() method in arrays?

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

const combined = arr1.concat(arr2);
console.log(combined); // [1, 2, 3, 4, 5, 6]

53. What is the reduceRight() method in arrays?

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

const sum = numbers.reduceRight(
  (accumulator, currentValue) => accumulator + currentValue,
  0
);
console.log(sum); // 10

54. What is the copyWithin() method in arrays?

const arr = [1, 2, 3, 4, 5];

arr.copyWithin(0, 3); // Copies elements from index 3 to index 0
console.log(arr); // [4, 5, 3, 4, 5]

55. What is the toString() method in arrays?

const arr = [1, "apple", true];

const str = arr.toString();
console.log(str); // "1,apple,true"

56. What is the keys() method in arrays?

const arr = ["a", "b", "c"];

const keys = arr.keys();
console.log([...keys]); // [0, 1, 2]

57. What is the values() method in arrays?

const arr = ["x", "y", "z"];

const values = arr.values();
console.log([...values]); // ['x', 'y', 'z']

58. What is the entries() method in arrays?

const arr = ["apple", "banana", "cherry"];

const entries = arr.entries();
console.log([...entries]); // [[0, 'apple'], [1, 'banana'], [2, 'cherry']]

59. How do you find the maximum value in an array?

const numbers = [10, 5, 8, 12, 20];

const maxValue = Math.max(...numbers);
console.log(maxValue); // 20

60. What is the some() method and how does it differ from every()?

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

const hasOdd = numbers.some((num) => num % 2 !== 0); // true (1, 3, 5 are odd)
const allEven = numbers.every((num) => num % 2 === 0); // false

console.log(hasOdd); // true
console.log(allEven); // false

61. What is an object in JavaScript?

const person = {
  name: "John",
  age: 30,
  greet: function () {
    console.log("Hello, " + this.name);
  },
};

person.greet(); // "Hello, John"

62. How do you create an object in JavaScript?

const car = {
  make: "Toyota",
  model: "Camry",
  year: 2020,
};

63. What is the difference between a shallow copy and a deep copy?

const original = { a: 1, b: { c: 2 } };

// Shallow copy
const shallowCopy = { ...original };
shallowCopy.b.c = 3;
console.log(original.b.c); // 3 (affected)

// Deep copy
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.b.c = 4;
console.log(original.b.c); // 3 (not affected)

64. How do you add a property to an object?

const student = {
  name: "Alice",
  age: 20,
};

// Dot notation
student.grade = "A";

// Bracket notation
student["major"] = "Computer Science";

console.log(student); // { name: 'Alice', age: 20, grade: 'A', major: 'Computer Science' }

65. What is the this keyword in JavaScript?

const person = {
  name: "John",
  greet: function () {
    console.log("Hello, " + this.name);
  },
};

person.greet(); // "Hello, John"

66. How do you delete a property from an object?

const car = {
  make: "Toyota",
  model: "Camry",
  year: 2020,
};

delete car.year;
console.log(car); // { make: 'Toyota', model: 'Camry' }

67. What are computed property names in JavaScript?

const propName = "age";
const person = {
  name: "John",
  [propName]: 30, // 'age' is dynamically set
};
console.log(person); // { name: 'John', age: 30 }

68. What is the difference between Object.keys() and Object.values()?

const person = { name: "Alice", age: 25 };

const keys = Object.keys(person); // ['name', 'age']
const values = Object.values(person); // ['Alice', 25]

69. How do you merge two objects in JavaScript?

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };

const merged = Object.assign({}, obj1, obj2); // { a: 1, b: 3, c: 4 }
const spreadMerged = { ...obj1, ...obj2 }; // { a: 1, b: 3, c: 4 }

70. What is the purpose of Object.freeze()?

const car = { make: "Toyota", model: "Camry" };
Object.freeze(car);

car.year = 2020; // This will not work
console.log(car); // { make: 'Toyota', model: 'Camry' }

71. What is the purpose of Object.seal()?

const car = { make: "Toyota", model: "Camry" };
Object.seal(car);

car.year = 2020; // This will not work
car.make = "Honda"; // This will work
console.log(car); // { make: 'Honda', model: 'Camry' }

72. How do you check if a property exists in an object?

const person = { name: "Alice", age: 25 };

console.log("age" in person); // true
console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("address")); // false

73. What is the difference between undefined and null in JavaScript?

let x; // x is undefined
let y = null; // y is explicitly set to null

console.log(x); // undefined
console.log(y); // null

74. How can you create a copy of an object?

const original = { a: 1, b: 2 };

// Shallow copy
const shallowCopy = { ...original };
const assignCopy = Object.assign({}, original);

// Deep copy
const deepCopy = JSON.parse(JSON.stringify(original));

75. What is the Object.prototype?

console.log(Object.prototype.toString); // function toString() { [native code] }

76. What is method chaining in JavaScript objects?

const calculator = {
  value: 0,
  add(num) {
    this.value += num;
    return this; // Return the object for chaining
  },
  subtract(num) {
    this.value -= num;
    return this; // Return the object for chaining
  },
  getValue() {
    return this.value;
  },
};

const result = calculator.add(5).subtract(2).getValue();
console.log(result); // 3

77. How do you iterate over an object’s properties?

const person = { name: "Alice", age: 25 };

// Using for...in
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

// Using Object.entries()
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

78. What is a constructor function in JavaScript?

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const alice = new Person("Alice", 25);
console.log(alice); // Person { name: 'Alice', age: 25 }

79. What is the Object.create() method?

const proto = {
  greet() {
    console.log("Hello");
  },
};
const obj = Object.create(proto);
obj.greet(); // "Hello"

80. What are the differences between == and === in JavaScript?

console.log(0 == "0"); // true (coerced)
console.log(0 === "0"); // false (no coercion)
console.log(null == undefined); // true (coerced)
console.log(null === undefined); // false (different types)