Loading image
Top JavaScript Interview Questions for fresher with Examples 2023

Top JavaScript Interview Questions for fresher with Examples 2023

  • showkat ali
  • 30th Jan, 2024
  • 138

JavaScript is the most popular programming language for developing dynamic and interactive web applications. If you are new to JavaScript and are preparing for an interview, you will most likely be asked a variety of questions that will put your knowledge of the language to the test. To help you prepare, we have compiled a list of common JavaScript interview questions, along with examples where applicable.

 

1. What is JavaScript and how does it differ from Java?

JavaScript is a high-level scripting language that is primarily used in web development. It runs on web browsers and enables developers to create interactive web pages. Despite their similar names, JavaScript and Java are completely different languages.

 

2. What exactly are variables in JavaScript? How are they declared?

JavaScript uses variables to store data values. You can declare variables using var, let, or const. For example:

var name = "John"; // Using var
let age = 30;      // Using let
const pi = 3.14;   // Using const

3. Explain the difference between let, const, and var.

  • var is function-scoped and can be re-declared within the same function.
  • let is block-scoped and allows reassignment.
  • const is block-scoped and cannot be reassigned once declared.

 

4. How do you create and use functions in JavaScript?

Functions are blocks of code that can be called repeatedly. You can create a function like this:

 

function greet(name) {
    console.log(`Hello, ${name}!`);
}

greet("Alice"); // Output: Hello, Alice!

 

5. Explain what callback functions are and provide an example.

Callback functions are functions passed as arguments to other functions and are executed when a specific event occurs or after a task is completed. Here's an example using setTimeout:

function delayedGreeting(name) {
    setTimeout(function() {
        console.log(`Hello, ${name}!`);
    }, 1000);
}

delayedGreeting("Bob"); // After 1 second: Hello, Bob!

 

6. Describe the concept of closures in JavaScript.

Closures occur when a function retains access to variables from its outer scope even after that scope has exited. They are commonly used for data encapsulation and maintaining state. Here's an example:

function outer() {
    let count = 0;
    
    function inner() {
        count++;
        console.log(count);
    }
    
    return inner;
}

const closureFunc = outer();
closureFunc(); // Output: 1
closureFunc(); // Output: 2

 

7. What is the event loop in JavaScript?

The event loop is a crucial part of JavaScript's concurrency model, responsible for managing the execution of asynchronous code. It ensures that the JavaScript runtime remains responsive by handling callbacks and events. For example:

console.log("Start");

setTimeout(function() {
    console.log("Inside setTimeout");
}, 2000);

console.log("End");

 

8. Explain the purpose of this keyword in JavaScript.

The this keyword refers to the current execution context. Its value depends on how a function is called:

  • In a global context, this refers to the global object (e.g., window in browsers).
  • In an object method, this refers to the object that owns the method.
  • In an event handler, this typically refers to the element that triggered the event.

 

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

person.greet(); // Output: Hello, Alice!

 

9. How do you handle errors in JavaScript?

JavaScript provides try...catch blocks to handle exceptions:

try {
    // Code that may throw an error
    throw new Error("Something went wrong");
} catch (error) {
    console.error(error.message);
}

10. What is the purpose of localStorage and sessionStorage in the browser?

localStorage and sessionStorage are web storage APIs used to store key-value pairs in a user's browser.

  • localStorage stores data persistently, even after the browser is closed.
  • sessionStorage stores data for the duration of a single page session (until the tab is closed).
localStorage.setItem("username", "John");
const username = localStorage.getItem("username");
console.log(username); // Output: John

 

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

null represents the intentional absence of any object value, while undefined indicates that a variable has been declared but has not been assigned any value.

let x = null;
let y;

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

 

12. Explain the concept of hoisting in JavaScript.

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation. However, only the declarations are hoisted, not the initializations.

console.log(a); // Output: undefined
var a = 10;

foo(); // Output: "Hello, world!"
function foo() {
    console.log("Hello, world!");
}

 

13. How can you prevent a variable from being modified after its initial assignment?

 Use the const keyword to declare a variable as a constant. It cannot be reassigned after its initial value is set.

const pi = 3.14;
pi = 3.14159; // Error: Assignment to constant variable

 

14. What is the purpose of the === operator in JavaScript?

The === operator is a strict equality operator that checks both value and type. It returns true if the values are equal in both value and type.

5 === 5;        // true
5 === "5";      // false

 

15. Explain the concept of the "event delegation" in JavaScript.

Event delegation is a technique where a single event handler is attached to a common ancestor of multiple elements instead of attaching individual handlers to each element. It's efficient for handling events on a large number of elements.

