DEV Community

Jakaria Masum
Jakaria Masum

Posted on

JavaScript Interview Questions for Beginners

If you're new to JavaScript, don't worry! This guide will break down some common JavaScript concepts into simple terms with easy-to-understand examples. Let’s dive in!


1. What is a Higher-Order Function & Callback Function?

Higher-Order Function

A higher-order function is like a "boss" function that can either:

  • Take another function as an input (like hiring a worker), or
  • Return a function as output (like creating a new worker).

Example:

// A higher-order function that takes a function as input
function sayHello(name, callback) {
  console.log(`Hello, ${name}!`);
  callback(); // Call the callback function
}

function sayGoodbye() {
  console.log("Goodbye!");
}

sayHello("Alice", sayGoodbye);
// Output:
// Hello, Alice!
// Goodbye!
Enter fullscreen mode Exit fullscreen mode

Here, sayHello is the boss, and sayGoodbye is the worker (callback).


Callback Function

A callback function is just a regular function that gets passed into another function and is called later.

Why Use Callbacks?
Callbacks are useful when you want to do something after a task finishes, like waiting for a user to click a button or fetching data from the internet.


2. What is Hoisting in JavaScript?

Hoisting means that JavaScript moves variable and function declarations to the top of their scope before running the code. It’s like writing your homework title at the top of the page before filling in the answers.

Example:

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

// Behind the scenes, JavaScript does this:
var x;         // Declaration is hoisted
console.log(x); // undefined
x = 5;         // Assignment happens later
Enter fullscreen mode Exit fullscreen mode

Important Note: let and const don’t get hoisted in the same way as var. If you try to use them before declaring, you’ll get an error.


3. What is Scope in JavaScript?

Scope is like a "boundary" that decides where variables live. Think of it like rooms in a house:

  • Variables declared inside a room (function) can only be used there.
  • Variables declared outside all rooms (globally) can be used anywhere.

Types of Scope:

  1. Global Scope: Variables declared outside any function.
  2. Local/Function Scope: Variables declared inside a function.
  3. Block Scope: Variables declared with let or const inside {}.

Example:

var globalVar = "I'm everywhere!";

function myRoom() {
  var localVar = "I'm stuck in this room!";
  console.log(globalVar); // Works
  console.log(localVar);  // Works
}

myRoom();
console.log(globalVar); // Works
console.log(localVar);  // Error: localVar is not defined
Enter fullscreen mode Exit fullscreen mode

4. What is the Difference Between call, apply, and bind?

These methods help control the value of this in a function. Imagine this as a person who needs to know where they belong.

  • call: Calls the function immediately and lets you pass arguments one by one.
  • apply: Calls the function immediately but lets you pass arguments as an array.
  • bind: Creates a new function with this set to a specific value, but doesn’t call it right away.

Example:

const person = {
  name: "Alice",
  greet: function (greeting) {
    console.log(`${greeting}, ${this.name}`);
  },
};

const otherPerson = { name: "Bob" };

// Using call
person.greet.call(otherPerson, "Hi"); // Output: Hi, Bob

// Using apply
person.greet.apply(otherPerson, ["Hello"]); // Output: Hello, Bob

// Using bind
const greetBob = person.greet.bind(otherPerson);
greetBob("Hey"); // Output: Hey, Bob
Enter fullscreen mode Exit fullscreen mode

5. What is the Difference Between == and === Operators?

  • == (Equality): Compares values but allows JavaScript to change types if needed (type coercion).
  • === (Strict Equality): Compares both value and type without changing anything.

Example:

console.log(5 == "5");  // true (JavaScript converts "5" to a number)
console.log(5 === "5"); // false (different types)

console.log(null == undefined); // true
console.log(null === undefined); // false
Enter fullscreen mode Exit fullscreen mode

Tip: Always use === unless you have a good reason to use ==.


6. What is a Cookie?

A cookie is like a sticky note that websites leave on your browser to remember things about you, like your login details or preferences.

Example:

// Setting a cookie
document.cookie = "username=JohnDoe";

// Reading cookies
console.log(document.cookie); // Output: username=JohnDoe
Enter fullscreen mode Exit fullscreen mode

Cookies are small and limited in size, so they’re best for simple tasks.


7. What is a Promise?

A promise is like a box that may contain a gift (success) or a note saying it’s out of stock (failure). Promises are used for asynchronous tasks, like fetching data from a server.

States of a Promise:

  1. Pending: Waiting for the result.
  2. Fulfilled: Got the result successfully.
  3. Rejected: Something went wrong.

Example:

const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = true;
      if (success) {
        resolve("Data loaded!"); // Success
      } else {
        reject("Error occurred!"); // Failure
      }
    }, 2000);
  });
};

fetchData()
  .then((data) => console.log(data)) // Output: Data loaded!
  .catch((error) => console.error(error));
Enter fullscreen mode Exit fullscreen mode

8. What is an Event Loop?

The event loop is like a waiter in a restaurant. It keeps checking if the kitchen (call stack) is free to take new orders (tasks). If the kitchen is busy, the waiter waits until it’s ready.

Example:

console.log("Start");

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

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

console.log("End");

// Output:
// Start
// End
// Promise
// Timeout
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • setTimeout goes to the "waiting area" (task queue).
  • Promises go to the "VIP area" (microtask queue) and get served first.

9. What is a Prototype Chain?

Every object in JavaScript has a "parent" object called a prototype. If you ask an object for something it doesn’t have, JavaScript looks up its prototype chain to find it.

Example:

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

Person.prototype.greet = function () {
  console.log(`Hello, ${this.name}`);
};

const alice = new Person("Alice");
alice.greet(); // Output: Hello, Alice
Enter fullscreen mode Exit fullscreen mode

Here, greet is not directly on alice, but JavaScript finds it through the prototype chain.


10. How Can You Eliminate Duplicate Values from a JavaScript Array?

Removing duplicates is like cleaning up a messy room by keeping only one of each item.

Using Set:

const numbers = [1, 2, 2, 3, 4, 4];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Using filter:

const numbers = [1, 2, 2, 3, 4, 4];
const uniqueNumbers = numbers.filter((value, index, array) => array.indexOf(value) === index);
console.log(uniqueNumbers); // Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

By understanding these concepts step-by-step, you'll build a strong foundation in JavaScript. Practice these examples, and soon you'll feel confident tackling more advanced topics!
Happy Coding!🚀

Top comments (0)