JavaScript Interview Questions and Answers

By | May 2, 2025

Below are a list JavaScript Interview Questions and Answers for entry level learners, these are basics of java where a starter will learn how to face an interview.

JavaScript Interview Questions and Answers Entry Level:

1.What is the purpose of Java Script?

JavaScript transforms static web pages (HTML, CSS) into interactive and dynamic experiences. It handles user interactions, such as search input and button clicks.

2. What are the roles of JavaScript Engine’s?

A JavaScript engine (e.g., V8 in Chrome, SpiderMonkey in Firefox) is a program within the web browser that interprets and executes JavaScript code received from the server.

3. What is difference between Client-side versus server-side JavaScript?

  • Client-side: Refers to the user’s device (laptop, mobile, desktop) and its browser. The browser runs HTML, CSS, and JavaScript to display and interact with web applications.
  • Server-side: Refers to the computer (server) hosting the website. It’s a powerful machine that handles requests from many clients simultaneously. Server-side code (e.g., in Java, PHP, Node.js) processes requests and delivers the appropriate information back to the client.
  • Interaction: When a user accesses a website, a request is sent from the client (browser) to the server. The server processes the request, generates the necessary data, and sends it back to the client, which then displays it in the browser.

Key Difference: Clients request and consume services, while servers provide those services.

4. JavaScript variables: `var`, `let`, `const` differences.?

  • Variables: Used to store data (e.g., numbers, text).
  • var:
    • Creates function-scoped variables.
    • Variables are accessible throughout the entire function, regardless of where they are declared within it (e.g., inside an if block).
    • Generally considered less desirable due to potential scope confusion.
  • let:
    • Creates block-scoped variables.
    • Variables are only accessible within the block (defined by curly braces {}) in which they are declared (e.g., inside an if block or loop).
    • Preferred over var for clarity and to avoid scope-related issues.
  • const:
    • Creates block-scoped variables with a constant value.
    • The value assigned to a const variable cannot be changed after its initial declaration.
    • Useful for values that should not be modified

5. JavaScript data types: a concise overview?

  • JavaScript automatically identifies data types based on assigned values.
  • Primitive data types (number, string, Boolean, undefined, null) hold only a single value.
  • Non-primitive data types (objects, arrays) can hold multiple values.
  • A data type determines the type of a variable.

6. Explain about JavaScript Data Types Examples?

JavaScript is a dynamically-typed language, which means it does not require explicit type definitions for variables. However, JavaScript does have several built-in data types that can be categorized into two main groups: primitive and complex.

Primitive Data Types

  1. Number

Example: let num = 10;

Description: Represents a numeric value, which can be an integer or a floating-point number.

  1. String

Example: let str = “Hello, World!”;

Description: Represents a sequence of characters, which can be enclosed in single quotes or double quotes.

  1. Boolean

Example: let isAdmin = true;

Description: Represents a logical value, which can be either true or false.

  1. Null

Example: let nullValue = null;

Description: Represents the intentional absence of any object value.

  1. Undefined

Example: let undefinedValue;

7. Describe about Complex Data Types in Java Script?

  1. Object

Example: let person = {name: “John”, age: 30};

Description: Represents a collection of key-value pairs, which can contain primitive and complex data types.

  1. Array

Example: let colors = [“red”,_”green”,_”blue”];

Description: Represents an ordered collection of values, which can be of any data type.

  1. Function

Example: let greet = function(name) { console.log(“Hello, ” + name + “!”); };

Description: Represents a block of code that can be executed with a set of parameters.

Symbol (ES6+)

Example: let sym = Symbol(“unique”);

Description: Represents a unique identifier, which can be used as a property key in objects.

BigInt (ES2020+)

Example: let bigInt = 12345678901234567890n;

Description: Represents an arbitrary-precision integer, which can be used for large integer calculations.

Note: The BigInt data type is only available in modern JavaScript engines that support ECMAScript 2020 or later.

8. Explain about JavaScript operators: types and examples?

  • Operators: Symbols or keywords performing operations on operands (values).
  • Arithmetic Operators: Perform mathematical calculations (e.g., +, -, *, /, %, **).
  • Assignment Operators: Assign values to variables (e.g., =, +=, -=, *=, /=).
  • Comparison Operators: Compare operands and return true or false (e.g., >, <, >=, <=, ==, !=).
  • Logical Operators: Combine or modify boolean expressions (true/false):
    • AND (&&): True only if both operands are true.
    • OR (||): True if at least one operand is true.
    • NOT (!): Inverts the boolean value of the operand.