// Using event delegation to handle clicks on a list of items
document.querySelector("#itemList").addEventListener("click", function(event) {
    if (event.target.tagName === "LI") {
        console.log(`Clicked on item: ${event.target.textContent}`);
    }
});

 

16. How do you deep-clone an object in JavaScript?

You can deep-clone an object using methods like the JSON methods JSON.parse() and JSON.stringify(). However, this method may not work with objects containing functions or circular references.

const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
console.log(clone); // Output: { a: 1, b: { c: 2 } }

17. Explain the concept of a "closure leak" and how to prevent it.

A closure leak occurs when a function retains references to variables that are no longer needed, preventing them from being garbage collected. To prevent closure leaks, be mindful of what you capture inside closures and use the null pattern to release references when necessary.

function createCounter() {
    let count = 0;
    return {
        increment: function() {
            count++;
        },
        // To prevent a closure leak
        destroy: function() {
            count = null;
        }
    };
}

 

18. What are arrow functions in JavaScript, and how do they differ from regular functions?

Arrow functions are a more concise way to write functions in JavaScript. They differ from regular functions in that they do not have their own this or arguments binding and cannot be used as constructors.

// Regular function
function add(a, b) {
    return a + b;
}

// Arrow function
const add = (a, b) => a + b;

 

19. How can you check if an array contains a specific element?

You can use the includes() method to check if an array contains a specific element.

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false

 

20. What is a promise in JavaScript, and how does it work?

A promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises have three states: pending, fulfilled, or rejected. You can use .then() and .catch() to handle the results or errors of promises.

const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() < 0.5) {
                resolve("Data fetched successfully");
            } else {
                reject("Error fetching data");
            }
        }, 1000);
    });
};

fetchData()
    .then(data => console.log(data))
    .catch(error => console.error(error));

 

21. What is the purpose of the map() function in JavaScript?

The map() function is used to create a new array by applying a given function to each element of an existing array.

const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(num => num * num);
console.log(squared); // Output: [1, 4, 9, 16, 25]

22. Explain the difference between let and var in terms of scope.

let is block-scoped, which means it is limited to the block or statement where it is declared. var is function-scoped and can be accessed within the entire function.

function example() {
    if (true) {
        let x = 5;
        var y = 10;
    }
    console.log(x); // Error: x is not defined
    console.log(y); // Output: 10
}

 

23. What is a closure in JavaScript and why is it important?

 A closure is a function that retains access to its outer (enclosing) function's variables even after the outer function has finished executing. Closures are important for data encapsulation and maintaining state in JavaScript.

function counter() {
    let count = 0;
    return function() {
        count++;
        console.log(count);
    };
}

const increment = counter();
increment(); // Output: 1
increment(); // Output: 2

 

24. How can you remove duplicates from an array in JavaScript?

You can remove duplicates from an array by converting it to a Set (which automatically removes duplicates) and then back to an array.

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

 

25. Explain the purpose of the bind() method in JavaScript.

The bind() method is used to create a new function that, when called, has its this value set to a specific object. It's often used to bind a function to a particular context.

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

const greetAlice = person.greet.bind(person);
greetAlice(); // Output: Hello, Alice!

 

26. How do you check if a variable is an array in JavaScript?

You can use the Array.isArray() method to check if a variable is an array.

const numbers = [1, 2, 3];
console.log(Array.isArray(numbers)); // true

const name = "Alice";
console.log(Array.isArray(name)); // false

 

28. Explain the concept of "event bubbling" in JavaScript.

Event bubbling is a propagation mechanism in the DOM where an event triggered on a nested element propagates to its parent elements in the DOM hierarchy. This allows event delegation by handling events on parent elements.

<div id="parent">
    <button id="child">Click me!</button>
</div>

 

document.getElementById("parent").addEventListener("click", function() {
    console.log("Parent clicked");
});

document.getElementById("child").addEventListener("click", function() {
    console.log("Child clicked");
});

 

29. How can you convert a string to an integer in JavaScript?

You can use functions like parseInt() or the unary + operator to convert a string to an integer.

const numStr = "42";
const num = parseInt(numStr);
console.log(num); // Output: 42

 

30. Explain the purpose of the JavaScript call() and apply() methods.

Both call() and apply() are used to invoke functions with a specific this value and arguments.

  • call() takes individual arguments.
  • apply() takes an array of arguments.
function greet(greeting) {
    console.log(`${greeting}, ${this.name}!`);
}

const person = { name: "Bob" };

greet.call(person, "Hello"); // Output: Hello, Bob!
greet.apply(person, ["Hi"]);  // Output: Hi, Bob!

 

These additional questions should further enhance your JavaScript interview preparation. Remember to practice coding and explore real-world scenarios to gain confidence in your JavaScript skills. Good luck with your interviews!

 

 

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

Advertisements