String Operators: The ‘+’ operator concatenates strings.

9. Explain about JavaScript conditional statement types?

  • If-Else Statements: The most common conditional statement. It checks a condition; if true, a block of code executes; otherwise (else), a different block executes. Nested if-else statements (else if) allow for multiple conditions.
  • Ternary Operator: A concise way to express an if-else statement in a single line. It takes the form condition ? valueIfTrue : valueIfFalse.

Switch Statements: Evaluates an expression and compares its value to multiple cases. If a case matches, the corresponding code block executes. The break keyword is crucial to prevent fallthrough (executing subsequent cases). A default case handles situations where no case matches.

10. if-else Statement: Example: Determining the discount amount for a customer based on their membership status?

let membershipStatus = “gold”;

let discountPercentage;

if (membershipStatus === “gold”) {

discountPercentage = 20;

} else if (membershipStatus === “silver”) {

discountPercentage = 10;

} else {

discountPercentage = 0;

}

console.log(`The discount percentage is ${discountPercentage}%.`);

11. Switch Statement: Example: Displaying a personalized greeting based on the day of the week?

let currentDay = 3; // 0 = Sunday, 1 = Monday, …, 6 = Saturday

let greeting;

switch (currentDay) {

case 0:

greeting = “Happy Sunday!”;

break;

case 1:

greeting = “Happy Monday!”;

break;

case 2:

greeting = “Happy Tuesday!”;

break;

// Additional cases for other days of the week

default:

greeting = “Have a great day!”;

}

console.log(greeting);

12: What is Ternary Operator: Example: Determining the shipping cost based on the order total?

let orderTotal = 75;

let shippingCost = orderTotal > 50 ? 0 : 5;

console.log(`The shipping cost is ${shippingCost}.`);

13: Use Logical AND (&&) and OR (||) Operators: Example: Validating a user’s login credentials?

let username = “myusername”;

let password = “mypassword”;

if (username && password) {

console.log(“Login successful!”);

} else {

console.log(“Invalid username or password.”);

}

14: Explain about JavaScript selectors?

JavaScript selectors retrieve specific elements from the Document Object Model (DOM).

  • getElementById is the simplest selector, retrieving an element by its ID.
  • Four other common selectors exist: getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll.
  • Selectors utilize element IDs, class names, and tag names to target specific DOM element

15. What are different JavaScript selectors and how do you use them practically?

  1. getElementById():

Example: Selecting an element with a specific ID and changing its text content.

“`javascript

let heading = document.getElementById(“main-heading”);

heading.textContent = “Welcome to our website!”;

“`

  1. getElementsByTagName():

Example: Selecting all `<p>` elements on a page and changing their font size.

“`javascript

let paragraphs = document.getElementsByTagName(“p”);

for (let i = 0; i < paragraphs.length; i++) {

paragraphs[i].style.fontSize = “18px”;

}

“`

  1. getElementsByClassName():

Example: Selecting all elements with a specific class and adding an event listener.

“`javascript

let buttons = document.getElementsByClassName(“action-button”);

for (let i = 0; i < buttons.length; i++) {

buttons[i].addEventListener(“click”, handleButtonClick);

}

“`

  1. querySelector():

Example: Selecting the first element that matches a CSS selector and changing its background color.

“`javascript

let firstListItem = document.querySelector(“ul li”);

firstListItem.style.backgroundColor = “#f0f0f0”;

“`

  1. querySelectorAll():

Example: Selecting all elements that match a CSS selector and toggling a CSS class.

“`javascript

let listItems = document.querySelectorAll(“ul li”);

for (let i = 0; i < listItems.length; i++) {

listItems[i].classList.toggle(“selected”);

}

“`

  1. getElementsByName():

Example: Selecting all elements with a specific name attribute and retrieving their values.

“`javascript

let radioButtons = document.getElementsByName(“gender”);

for (let i = 0; i < radioButtons.length; i++) {

if (radioButtons[i].checked) {

console.log(`Selected gender: ${radioButtons[i].value}`);

}

}

“`

  1. getElementsByTagNameNS():

Example: Selecting all SVG elements on a page and manipulating their attributes.

“`javascript

let svgElements = document.getElementsByTagNameNS(“http://www.w3.org/2000/svg”, “*”);

for (let i = 0; i < svgElements.length; i++) {

svgElements[i].setAttribute(“fill”, “#007bff”);

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *