Playwright BDD Framework Step By Step

To build an automated test framework using Playwright, Cucumber (BDD), and the Page Object Model (POM) pattern with TypeScript, follow this structured setup.

Cucumber Framework Official docs

1.Initialize Project & Dependencies:Node.js required.

Create a project directory and install the necessary dependencies for Playwright, @cucumber/cucumber, and TypeScript.

Bash

mkdir playwright-cucumber-pom
cd playwright-cucumber-pom
npm init -y
npm install --save-dev @playwright/test @cucumber/cucumber ts-node typescript @types/node
npx playwright install

2.Configure TypeScript & Cucumber:Set up root configuration files.

Create a tsconfig.json file in your root folder:

JSON

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true
  }
}

Create a cucumber.json file in your root folder to define execution profiles:

JSON

{
  "default": {
    "formatOptions": {
      "snippetInterface": "async-await"
    },
    "paths": ["src/tests/features/**/*.feature"],
    "require": ["src/tests/steps/**/*.ts", "src/hooks/hooks.ts"],
    "requireModule": ["ts-node/register"],
    "format": ["progress", "html:reports/cucumber-report.html"]
  }
}

3.Set Up Browser Hooks & Context Management:Manages browser lifecycle.

Create src/hooks/hooks.ts to manage launching and closing the browser instance before and after scenarios.

TypeScript

import { Before, After, BeforeAll, AfterAll } from '@cucumber/cucumber';
import { Browser, BrowserContext, Page, chromium } from '@playwright/test';

let browser: Browser;
let context: BrowserContext;
export let page: Page;

BeforeAll(async () => {
  browser = await chromium.launch({ headless: false });
});

Before(async () => {
  context = await browser.newContext();
  page = await context.newPage();
});

After(async () => {
  await page.close();
  await context.close();
});

AfterAll(async () => {
  await browser.close();
});

4.Create the Page Object Model (POM):Encapsulate page UI elements and actions.

Create src/pages/LoginPage.ts to store page selectors and interaction logic.

TypeScript

import { Page, Locator } from '@playwright/test';

export class LoginPage {
  private page: Page;
  private usernameInput: Locator;
  private passwordInput: Locator;
  private loginButton: Locator;

  constructor(page: Page) {
    this.page = page;
    this.usernameInput = page.locator('#user-name');
    this.passwordInput = page.locator('#password');
    this.loginButton = page.locator('#login-button');
  }

  async navigateTo(url: string) {
    await this.page.goto(url);
  }

  async login(username: string, password: string) {
    await this.usernameInput.fill(username);
    await this.passwordInput.fill(password);
    await this.loginButton.click();
  }
}

5.Write the Feature File:Define BDD scenarios using Gherkin.

Create src/tests/features/login.feature:

Gherkin

Feature: User Authentication

  Scenario: Successful login with valid credentials
    Given I navigate to "https://www.saucedemo.com/"
    When I log in with username "standard_user" and password "secret_sauce"
    Then I should see the inventory page title "Swag Labs"

6.Implement Step Definitions:Map Feature steps to Page Object code.

Create src/tests/steps/loginSteps.ts:

TypeScript

import { Given, When, Then } from '@cucumber/cucumber';
import { expect } from '@playwright/test';
import { page } from '../../hooks/hooks';
import { LoginPage } from '../../pages/LoginPage';

let loginPage: LoginPage;

Given('I navigate to {string}', async (url: string) => {
  loginPage = new LoginPage(page);
  await loginPage.navigateTo(url);
});

When('I log in with username {string} and password {string}', async (username: string, password: string) => {
  await loginPage.login(username, password);
});

Then('I should see the inventory page title {string}', async (expectedTitle: string) => {
  const actualTitle = await page.title();
  expect(actualTitle).toBe(expectedTitle);
});

7.Add Execution Script & Run Tests:Execute tests via npm.

Update your package.json file to include a test command:

JSON

"scripts": {
  "test": "cucumber-js"
}

Execute your framework in the terminal:

Bash

npm test

Configure Reporting in Cucumber Framework

1. Install Reporter Package:

Bash

npm install --save-dev multiple-cucumber-html-reporter

2. Configure JSON Output in cucumber.json:

Ensure Cucumber outputs test results in JSON format so the reporter engine can process them:

JSON

{
  "default": {
    "requireModule": ["ts-node/register"],
    "require": ["src/hooks/**/*.ts", "src/tests/steps/**/*.ts"],
    "format": ["json:reports/cucumber_report.json"]
  }
}

3. Create Report Generation Generator Script (reporter.js):

Create reporter.js at the root of your project:

JavaScript

const report = require('multiple-cucumber-html-reporter');

report.generate({
  jsonDir: './reports/',
  reportPath: './reports/html-report/',
  metadata: {
    browser: { name: 'chromium', version: 'latest' },
    device: 'Local Test Engine',
    platform: { name: 'Windows/Linux' }
  },
  customData: {
    title: 'Execution Info',
    data: [
      { label: 'Project', value: 'Playwright Cucumber Framework' },
      { label: 'Environment', value: 'Staging' }
    ]
  }
});

3. Update your package.json to unify test execution, reporting, and linting into seamless npm commands:

JSON

"scripts": {
  "test": "cucumber-js || npm run report",
  "test:smoke": "cucumber-js --tags '@smoke' || npm run report",
  "test:parallel": "cucumber-js --parallel 4 || npm run report",
  "report": "node reporter.js"
}

JavaScript Operators Assignment: 60+ Real-Life Practice Questions

Learning JavaScript operators becomes much easier when you practice them with real-world programming problems instead of solving only simple mathematical examples.

In this JavaScript Operators Assignment, you will solve more than 60 practical programming problems based on shopping bills, salary calculations, banking, loan eligibility, electricity bills, cab fares, student results, QA automation reports, and other real-life scenarios.

The exercises cover Arithmetic, Assignment, Comparison, Logical, Unary, Ternary, Optional Chaining, Nullish Coalescing, in, and instanceof operators.

Recommended for: JavaScript beginners, automation testers, QA engineers, SDET candidates, and students preparing for JavaScript or Playwright interviews.


What You Will Practice

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Unary Operators
  • Ternary Operator
  • Optional Chaining Operator
  • Nullish Coalescing Operator
  • in Operator
  • instanceof Operator
  • Combination of multiple JavaScript operators
  • Formula-based JavaScript programs
  • Real-world business calculations

Prerequisites

Before attempting these exercises, you should understand JavaScript variables, data types, basic expressions, and console.log().

You should also be familiar with the basic JavaScript operators explained in the JavaScript Operators tutorial.


1. Arithmetic Operators – Assignment Questions

Arithmetic operators are commonly used for calculations. The main operators include +, -, *, /, %, and **.

Assignment 1: E-Commerce Shopping Bill

An online shopping website has the following products:

1 Laptop = ₹55,000
1 Mouse = ₹750
1 Keyboard = ₹1,500

A customer purchases:

1 Laptop
2 Mouse
1 Keyboard

Write a JavaScript program to calculate the total shopping amount.

Formula:

Total =
(Laptop Price × Quantity)
+ (Mouse Price × Quantity)
+ (Keyboard Price × Quantity)

Assignment 2: Restaurant Bill Split

Four friends visit a restaurant and the total bill is ₹3,850.

Calculate how much each person should pay if the bill is divided equally.

Formula:

Amount Per Person = Total Bill / Number of People

Assignment 3: Employee Net Salary

An employee has:

Basic Salary = ₹40,000
HRA = ₹8,000
Bonus = ₹5,000
Tax = ₹4,500

Calculate the gross salary and net salary.

Formula:

Gross Salary = Basic Salary + HRA + Bonus

Net Salary = Gross Salary - Tax

Assignment 4: Simple Interest Calculator

Create a program using:

Principal = ₹100,000
Rate = 8%
Time = 3 years

Calculate simple interest and total amount.

Formula:

SI = (Principal × Rate × Time) / 100

Total Amount = Principal + SI

Assignment 5: Compound Interest Calculator

Calculate compound interest for:

Principal = ₹50,000
Rate = 10%
Time = 2 years

Use the exponentiation operator **.

Formula:

Amount = Principal × (1 + Rate / 100) ** Time

Compound Interest = Amount - Principal

Assignment 6: Celsius to Fahrenheit

A weather application receives temperature in Celsius.

Celsius = 35

Convert it into Fahrenheit.

Formula:

Fahrenheit = (Celsius × 9 / 5) + 32

Assignment 7: BMI Calculator

A person’s weight is 72 kg and height is 1.75 meters.

Calculate BMI.

Formula:

BMI = Weight / Height²

Use the ** operator to calculate the square of the height.

Assignment 8: Rectangle Area and Perimeter

Create a program for:

Length = 15
Width = 8

Calculate:

Area = Length × Width

Perimeter = 2 × (Length + Width)

Assignment 9: Student Group Calculation

A teacher has 53 students and wants to create groups of 5 students.

Calculate:

  • Number of complete groups
  • Number of remaining students

Use both / and %.

Assignment 10: Convert Minutes into Hours

A training video has a duration of 367 minutes.

Convert the duration into hours and remaining minutes.

Expected format:

6 Hours 7 Minutes

Use division and modulus operators.


2. Assignment Operators – Assignment Questions

Assignment operators are useful when a variable needs to be updated based on its existing value.

Assignment 11: Bank Account Transactions

A customer’s bank balance is ₹50,000.

Perform these transactions:

Salary credited = ₹25,000
Electricity Bill = ₹3,500
Shopping = ₹7,000

Use += and -= to update the balance.

Assignment 12: Shopping Cart Update

The shopping cart initially contains products worth ₹2,000.

Add:

Shoes = ₹3,500
Shirt = ₹1,200

Then remove an item worth ₹800.

Use assignment operators to calculate the final cart value.

Assignment 13: Product Price Increase

A laptop costs ₹50,000. The manufacturer increases the price by 10%.

Update the price using an assignment operator.

Hint:

price += price * 10 / 100;

Assignment 14: Employee Salary Hike

An employee earns ₹60,000 per month. The company gives a 15% salary hike.

Update the salary using an assignment operator.

Assignment 15: Game Score Calculator

A player starts with a score of 100.

Perform the following:

Enemy defeated → +50
Bonus collected → +100
Penalty → -30
Score doubled → ×2

Use +=, -=, and *=.


3. Comparison Operators – Assignment Questions

Comparison operators return Boolean values such as true or false. They are commonly used in validation and decision-making logic.

Assignment 16: Voting Eligibility

A person is 20 years old.

Check whether the person is eligible to vote.

Condition:

Age >= 18

Assignment 17: Exam Passing Status

A student scores 39 marks and the passing marks are 40.

Determine whether the student has passed.

Assignment 18: Free Delivery Eligibility

An e-commerce website provides free delivery for orders of ₹999 or more.

Create an order amount and check whether the customer qualifies for free delivery.

Assignment 19: Loose vs Strict Equality

Consider:

let otpFromServer = 123456;
let otpFromUser = "123456";

Compare the values using both:

==
===

Observe the result and explain why the two operators behave differently.

Assignment 20: Product Stock Validation

A store has 10 units of a product, but the customer requests 12 units.

Determine whether sufficient stock is available.

Use:

Requested Quantity <= Available Quantity

Assignment 21: Speed Limit Checker

A car is travelling at 85 km/h on a road where the speed limit is 80 km/h.

Write a program to determine whether the driver has exceeded the speed limit.


4. Logical Operators – Assignment Questions

Logical operators such as &&, ||, and ! are used to combine or reverse conditions.

Assignment 22: Bank Loan Eligibility

A bank approves a loan when:

Age >= 21
AND
Monthly Salary >= ₹25,000
AND
Credit Score >= 700

Use the && operator to determine eligibility.

Assignment 23: Login Validation

A user should be allowed to log in only when both the username and password are correct.

Username = "admin"
Password = "admin123"

Use &&.

Assignment 24: Discount Eligibility

A shopping website gives a discount when either:

  • The customer is a Premium Member.
  • The order amount is ₹5,000 or more.

Use the || operator.

Assignment 25: Job Eligibility

A company requires:

Experience >= 3 years
JavaScript Skill = true
Automation Skill = true

Determine whether the candidate is eligible.

Assignment 26: Movie Ticket Eligibility

A person can watch a movie when either:

  • Age is 18 or above.
  • Parent permission is available.

Use the || operator.

Assignment 27: Account Status

Given:

let accountBlocked = false;

Use the ! operator to determine whether the account is active.


5. Unary Operators – Assignment Questions

Unary operators work with a single operand. Common examples include ++, --, typeof, and !.

Assignment 28: Website Visitor Counter

A website currently has 1,000 visitors.

When a new visitor opens the website, increase the count using ++.

Assignment 29: Inventory Counter

A store has 50 units of a product.

A customer purchases one item. Reduce the stock using --.

Assignment 30: Cricket Score Counter

A batsman has scored 49 runs and scores one additional run.

Use ++ to update the score.

Assignment 31: Identify JavaScript Data Types

Create variables for:

name = "Rahul"
age = 25
isEmployee = true
salary = undefined

Use typeof to determine the data type of each variable.

Assignment 32: Login Status Reversal

Given:

let isLoggedIn = false;

Use ! to reverse the login status.


6. Ternary Operator – Assignment Questions

The ternary operator provides a concise way to write simple conditional expressions.

Syntax:

condition ? value1 : value2;

Assignment 33: Student Pass or Fail

A student scores 65 marks.

Display Pass when marks are 40 or above; otherwise display Fail.

Use the ternary operator.

Assignment 34: Adult or Minor

A person’s age is 17.

Use the ternary operator to display either Adult or Minor.

Assignment 35: Free Delivery

An online order is worth ₹1,200.

Display:

Free Delivery

when the order amount is at least ₹999; otherwise display:

Delivery Charge ₹100

Assignment 36: Even or Odd

Given:

let number = 27;

Use the modulus operator together with the ternary operator to determine whether the number is even or odd.

Assignment 37: Maximum of Two Numbers

Given:

Number1 = 45
Number2 = 78

Use the ternary operator to determine the larger number.

Assignment 38: Employee Bonus

An employee receives a ₹10,000 bonus when years of service are 5 or more. Otherwise, the employee receives ₹5,000.

Calculate the bonus using the ternary operator.


7. Optional Chaining Operator ?.

Optional chaining is useful when working with objects or API responses where a property may not exist.

Assignment 39: Customer Address

let customer = {
    name: "Rahul",
    address: {
        city: "Bhopal"
    }
};

Safely retrieve:

customer.address.city
customer.address.pincode

Use optional chaining so that the program does not throw an error when the property does not exist.

Assignment 40: API Response Validation

let response = {
    user: {
        profile: {
            name: "Amit"
        }
    }
};

Safely access:

response.user.profile.name
response.user.profile.mobile
response.user.address.city

Use ?..


8. Nullish Coalescing Operator ??

The nullish coalescing operator can be used to provide a default value when a variable is null or undefined.

Assignment 41: Default Username

let username = null;

Display Guest User when the username is null or undefined.

Use ??.

Assignment 42: Default Product Discount

An API returns:

let discount = null;

If the discount is unavailable, use 0 as the default value.

Assignment 43: Employee Salary

let employee = {
    name: "John"
};

Safely retrieve the employee’s salary.

If the salary is unavailable, display:

Salary Not Available

Combine ?. and ??.


9. in Operator – Assignment Questions

The in operator is useful when checking whether a property exists in an object.

Assignment 44: User Profile Validation

let user = {
    name: "Rahul",
    email: "rahul@gmail.com"
};

Check whether the following properties exist:

name
email
mobile

Use the in operator.

Assignment 45: Product Information Validation

let product = {
    id: 101,
    name: "Laptop",
    price: 55000
};

Check whether the following properties exist:

price
discount
stock

10. instanceof Operator – Assignment Questions

Assignment 46: Employee Object Validation

Create an Employee class:

class Employee {
    constructor(name) {
        this.name = name;
    }
}

Create an employee object and use instanceof to verify that the object belongs to the Employee class.

Assignment 47: Array Validation

Create:

let products = ["Laptop", "Mouse", "Keyboard"];

Use instanceof to determine whether products is an instance of Array.


11. Mixed JavaScript Operator Challenges

The following problems are designed to simulate real application scenarios. You will need to combine multiple JavaScript operators.

Assignment 48: E-Commerce Final Bill Calculator

A customer purchases:

Laptop = ₹50,000
Mouse = ₹1,000
Keyboard = ₹2,000

Discount rules:

Purchase >= ₹50,000 → 10% discount
Otherwise → 5% discount

GST is 18%.

Calculate:

  • Subtotal
  • Discount
  • Amount after discount
  • GST
  • Final amount

Formulas:

Subtotal = Laptop + Mouse + Keyboard

Discount = Subtotal × DiscountPercentage / 100

AmountAfterDiscount = Subtotal - Discount

GST = AmountAfterDiscount × 18 / 100

FinalAmount = AmountAfterDiscount + GST

Assignment 49: Employee Monthly Salary Calculator

Employee details:

Basic Salary = ₹50,000
HRA = 20%
DA = 10%
PF = 12%
Tax = 5%

Calculate HRA, DA, gross salary, PF deduction, tax deduction, and net salary.

Formulas:

HRA = Basic × 20 / 100
DA = Basic × 10 / 100
Gross = Basic + HRA + DA
PF = Basic × 12 / 100
Tax = Gross × 5 / 100
Net Salary = Gross - PF - Tax

Assignment 50: Electricity Bill Calculator

A customer consumes 350 units.

Billing rules:

First 100 units → ₹5/unit
Next 200 units → ₹7/unit
Above 300 units → ₹10/unit

Calculate the final electricity bill.

Challenge: Calculate the bill slab by slab rather than multiplying all units by ₹10.

Assignment 51: Cab Fare Calculator

A cab company charges:

Base Fare = ₹50
Per KM Charge = ₹12
Distance = 25 KM

If the distance exceeds 20 KM, add a long-distance charge of ₹100.

Calculate the final fare.

Formula:

Fare = Base Fare + Distance × PerKM

Assignment 52: EMI Calculator

Calculate the approximate monthly EMI for:

Loan Amount = ₹500,000
Annual Interest Rate = 10%
Loan Duration = 5 Years

Use:

Monthly Rate = Annual Rate / 12 / 100

Number of Payments = Years × 12

EMI =
P × R × (1 + R)^N
-----------------
(1 + R)^N - 1

Where P is the principal, R is the monthly interest rate, and N is the number of monthly payments.

Assignment 53: Student Result Calculator

A student has the following marks:

Math = 78
Science = 82
English = 69
Computer = 91
Hindi = 74

Calculate:

  • Total marks
  • Percentage
  • Pass/Fail status
  • Grade

Grade rules:

Percentage >= 90 → A+
Percentage >= 80 → A
Percentage >= 70 → B
Percentage >= 60 → C
Percentage >= 40 → D
Below 40 → Fail

The student must also fail if any individual subject mark is below 40.

Assignment 54: Online Shopping Checkout

Customer details:

Cart Amount = ₹4,500
Premium Member = true
Coupon Available = true

Rules:

  • Premium Member → 10% discount
  • Coupon Available → Additional ₹500 discount
  • Orders of ₹3,000 or more → Free delivery
  • Otherwise → ₹100 delivery charge

Calculate the final payable amount.

Use arithmetic, comparison, logical, ternary, and assignment operators.

Assignment 55: Bank Loan EMI Eligibility

Customer details:

Age = 30
Monthly Salary = ₹60,000
Existing EMI = ₹10,000
Credit Score = 750
Requested EMI = ₹18,000

Eligibility rules:

Age >= 21 AND Age <= 60

Credit Score >= 700

Total EMI <= 50% of Monthly Salary

Calculate:

Total EMI = Existing EMI + Requested EMI

Maximum Allowed EMI = Salary × 50 / 100

Display Loan Approved or Loan Rejected.


12. Bonus JavaScript Operator Challenges

Assignment 56: Food Delivery Order Calculator

Create a food delivery billing program with:

Food Amount = ₹850
Delivery Distance = 7 KM
Premium Member = false
Coupon Discount = ₹100

Rules:

  • Food Amount of ₹500 or more → 5% discount
  • Premium Member → Free delivery
  • Non-premium and distance <= 5 KM → ₹40 delivery
  • Non-premium and distance > 5 KM → ₹80 delivery
  • GST = 5%

Calculate the final payable amount.

Assignment 57: Fuel Cost Calculator

A car travels 650 KM.

Distance = 650 KM
Mileage = 18 KM/L
Petrol Price = ₹105/L

Calculate:

Fuel Required = Distance / Mileage

Fuel Cost = Fuel Required × Petrol Price

If the fuel cost exceeds ₹3,000, calculate the amount exceeding the budget.

Assignment 58: Profit Percentage Calculator

A shopkeeper purchases a laptop for ₹45,000 and sells it for ₹52,000.

Calculate:

Profit = Selling Price - Cost Price

Profit Percentage =
Profit / Cost Price × 100

Finally determine whether the transaction resulted in profit or loss.

Assignment 59: Attendance Calculator

A student has:

Total Classes = 120
Classes Attended = 92

Calculate:

Attendance Percentage =
Classes Attended / Total Classes × 100

The student is eligible for the examination only when attendance is at least 75%.

Assignment 60: QA Automation Test Report

An automation test suite contains:

Total Tests = 250
Passed = 210
Failed = 25
Skipped = 15

Calculate:

  • Pass Percentage
  • Failure Percentage
  • Skipped Percentage

Formula:

Percentage = Count / Total Tests × 100

The build is considered PASSED when:

Pass Percentage >= 90
AND
Failed Tests <= 10

Otherwise, display FAILED.


13. Final Mini Project – Employee Payroll System

This is the final challenge. Build a complete employee payroll calculator using multiple JavaScript operators.

Employee Information

Employee Name = "Rahul"
Basic Salary = ₹60,000
Performance Rating = 4.5
Years of Service = 6

Salary Components

HRA = 20% of Basic Salary
DA = 10% of Basic Salary
PF = 12% of Basic Salary

Performance Bonus Rules

Rating >= 4.5 → 15% Bonus
Rating >= 4.0 → 10% Bonus
Rating >= 3.0 → 5% Bonus
Otherwise → No Bonus

Loyalty Bonus

If years of service are 5 or more, the employee receives a ₹10,000 loyalty bonus.

Calculate

  • HRA
  • DA
  • Performance Bonus
  • Loyalty Bonus
  • Gross Salary
  • PF
  • Net Salary

Expected Output Format

Employee: Rahul
Basic Salary: ₹60000
HRA: ₹____
DA: ₹____
Performance Bonus: ₹____
Loyalty Bonus: ₹____
Gross Salary: ₹____
PF Deduction: ₹____
Net Salary: ₹____

How to Solve These JavaScript Assignments

Follow these steps for every problem:

  1. Read the problem carefully.
  2. Identify the input values.
  3. Identify the required output.
  4. Write the mathematical formula if applicable.
  5. Identify which JavaScript operators are required.
  6. Create meaningful variables.
  7. Implement the calculation or condition.
  8. Display the result using console.log().
  9. Test the program with different input values.

Assignment Rules for Students

  1. Use meaningful variable names.
  2. Do not hardcode calculated results.
  3. Use the operator relevant to each assignment.
  4. Display intermediate calculations where appropriate.
  5. Add comments explaining important formulas.
  6. For challenge programs, combine multiple operator types.
  7. Test each program with at least two different sets of input values.
  8. Use console.log() to clearly display the final output.
  9. For formula-based problems, write the formula as a comment before implementing it.
  10. Try to solve the problem independently before looking at a solution.

JavaScript Operators Assignment – Learning Outcome

After completing these assignments, you should be comfortable using JavaScript operators to solve practical programming problems involving calculations, validation, decision-making, object handling, and business logic.

These exercises are particularly useful for students preparing for JavaScript interviews, QA automation, SDET interviews, Selenium JavaScript automation, and Playwright with TypeScript.

Frequently Asked Questions

What are JavaScript operators?

JavaScript operators are symbols or keywords used to perform operations on values and variables. They are commonly used for calculations, comparisons, assignments, logical conditions, and object-related operations.

What are the main types of JavaScript operators?

The commonly used categories include arithmetic, assignment, comparison, logical, unary, ternary, and special operators such as optional chaining, nullish coalescing, in, and instanceof.

Which JavaScript operators should beginners learn first?

Beginners should first learn arithmetic, assignment, comparison, logical, and ternary operators. Once these are comfortable, they can move to unary and modern operators such as ?. and ??.

Why should JavaScript operators be practiced using real-life problems?

Real-life problems help students understand how operators are used in applications such as shopping carts, banking systems, payroll applications, billing systems, login validation, and test automation reports.

Are these JavaScript operator exercises suitable for interviews?

Yes. These exercises are useful for building the calculation and logical reasoning skills commonly tested in JavaScript and automation interviews.

Conclusion

Practicing JavaScript operators through real-world scenarios is one of the best ways to strengthen JavaScript fundamentals. Instead of memorizing operator definitions, solve problems involving shopping bills, salaries, banking, loans, electricity bills, student results, and automation reports.

Start with the basic arithmetic assignments and gradually move toward the mixed operator challenges and the final employee payroll project.

Tip: Do not immediately look for the solution. First identify the required formula, select the appropriate operators, write the logic yourself, and then test your program with different inputs.

Next Step: After completing these assignments, practice JavaScript Arrays, JavaScript Functions, objects, loops, and scenario-based JavaScript programs to build stronger programming skills.

JavaScript Interview Questions and Answers

Are you preparing for a JavaScript interview? This comprehensive guide covers 100+ JavaScript interview questions and answers from beginner to advanced levels.

These questions are useful for JavaScript Developers, Frontend Developers, QA Automation Engineers, SDETs, and Playwright Automation Engineers.

The questions are organized into different categories, including JavaScript fundamentals, variables, data types, functions, arrays, objects, promises, asynchronous JavaScript, closures, OOP, event handling, and advanced JavaScript concepts.


JavaScript Interview Questions for Beginners

1. What is JavaScript?

Answer: JavaScript is a high-level programming language used to create dynamic and interactive web applications.

JavaScript can run in:

  • Web browsers
  • Node.js
  • Playwright
  • Backend applications
  • Desktop and mobile applications
let name = "Deepesh";

console.log(`Hello ${name}`);

2. What are the features of JavaScript?

Answer: Some important features of JavaScript are:

  • Lightweight
  • Dynamically typed
  • Object-oriented
  • Prototype-based
  • Event-driven
  • Supports asynchronous programming
  • Supports functional programming
  • Supports first-class functions
  • Cross-platform
  • Supports modules

3. Is JavaScript the same as Java?

Answer: No. JavaScript and Java are completely different programming languages.

JavaScript Java
Dynamically typed Statically typed
Primarily used for web applications and scripting General-purpose programming language
Prototype-based Class-based
Runs in browsers and Node.js Runs on the JVM

JavaScript Variables and Data Types

4. What is a variable in JavaScript?

Answer: A variable is a named container used to store data.

JavaScript provides three keywords for declaring variables:

var x = 10;
let y = 20;
const z = 30;

Modern JavaScript generally prefers let and const.


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

Feature var let const
Scope Function Block Block
Redeclaration Yes No No
Reassignment Yes Yes No
Hoisting Yes Yes, TDZ Yes, TDZ
let age = 25;

age = 30;

const country = "India";

// country = "USA"; // Error

6. What are the data types in JavaScript?

Answer: JavaScript data types can be broadly divided into primitive and non-primitive types.

Primitive Data Types

  • String
  • Number
  • BigInt
  • Boolean
  • Undefined
  • Null
  • Symbol

Non-Primitive Data Types

  • Object
  • Array
  • Function
let name = "John";
let age = 25;
let active = true;
let value;
let data = null;
let user = {};
let numbers = [1, 2, 3];

7. What is the difference between null and undefined?

Answer:

undefined generally means that a variable has been declared but has not been assigned a value.

let x;

console.log(x); // undefined

null represents an intentional absence of a value.

let user = null;

8. What is typeof in JavaScript?

Answer: typeof is an operator used to determine the type of a value.

console.log(typeof "Hello"); // string
console.log(typeof 10);      // number
console.log(typeof true);    // boolean
console.log(typeof {});      // object

One well-known JavaScript behavior is:

console.log(typeof null);

Output:

object

This is a historical behavior of JavaScript.


JavaScript Operators

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

Answer:

== performs loose equality and may perform type conversion.

=== performs strict equality and checks both value and type.

console.log(5 == "5");  // true
console.log(5 === "5"); // false

In modern JavaScript, === is generally preferred.


10. What is the difference between != and !==?

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

!= performs loose inequality, while !== performs strict inequality.


JavaScript Functions

11. What is a function in JavaScript?

Answer: A function is a reusable block of code designed to perform a specific task.

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

console.log(add(10, 20));

Output:

30

12. What is a function expression?

Answer: A function expression is a function assigned to a variable.

const add = function(a, b) {
    return a + b;
};

console.log(add(10, 20));

13. What is an arrow function?

Answer: Arrow functions provide a shorter syntax for writing functions.

const add = (a, b) => {
    return a + b;
};

It can also be written as:

const add = (a, b) => a + b;

14. What is the difference between a normal function and an arrow function?

One of the most important differences is how they handle this.

const user = {
    name: "John",

    greet: function() {
        console.log(this.name);
    }
};

user.greet();

Arrow functions do not create their own this. They inherit this from their surrounding lexical scope.


JavaScript Scope and Hoisting

15. What is scope?

Answer: Scope determines where a variable can be accessed in a JavaScript program.

Common types of scope include:

  • Global scope
  • Function scope
  • Block scope
  • Module scope

16. What is hoisting?

Answer: Hoisting describes how JavaScript processes declarations before executing code within their relevant scope.

console.log(x);

var x = 10;

Output:

undefined

With let:

console.log(x);

let x = 10;

This results in a ReferenceError because the variable is in the Temporal Dead Zone until initialization.


17. What is the Temporal Dead Zone?

Answer: The Temporal Dead Zone, commonly called TDZ, is the period between entering a scope and the point where a let or const variable is initialized.

console.log(name);

let name = "John";

The variable cannot be accessed before its initialization.


JavaScript Arrays

18. What is an array?

Answer: An array is an ordered collection of values.

const numbers = [10, 20, 30, 40];

console.log(numbers[0]); // 10

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

map()

Creates a new array by transforming every element.

const numbers = [1, 2, 3];

const result = numbers.map(n => n * 2);

console.log(result);

Output:

[2, 4, 6]

filter()

Creates a new array containing elements that satisfy a condition.

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

const result = numbers.filter(n => n % 2 === 0);

console.log(result);

Output:

[2, 4]

forEach()

Executes a function for each element.

numbers.forEach(n => console.log(n));

Interview Tip: Use map() when you need a transformed array, filter() when you need selected elements, and forEach() when you simply want to perform an action for each element.


20. What is reduce()?

Answer: reduce() is used to reduce an array to a single value.

const numbers = [10, 20, 30];

const total = numbers.reduce((sum, value) => {
    return sum + value;
}, 0);

console.log(total);

Output:

60

21. What is find()?

Answer: find() returns the first element that satisfies a condition.

const users = [
    { id: 1, name: "John" },
    { id: 2, name: "David" },
    { id: 3, name: "Alex" }
];

const user = users.find(user => user.id === 2);

console.log(user);

Output:

{ id: 2, name: "David" }

22. What is the difference between find() and filter()?

find() returns the first matching element.

numbers.find(n => n > 10);

filter() returns all matching elements.

numbers.filter(n => n > 10);

23. What are some() and every()?

some() checks whether at least one element satisfies a condition.

const numbers = [1, 3, 5, 8];

console.log(
    numbers.some(n => n % 2 === 0)
);

Output:

true

every() checks whether all elements satisfy a condition.

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

console.log(
    numbers.every(n => n % 2 === 0)
);

Output:

true

JavaScript Objects

24. What is an object?

Answer: An object stores data in key-value pairs.

const user = {
    name: "John",
    age: 30,
    city: "Delhi"
};

console.log(user.name);

25. How can you access object properties?

There are several ways to access object properties.

user.name;
user["name"];

You can also use a variable:

const key = "name";

console.log(user[key]);

26. What is object destructuring?

Answer: Destructuring allows values to be extracted from objects into variables.

const user = {
    name: "John",
    age: 30
};

const { name, age } = user;

console.log(name);
console.log(age);

27. What is array destructuring?

const numbers = [10, 20];

const [a, b] = numbers;

console.log(a);
console.log(b);

28. What is the spread operator?

Answer: The spread operator ... expands the elements of an iterable or properties of an object.

const arr1 = [1, 2, 3];

const arr2 = [...arr1, 4, 5];

console.log(arr2);

Output:

[1, 2, 3, 4, 5]

Object example:

const user = {
    name: "John",
    age: 30
};

const updatedUser = {
    ...user,
    city: "Delhi"
};

29. What is the rest operator?

Answer: The rest operator collects multiple values into a single array.

function add(...numbers) {

    return numbers.reduce(
        (sum, n) => sum + n,
        0
    );
}

console.log(add(10, 20, 30));

Output:

60

JavaScript Closures

30. What is a closure?

Answer: A closure occurs when an inner function remembers and can access variables from its outer function even after the outer function has finished executing.

function outer() {

    let count = 0;

    return function() {
        count++;
        return count;
    };
}

const counter = outer();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

Closures are commonly used for:

  • Data privacy
  • Counters
  • Callbacks
  • Function factories
  • Event handlers

JavaScript this Keyword

31. What is this in JavaScript?

Answer: this is a context-dependent value. Its value depends on how a function is called.

const user = {

    name: "John",

    greet() {
        console.log(this.name);
    }

};

user.greet();

In this example, this refers to the user object.


32. What are call(), apply(), and bind()?

These methods are used to control the value of this.

call()

function greet(city) {
    console.log(this.name, city);
}

const user = {
    name: "John"
};

greet.call(user, "Delhi");

apply()

apply() accepts arguments as an array.

greet.apply(user, ["Delhi"]);

bind()

bind() returns a new function.

const newFunction = greet.bind(user, "Delhi");

newFunction();

Asynchronous JavaScript

33. What is synchronous execution?

Answer: Synchronous code executes one operation at a time in sequence.

console.log("A");
console.log("B");
console.log("C");

Output:

A
B
C

34. What is asynchronous JavaScript?

Answer: Asynchronous JavaScript allows certain operations to complete later without blocking the execution of other code.

Common examples include:

  • API requests
  • Timers
  • File operations
  • Database operations
  • Browser events

35. What is a callback function?

Answer: A callback is a function passed to another function to be executed later.

function greet(name, callback) {

    console.log("Hello " + name);

    callback();
}

greet("John", function() {
    console.log("Welcome!");
});

JavaScript Promises

36. What is a Promise?

Answer: A Promise represents the eventual completion or failure of an asynchronous operation.

A Promise has three states:

  1. Pending
  2. Fulfilled
  3. Rejected
const promise = new Promise((resolve, reject) => {

    const success = true;

    if (success) {
        resolve("Operation successful");
    } else {
        reject("Operation failed");
    }

});

37. How do you consume a Promise?

promise
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.log(error);
    })
    .finally(() => {
        console.log("Completed");
    });

38. What is async/await?

Answer: async/await provides a cleaner syntax for working with Promises.

async function getData() {

    const response =
        await fetch("https://example.com/api/users");

    const data = await response.json();

    console.log(data);
}

await pauses execution of the current async function until the awaited Promise settles. It does not block the entire JavaScript runtime.


39. What is Promise.all()?

Answer: Promise.all() waits for multiple Promises and fulfills when all of them fulfill.

const p1 = Promise.resolve("A");
const p2 = Promise.resolve("B");
const p3 = Promise.resolve("C");

const result = await Promise.all([
    p1,
    p2,
    p3
]);

console.log(result);

Output:

["A", "B", "C"]

If one Promise rejects, Promise.all() rejects.


40. What is Promise.allSettled()?

Answer: Promise.allSettled() waits for all Promises to settle, regardless of whether they fulfill or reject.

const results = await Promise.allSettled([
    Promise.resolve("Success"),
    Promise.reject("Failed")
]);

console.log(results);

41. What is Promise.race()?

Answer: Promise.race() returns the result of the first Promise that settles.

const p1 = new Promise(resolve => {
    setTimeout(() => resolve("First"), 1000);
});

const p2 = new Promise(resolve => {
    setTimeout(() => resolve("Second"), 500);
});

const result = await Promise.race([p1, p2]);

console.log(result);

Output:

Second

42. What is Promise.any()?

Answer: Promise.any() fulfills when the first Promise fulfills.

const result = await Promise.any([
    Promise.reject("Error 1"),
    Promise.resolve("Success"),
    Promise.resolve("Success 2")
]);

console.log(result);

Output:

Success

JavaScript Event Loop

43. What is the event loop?

Answer: The event loop is a mechanism that allows JavaScript to handle asynchronous operations while JavaScript execution itself is single-threaded.

A simplified model is:

Call Stack
    ↓
Host APIs
    ↓
Task / Microtask Queues
    ↓
Event Loop
    ↓
Call Stack

44. What are microtasks and tasks?

Answer:

Microtasks include Promise reactions and queueMicrotask().

Tasks include operations such as timer callbacks and certain host events.

console.log("1");

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

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

console.log("4");

Output:

1
4
3
2

The synchronous code executes first, followed by the Promise microtask, and then the timer task.


JavaScript Error Handling

45. What is exception handling?

Answer: JavaScript provides try, catch, finally, and throw for handling errors.

try {

    let result = 10 / 0;

    console.log(result);

} catch (error) {

    console.log(error.message);

} finally {

    console.log("Execution completed");
}

46. What is throw?

Answer: The throw statement allows developers to manually generate an error.

function validateAge(age) {

    if (age < 18) {
        throw new Error("Age must be 18 or above");
    }

    return true;
}

JavaScript Object-Oriented Programming

47. Does JavaScript support OOP?

Answer: Yes. JavaScript supports object-oriented programming using prototypes and modern class syntax.

class Employee {

    constructor(name, salary) {
        this.name = name;
        this.salary = salary;
    }

    display() {
        console.log(this.name, this.salary);
    }
}

const emp = new Employee("John", 50000);

emp.display();

48. What is inheritance?

Answer: Inheritance allows one class to reuse properties and methods from another class.

class Animal {

    eat() {
        console.log("Eating");
    }
}

class Dog extends Animal {

    bark() {
        console.log("Barking");
    }
}

const dog = new Dog();

dog.eat();
dog.bark();

49. What is a prototype?

Answer: JavaScript uses a prototype-based inheritance model.

Objects can inherit properties and methods through the prototype chain.

const user = {
    name: "John"
};

console.log(Object.getPrototypeOf(user));

Advanced JavaScript Interview Questions

50. What is shallow copy and deep copy?

A shallow copy copies the outer structure, but nested objects can still be shared.

const user = {
    name: "John",
    address: {
        city: "Delhi"
    }
};

const copy = {
    ...user
};

copy.address still refers to the same nested object.

For many data structures, a modern deep-copy approach is:

const deepCopy = structuredClone(user);

51. What is optional chaining?

Answer: Optional chaining ?. allows safe access to potentially missing properties.

const user = {};

console.log(user.address?.city);

The result is undefined instead of throwing an error.


52. What is the nullish coalescing operator?

Answer: The ?? operator provides a default value when the left-hand side is null or undefined.

const username = null;

console.log(username ?? "Guest");

Output:

Guest

53. What is the difference between || and ???

console.log(0 || 100);  // 100
console.log(0 ?? 100);  // 0

console.log(false || true); // true
console.log(false ?? true); // false

|| checks for falsy values, while ?? checks specifically for null and undefined.


54. What is an IIFE?

Answer: IIFE stands for Immediately Invoked Function Expression.

(function() {
    console.log("Executed immediately");
})();

Arrow function syntax can also be used:

(() => {
    console.log("Hello");
})();

55. What is a JavaScript module?

Answer: A module is a JavaScript file that can export functionality for use in another file.

Export:

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

Import:

import { add } from "./calculator.js";

console.log(add(10, 20));

56. What is the difference between named export and default export?

Named export:

export function login() {
    console.log("Login");
}

Import:

import { login } from "./auth.js";

Default export:

export default function login() {
    console.log("Login");
}

Import:

import login from "./auth.js";

57. What is strict mode?

Answer: Strict mode enables a stricter set of JavaScript rules.

"use strict";

x = 10;

This produces an error because x was not declared.

JavaScript modules are automatically executed in strict mode.


58. What is type coercion?

Answer: Type coercion is the conversion of one data type into another.

console.log("5" + 2);

Output:

52

Here JavaScript converts the number into a string.

Another example:

console.log("5" - 2);

Output:

3

Here JavaScript converts the string into a number.


59. What are truthy and falsy values?

Answer: A value is truthy if JavaScript treats it as true in a Boolean context.

Common falsy values include:

false
0
-0
0n
""
null
undefined
NaN

Most other values are truthy, including:

[]
{}
"false"
"0"

60. What is short-circuit evaluation?

Answer: JavaScript logical operators can stop evaluating once the result is known.

const name = "";

const result = name || "Guest";

console.log(result);

Output:

Guest

JavaScript Map and Set

61. What is Map in JavaScript?

Answer: Map is a collection of key-value pairs.

const users = new Map();

users.set(1, "John");
users.set(2, "David");

console.log(users.get(1));

Output:

John

Common methods include:

  • set()
  • get()
  • has()
  • delete()
  • clear()

62. What is Set in JavaScript?

Answer: A Set is a collection of unique values.

const numbers = new Set([1, 2, 2, 3, 3]);

console.log(numbers);

A common use case is removing duplicates:

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

const unique = [...new Set(numbers)];

console.log(unique);

Performance and Advanced Concepts

63. What is garbage collection?

Answer: Garbage collection is the process through which the JavaScript runtime identifies objects that are no longer reachable and reclaims their memory.

let user = {
    name: "John"
};

user = null;

If no other reference points to the original object, it can become eligible for garbage collection.


64. What is a memory leak?

Answer: A memory leak occurs when memory that is no longer needed remains reachable and therefore cannot be reclaimed.

Common causes include:

  • Unremoved event listeners
  • Long-lived global variables
  • Forgotten timers
  • Unnecessary object references
  • Unbounded caches

65. What is currying?

Answer: Currying converts a function with multiple arguments into a sequence of functions that each accept one argument.

function add(a) {

    return function(b) {
        return a + b;
    };

}

console.log(add(10)(20));

Output:

30

66. What is function composition?

Answer: Function composition means combining multiple functions so that the output of one function becomes the input of another.

const double = x => x * 2;

const square = x => x * x;

const result = square(double(5));

console.log(result);

Output:

100

67. What is memoization?

Answer: Memoization is an optimization technique where function results are cached so that repeated calculations can be avoided.

function memoize(fn) {

    const cache = new Map();

    return function(value) {

        if (cache.has(value)) {
            return cache.get(value);
        }

        const result = fn(value);

        cache.set(value, result);

        return result;
    };
}

68. What is debouncing?

Answer: Debouncing delays function execution until a specified period has passed without another call.

It is commonly used for:

  • Search boxes
  • Auto-save
  • Input validation
  • Window resize events
function debounce(fn, delay) {

    let timer;

    return function(...args) {

        clearTimeout(timer);

        timer = setTimeout(() => {
            fn(...args);
        }, delay);
    };
}

69. What is throttling?

Answer: Throttling limits how frequently a function can execute.

It is commonly used for:

  • Scroll events
  • Mouse movement
  • Window resize
  • Continuous browser events

Important difference:

  • Debouncing: Executes after activity stops.
  • Throttling: Executes at controlled intervals during activity.

DOM and Event Handling

70. What is the DOM?

Answer: DOM stands for Document Object Model.

The browser represents an HTML document as a tree-like object structure that JavaScript can interact with.

document.getElementById("username");

71. What is event bubbling?

Answer: Event bubbling means an event triggered on a child element can propagate upward through its parent elements.

button
   ↓
div
   ↓
body
   ↓
document

72. What is event capturing?

Answer: Event capturing is the propagation of an event from an outer ancestor toward the target element.

document
   ↓
body
   ↓
div
   ↓
button

73. What is event delegation?

Answer: Event delegation means attaching an event listener to a parent instead of adding separate listeners to every child element.

document
    .getElementById("products")
    .addEventListener("click", event => {

        if (event.target.matches(".product")) {
            console.log(event.target.textContent);
        }

    });

Event delegation is useful when:

  • There are many child elements.
  • Elements are dynamically created.
  • You want fewer event listeners.

74. What is preventDefault()?

Answer: preventDefault() prevents the browser’s default action for an event.

document
    .querySelector("form")
    .addEventListener("submit", event => {

        event.preventDefault();

        console.log("Default submission prevented");

    });

75. What is stopPropagation()?

Answer: stopPropagation() prevents an event from continuing to propagate through the DOM.

button.addEventListener("click", event => {
    event.stopPropagation();
});

Difference:

  • preventDefault() prevents the browser’s default action.
  • stopPropagation() prevents event propagation.

Scenario-Based JavaScript Interview Questions

76. How do you remove duplicate values from an array?

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

const unique = [...new Set(numbers)];

console.log(unique);

Output:

[1, 2, 3, 4]

77. How do you find the largest number in an array?

const numbers = [10, 50, 20, 90, 30];

const largest = Math.max(...numbers);

console.log(largest);

Output:

90

78. How do you reverse a string?

const text = "JavaScript";

const reversed = text
    .split("")
    .reverse()
    .join("");

console.log(reversed);

79. How do you check whether a string is a palindrome?

function isPalindrome(text) {

    const reversed = text
        .split("")
        .reverse()
        .join("");

    return text === reversed;
}

console.log(isPalindrome("madam"));

Output:

true

80. How do you count occurrences of elements in an array?

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

const count = fruits.reduce((result, fruit) => {

    result[fruit] = (result[fruit] || 0) + 1;

    return result;

}, {});

console.log(count);

Output:

{
    apple: 2,
    banana: 2,
    orange: 1
}

JavaScript Output-Based Interview Questions

81. What is the output?

console.log(a);

var a = 10;

Answer:

undefined

82. What is the output?

console.log(a);

let a = 10;

Answer:

ReferenceError

The variable is in the Temporal Dead Zone before initialization.


83. What is the output?

console.log("A");

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

console.log("C");

Answer:

A
C
B

The timer callback executes after the synchronous code.


84. What is the output?

console.log(1);

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

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

console.log(4);

Answer:

1
4
3
2

The Promise callback is a microtask, which is processed before the timer task.


85. What is the output?

const user = {
    name: "John"
};

const copy = user;

copy.name = "David";

console.log(user.name);

Answer:

David

Both variables reference the same object.


86. What is the output?

const user = {
    name: "John"
};

const copy = {
    ...user
};

copy.name = "David";

console.log(user.name);

Answer:

John

The spread operator creates a new outer object. However, nested objects are still shared because the copy is shallow.


JavaScript Interview Questions for QA and SDET Engineers

If you are preparing for a QA Automation, SDET, Selenium, or Playwright interview, you should pay special attention to the following JavaScript concepts:

  • Variables and data types
  • Functions
  • Scope
  • Hoisting
  • Closures
  • this
  • Arrow functions
  • Callbacks
  • Promises
  • async/await
  • Promise.all()
  • Event loop
  • Microtasks and tasks
  • Arrays and array methods
  • Objects
  • Destructuring
  • Spread and rest operators
  • Exception handling
  • Classes and inheritance
  • Modules
  • JSON manipulation
  • API handling

Top 20 JavaScript Interview Questions for Quick Revision

# Question Key Concept
1What is JavaScript?Fundamentals
2What is the difference between var, let, and const?Variables
3What is hoisting?Execution
4What is TDZ?let/const
5What is the difference between == and ===?Equality
6What is a closure?Scope
7What is this?Context
8Arrow function vs normal function?Functions
9What is a Promise?Asynchronous JavaScript
10What is async/await?Asynchronous JavaScript
11What is Promise.all()?Concurrency
12What is the event loop?Runtime
13Microtask vs task?Async execution
14map() vs filter()?Arrays
15find() vs filter()?Arrays
16Spread vs rest?ES6
17What is destructuring?ES6
18What is prototype inheritance?OOP
19What are JavaScript modules?Code organization
20What is event delegation?DOM

JavaScript Interview Preparation Strategy

Beginner Level

Start with:

  • Variables
  • Data types
  • Operators
  • Conditions
  • Loops
  • Functions
  • Arrays
  • Objects

Intermediate Level

Next, learn:

  • Scope
  • Hoisting
  • Closures
  • Destructuring
  • Spread/rest operators
  • Array methods
  • Exception handling
  • Promises
  • async/await
  • Classes
  • Modules

Advanced Level

Finally, focus on:

  • Event loop
  • Microtasks and tasks
  • Prototype chain
  • this
  • call(), apply(), and bind()
  • Currying
  • Memoization
  • Debouncing
  • Throttling
  • Event delegation
  • Memory management
  • Promise concurrency methods

Final Interview Tip

For JavaScript interviews, do not focus only on memorizing definitions. Interviewers frequently provide a short code snippet and ask:

“What will be the output and why?”

Therefore, practice code execution, scope, closures, this, Promises, async/await, event-loop behavior, arrays, objects, and asynchronous programming.

For QA Automation and SDET roles, combine JavaScript knowledge with practical scenarios involving API responses, JSON manipulation, Playwright, asynchronous test execution, Promise handling, and browser automation.

Conclusion

JavaScript is an essential skill for modern automation engineers, developers, and SDETs. A strong understanding of JavaScript fundamentals makes it much easier to learn technologies such as Playwright, Cypress, Node.js, React, and API automation.

Start with the fundamentals, practice small coding problems every day, and gradually move toward advanced concepts such as closures, Promises, event loops, prototypes, and asynchronous programming.

Keep practicing and focus on understanding why the code works, not just memorizing the answer.

TypeScript Interview Questions and Answers for Beginners

Are you preparing for a TypeScript interview as a beginner or fresher? This guide covers the most commonly asked TypeScript interview questions and answers, starting from basic concepts and gradually moving toward practical and coding-based questions.

TypeScript is widely used in modern web development, Node.js applications, Angular, React projects, and test automation frameworks such as Playwright with TypeScript.

This article contains 60 TypeScript interview questions and answers covering variables, data types, interfaces, classes, generics, functions, type guards, TypeScript configuration, and practical coding questions.

Table of Contents

1. What is TypeScript?

Answer: TypeScript is a strongly typed programming language developed by Microsoft. It is a superset of JavaScript, which means valid JavaScript code can generally be used in a TypeScript project.

TypeScript adds several features to JavaScript, including:

  • Static typing
  • Interfaces
  • Generics
  • Enums
  • Access modifiers
  • Better IDE support
  • Compile-time type checking

TypeScript code is transformed into JavaScript before it runs in a browser or Node.js environment.

2. What is the difference between JavaScript and TypeScript?

JavaScript TypeScript
Dynamically typed Supports static typing
Uses .js files Uses .ts files
Many type errors are discovered at runtime Many type errors can be detected during development
Does not require TypeScript compilation Usually transpiled to JavaScript
Less type information Provides rich type information

3. Why do we use TypeScript?

TypeScript makes JavaScript development safer and easier to maintain, particularly in large applications.

Major advantages include:

  • Early error detection
  • Better code completion
  • Improved refactoring
  • Static type checking
  • Better maintainability
  • Support for object-oriented programming
  • Improved developer productivity

4. Is TypeScript a programming language?

Answer: Yes. TypeScript is a programming language developed and maintained by Microsoft. It extends JavaScript by adding static typing and other development features.

5. What is the TypeScript compiler?

The TypeScript compiler converts TypeScript source code into JavaScript.

The compiler command is commonly called tsc.

tsc app.ts

For example:

let message: string = "Hello TypeScript";

console.log(message);

The TypeScript compiler generates JavaScript that can execute in a JavaScript environment.

6. How do you install TypeScript?

First install Node.js and npm. Then install TypeScript using:

npm install -g typescript

Verify the installation:

tsc --version

7. What is a .ts file?

A .ts file is a TypeScript source file.

Examples:

app.ts
login.ts
user.ts
employee.ts

TypeScript code is normally written in .ts files and then compiled or transpiled into JavaScript.

8. What are the basic data types in TypeScript?

Some commonly used TypeScript types are:

string
number
boolean
array
tuple
enum
any
unknown
void
null
undefined
never
object

Example:

let name: string = "Deepesh";
let age: number = 35;
let isTrainer: boolean = true;

9. What is type annotation?

Type annotation means explicitly specifying the type of a variable.

let username: string = "admin";
let age: number = 30;
let active: boolean = true;

Here, string, number, and boolean are type annotations.

10. What is type inference?

Type inference means TypeScript automatically determines the type of a variable based on its assigned value.

let name = "Deepesh";
let age = 30;

TypeScript infers:

name: string
age: number

11. What is the any type?

The any type disables most TypeScript type checking for a value.

let data: any = "Hello";

data = 100;
data = true;
data = { name: "John" };

Although any can be useful when migrating JavaScript code or dealing with genuinely untyped APIs, excessive use of it removes many of the benefits of TypeScript.

12. What is the unknown type?

The unknown type is used when the type of a value is not known.

let value: unknown = "Hello";

if (typeof value === "string") {
    console.log(value.toUpperCase());
}

Unlike any, TypeScript requires you to perform an appropriate type check before using an unknown value in type-specific operations.

13. What is an array in TypeScript?

An array stores multiple values.

let numbers: number[] = [10, 20, 30];

let names: string[] = ["John", "David", "Alex"];

Another syntax is:

let numbers: Array<number> = [10, 20, 30];

14. What is a tuple?

A tuple defines a fixed structure for an array, including the expected type and position of its elements.

let employee: [number, string] = [101, "John"];

In this example:

  • The first element must be a number.
  • The second element must be a string.

15. What is an interface?

An interface defines the structure or contract of an object.

interface Employee {
    id: number;
    name: string;
    salary: number;
}

const employee: Employee = {
    id: 101,
    name: "John",
    salary: 50000
};

Interfaces are commonly used to define the expected structure of objects and contracts implemented by classes.

16. What is an optional property?

A property followed by ? is optional.

interface Employee {
    id: number;
    name: string;
    email?: string;
}

Therefore, the following object is valid:

const employee: Employee = {
    id: 101,
    name: "John"
};

17. What is a type alias?

A type alias allows you to create a custom name for a type.

type Employee = {
    id: number;
    name: string;
};

const emp: Employee = {
    id: 101,
    name: "John"
};

Type aliases can also represent unions and other type expressions.

type ID = string | number;

let userId: ID = 101;
userId = "EMP101";

18. What is the difference between interface and type?

Both interfaces and type aliases can describe object structures.

interface User {
    name: string;
}

Equivalent object type:

type User = {
    name: string;
};

Interfaces are especially useful for object/class contracts and can be extended. Type aliases are more flexible for unions, intersections, tuples, and other type expressions.

19. What is a union type?

A union type allows a variable to have more than one possible type.

let id: string | number;

id = 101;
id = "EMP101";

The | symbol represents a union.

20. What is an intersection type?

An intersection type combines multiple types into a single type.

type Person = {
    name: string;
};

type Employee = {
    salary: number;
};

type EmployeeDetails = Person & Employee;

const emp: EmployeeDetails = {
    name: "John",
    salary: 50000
};

The & operator represents an intersection type.

21. What is an enum?

An enum allows you to define a collection of named constants.

enum Status {
    Pending,
    Approved,
    Rejected
}

let currentStatus: Status = Status.Approved;

Enums can be useful when working with a predefined set of values.

22. How do you define a function in TypeScript?

function add(a: number, b: number): number {
    return a + b;
}

console.log(add(10, 20));

The parameter types are defined using : number, and the return type is also specified as number.

23. What is an optional parameter?

An optional parameter is defined using ?.

function greet(name: string, age?: number) {
    console.log(name);
}

greet("John");
greet("John", 30);

The age parameter is optional.

24. What are default parameters?

A default parameter receives a default value when no value is provided.

function greet(name: string = "Guest") {
    console.log(`Hello ${name}`);
}

greet();

Output:

Hello Guest

25. What is a class in TypeScript?

A class is a blueprint for creating objects.

class Employee {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    display() {
        console.log(this.name);
    }
}

const emp = new Employee("John");

emp.display();

TypeScript classes support object-oriented programming concepts such as encapsulation, inheritance, abstraction, and polymorphism.

26. What are access modifiers in TypeScript?

TypeScript supports the following common access modifiers:

  • public – accessible from anywhere
  • private – accessible only inside the declaring class
  • protected – accessible inside the class and subclasses
class Employee {
    public name: string;
    private salary: number;
    protected department: string;

    constructor(
        name: string,
        salary: number,
        department: string
    ) {
        this.name = name;
        this.salary = salary;
        this.department = department;
    }
}

27. What is inheritance?

Inheritance allows one class to reuse members of another class.

class Animal {
    eat() {
        console.log("Eating");
    }
}

class Dog extends Animal {
    bark() {
        console.log("Barking");
    }
}

const dog = new Dog();

dog.eat();
dog.bark();

Here, Dog inherits from Animal.

28. What are generics in TypeScript?

Generics allow you to create reusable code that works with different types while preserving type safety.

function identity<T>(value: T): T {
    return value;
}

let numberValue = identity<number>(100);
let stringValue = identity<string>("Hello");

Here, T acts as a type parameter.

29. What is type assertion?

Type assertion tells TypeScript that you know more about the type of a value than the compiler currently does.

let value: unknown = "Hello";

let message = value as string;

console.log(message.toUpperCase());

The as syntax is commonly used for type assertions.

30. What is void?

The void type is commonly used for functions that do not return a meaningful value.

function printMessage(): void {
    console.log("Hello");
}

31. What is null and undefined?

undefined generally means a value has not been assigned.

let name: string | undefined;

console.log(name);

null represents an intentional absence of a value.

let user: string | null = null;

32. What is never in TypeScript?

never represents a value that never occurs. It is commonly used for functions that never successfully complete.

function throwError(message: string): never {
    throw new Error(message);
}

33. What is strict mode?

Strict mode enables a collection of stronger type-checking rules.

{
    "compilerOptions": {
        "strict": true
    }
}

Strict checking helps identify potential problems during development.

34. What is tsconfig.json?

tsconfig.json is the configuration file for a TypeScript project.

Example:

{
    "compilerOptions": {
        "target": "ES2022",
        "module": "commonjs",
        "strict": true,
        "outDir": "./dist"
    },
    "include": [
        "src/**/*.ts"
    ]
}

35. What is the target option?

The target option specifies the JavaScript version that TypeScript should generate.

{
    "compilerOptions": {
        "target": "ES2022"
    }
}

36. What is the module option?

The module option controls the module system used by the generated JavaScript.

{
    "compilerOptions": {
        "module": "commonjs"
    }
}

Modern projects may use module settings such as ESNext depending on the runtime and build system.

37. What is type narrowing?

Type narrowing means reducing a broad type to a more specific type based on a condition.

function printValue(value: string | number) {

    if (typeof value === "string") {
        console.log(value.toUpperCase());
    } else {
        console.log(value.toFixed(2));
    }
}

38. What is typeof used for?

The typeof operator can be used to check the runtime type of a value and can also help TypeScript narrow a union type.

function display(value: string | number) {

    if (typeof value === "string") {
        console.log("String:", value);
    } else {
        console.log("Number:", value);
    }
}

39. What is a type guard?

A type guard is a condition or function that helps TypeScript determine the specific type of a value.

function isString(value: unknown): value is string {
    return typeof value === "string";
}

const data: unknown = "Hello";

if (isString(data)) {
    console.log(data.toUpperCase());
}

40. What is instanceof?

The instanceof operator checks whether an object is an instance of a particular class or constructor.

class Employee {
}

const emp = new Employee();

console.log(emp instanceof Employee);

Output:

true

41. What is optional chaining?

Optional chaining ?. allows you to safely access properties that may not exist.

interface User {
    name: string;
    address?: {
        city: string;
    };
}

const user: User = {
    name: "John"
};

console.log(user.address?.city);

42. What is the nullish coalescing operator?

The ?? operator provides a fallback value when the left-hand side is null or undefined.

let username: string | undefined;

let result = username ?? "Guest";

console.log(result);

Output:

Guest

43. What is readonly?

The readonly modifier prevents a property from being assigned a new value after initialization.

interface Employee {
    readonly id: number;
    name: string;
}

const employee: Employee = {
    id: 101,
    name: "John"
};

employee.name = "David";

// Error:
// employee.id = 102;

44. What is the difference between const and readonly?

const applies to a variable binding, while readonly applies to a property or type member.

const employee = {
    name: "John"
};

employee.name = "David";

The object reference cannot be reassigned, but its property can still be changed.

With readonly:

interface Employee {
    readonly id: number;
}

The id property cannot be reassigned after initialization.

45. Can an interface extend another interface?

Yes. An interface can extend another interface.

interface Person {
    name: string;
}

interface Employee extends Person {
    employeeId: number;
}

const emp: Employee = {
    name: "John",
    employeeId: 101
};

46. Can a class implement an interface?

Yes. A class can implement one or more interfaces.

interface Employee {
    name: string;
    display(): void;
}

class Manager implements Employee {

    name: string;

    constructor(name: string) {
        this.name = name;
    }

    display(): void {
        console.log(this.name);
    }
}

47. What is the difference between extends and implements?

extends is generally used for inheritance.

class Dog extends Animal {
}

implements is used when a class agrees to follow an interface contract.

class Employee implements Person {
}

48. Can an interface have methods?

Yes. An interface can define method signatures.

interface Employee {
    name: string;
    display(): void;
}

A class implementing the interface must provide the required method.

49. What is function overloading?

Function overloading allows you to define multiple function signatures for different valid calling patterns.

function add(a: number, b: number): number;
function add(a: string, b: string): string;

function add(a: number | string, b: number | string) {
    return (a as any) + (b as any);
}

console.log(add(10, 20));
console.log(add("Hello ", "World"));

50. What is the purpose of generics?

Generics allow developers to create reusable, type-safe functions, classes, and interfaces.

function getValue<T>(value: T): T {
    return value;
}

const numberValue = getValue(100);
const stringValue = getValue("Hello");
const booleanValue = getValue(true);

TypeScript Coding Interview Questions

51. Write a function to calculate the sum of two numbers.

function sum(a: number, b: number): number {
    return a + b;
}

console.log(sum(10, 20));

52. Create an interface for a Student.

interface Student {
    id: number;
    name: string;
    age: number;
}

const student: Student = {
    id: 1,
    name: "John",
    age: 22
};

53. Create an interface with an optional property.

interface User {
    id: number;
    name: string;
    email?: string;
}

54. Create a function that accepts string or number.

function display(value: string | number): void {
    console.log(value);
}

display("Hello");
display(100);

55. Create a generic function.

function getData<T>(data: T): T {
    return data;
}

console.log(getData<number>(100));
console.log(getData<string>("TypeScript"));

Practical TypeScript Interview Questions

56. What will be the output?

let value: string | number = "100";

if (typeof value === "string") {
    console.log("String");
} else {
    console.log("Number");
}

Answer:

String

Because the value is initially assigned a string.

57. Is this code valid?

let age: number = 25;

age = "25";

Answer: No.

TypeScript reports a type error because age was declared as a number.

58. Is this valid TypeScript?

let data: any = 100;

data = "Hello";
data = true;

Answer: Yes.

The any type allows the variable to contain values of different types. However, it should be used carefully.

59. What is the output?

let username: string | undefined;

console.log(username ?? "Guest");

Answer:

Guest

Because username is undefined.

60. What is the main advantage of generics?

Generics allow you to write reusable code while preserving type information.

function getData<T>(data: T): T {
    return data;
}

const numberData = getData(100);
const stringData = getData("Hello");

TypeScript can infer the appropriate type for T.

Important TypeScript Interview Topics for Beginners

If you have limited preparation time, focus on the following topics:

  1. What is TypeScript?
  2. TypeScript vs JavaScript
  3. Advantages of TypeScript
  4. Type annotations
  5. Type inference
  6. any vs unknown
  7. Union types
  8. Intersection types
  9. Interfaces
  10. Type aliases
  11. Interface vs type
  12. Arrays
  13. Tuples
  14. Enums
  15. Functions
  16. Optional parameters
  17. Classes
  18. Access modifiers
  19. Inheritance
  20. extends vs implements
  21. Generics
  22. Type assertions
  23. Type guards
  24. null and undefined
  25. never
  26. void
  27. readonly
  28. Optional chaining
  29. Nullish coalescing
  30. tsconfig.json

TypeScript Interview Preparation Tips

For a beginner TypeScript interview, don’t just memorize definitions. Try to understand each concept with a small coding example.

  • Understand JavaScript fundamentals first.
  • Practice TypeScript data types.
  • Write interfaces for real-world objects.
  • Practice classes and inheritance.
  • Understand union and intersection types.
  • Practice generics with simple examples.
  • Learn type narrowing and type guards.
  • Understand any, unknown, never, and void.
  • Practice TypeScript coding questions.
  • Learn how tsconfig.json works.

TypeScript for Playwright Automation

TypeScript is particularly useful for test automation because it provides type safety, better autocomplete, and improved maintainability.

For example, a Playwright test can be written as:

import { test, expect } from '@playwright/test';

test('Login test', async ({ page }) => {

    await page.goto('https://example.com');

    await expect(page).toHaveTitle(/Example/);

});

Understanding TypeScript fundamentals is therefore highly recommended if you are preparing for a Playwright with TypeScript or SDET interview.

Frequently Asked Questions

Is TypeScript difficult for beginners?

No. If you already know JavaScript fundamentals, TypeScript can be learned progressively by adding types and understanding interfaces, classes, generics, and other features.

Do I need to learn JavaScript before TypeScript?

Yes, it is highly recommended. TypeScript builds on JavaScript, so understanding variables, functions, arrays, objects, classes, promises, and asynchronous programming will make TypeScript much easier to learn.

Is TypeScript used in automation testing?

Yes. TypeScript is widely used with modern automation frameworks, including Playwright. It provides type checking, IDE support, and improved maintainability for automation frameworks.

What should I learn after TypeScript basics?

After learning the fundamentals, you should study advanced TypeScript concepts such as generics, utility types, mapped types, conditional types, decorators, modules, namespaces, advanced type narrowing, and TypeScript configuration.

Conclusion

TypeScript is an important skill for modern web development and test automation. Beginners should first understand the fundamentals such as data types, type annotations, type inference, interfaces, type aliases, functions, classes, union types, and generics.

Once these concepts are clear, you can move toward advanced TypeScript concepts and frameworks such as Playwright, Angular, React, Node.js, and automation framework development.

Practicing the questions and coding examples in this article will help you build a strong foundation for TypeScript interviews.

Next Recommended Topic: TypeScript Interview Questions and Answers for Intermediate and Advanced Developers.

Scenario-Based JavaScript Array Programs

Below is a collection of real-world, scenario-based JavaScript array programs designed for QA/SDET training, coding practice, and interviews. They progress from beginner to advanced.


1. Find the Highest Product Price

Scenario

An e-commerce application stores product prices. Find the most expensive product.

const prices = [1200, 4500, 2300, 8900, 1500];

let maxPrice = prices[0];

for (let price of prices) {
    if (price > maxPrice) {
        maxPrice = price;
    }
}

console.log("Highest Price:", maxPrice);

Expected Output:

Highest Price: 8900

2. Find the Lowest Product Price

const prices = [1200, 4500, 2300, 8900, 1500];

let minPrice = prices[0];

for (let price of prices) {
    if (price < minPrice) {
        minPrice = price;
    }
}

console.log("Lowest Price:", minPrice);

3. Calculate Total Shopping Cart Amount

Scenario

A shopping cart contains multiple product prices. Calculate the total.

const cart = [499, 1299, 799, 2499];

let total = 0;

for (let price of cart) {
    total += price;
}

console.log("Cart Total:", total);

Output:

Cart Total: 5096

4. Find Products Above ₹1000

const prices = [500, 1200, 2500, 700, 1800, 450];

const result = [];

for (let price of prices) {
    if (price > 1000) {
        result.push(price);
    }
}

console.log(result);

Output:

[1200, 2500, 1800]

5. Remove Duplicate Product IDs

Scenario

During automation testing, duplicate product IDs are received from an API.

const productIds = [101, 102, 103, 101, 104, 102, 105];

const uniqueIds = [];

for (let id of productIds) {
    if (!uniqueIds.includes(id)) {
        uniqueIds.push(id);
    }
}

console.log(uniqueIds);

Output:

[101, 102, 103, 104, 105]

6. Find Duplicate Values

const ids = [101, 102, 103, 101, 104, 102, 105];

const duplicates = [];

for (let i = 0; i < ids.length; i++) {
    for (let j = i + 1; j < ids.length; j++) {

        if (ids[i] === ids[j] && !duplicates.includes(ids[i])) {
            duplicates.push(ids[i]);
        }
    }
}

console.log("Duplicates:", duplicates);

Output:

Duplicates: [101, 102]

7. Find Second Highest Salary

Scenario

An HR application stores employee salaries. Find the second-highest salary without sorting.

const salaries = [45000, 75000, 55000, 90000, 65000];

let highest = -Infinity;
let secondHighest = -Infinity;

for (let salary of salaries) {

    if (salary > highest) {
        secondHighest = highest;
        highest = salary;
    } 
    else if (salary > secondHighest && salary !== highest) {
        secondHighest = salary;
    }
}

console.log("Highest:", highest);
console.log("Second Highest:", secondHighest);

Output:

Highest: 90000
Second Highest: 75000

8. Count Passed and Failed Students

Scenario

A training institute stores student marks. Determine how many students passed.

const marks = [85, 45, 72, 30, 90, 55, 28];

let passed = 0;
let failed = 0;

for (let mark of marks) {

    if (mark >= 40) {
        passed++;
    } else {
        failed++;
    }
}

console.log("Passed:", passed);
console.log("Failed:", failed);

9. Calculate Average Marks

const marks = [80, 75, 90, 65, 85];

let total = 0;

for (let mark of marks) {
    total += mark;
}

const average = total / marks.length;

console.log("Average:", average);

10. Find Students Who Scored Above Average

const marks = [80, 45, 90, 65, 85];

let total = 0;

for (let mark of marks) {
    total += mark;
}

const average = total / marks.length;

const aboveAverage = [];

for (let mark of marks) {
    if (mark > average) {
        aboveAverage.push(mark);
    }
}

console.log("Average:", average);
console.log("Above Average:", aboveAverage);

11. Find Missing Test Case IDs

Scenario

A QA automation suite should execute test cases from 1 to 10, but some test cases are missing.

const executedTests = [1, 2, 3, 5, 6, 8, 10];

const missingTests = [];

for (let i = 1; i <= 10; i++) {

    if (!executedTests.includes(i)) {
        missingTests.push(i);
    }
}

console.log("Missing Tests:", missingTests);

Output:

Missing Tests: [4, 7, 9]

12. Count Even and Odd Numbers

Scenario

An application receives transaction IDs and needs to classify them.

const transactionIds = [101, 202, 303, 404, 505, 606];

let even = 0;
let odd = 0;

for (let id of transactionIds) {

    if (id % 2 === 0) {
        even++;
    } else {
        odd++;
    }
}

console.log("Even:", even);
console.log("Odd:", odd);

13. Reverse an Array Without reverse()

const users = ["John", "David", "Mike", "Alex"];

const reversed = [];

for (let i = users.length - 1; i >= 0; i--) {
    reversed.push(users[i]);
}

console.log(reversed);

Output:

["Alex", "Mike", "David", "John"]

14. Find a Specific User

const users = ["John", "David", "Mike", "Alex"];

const searchUser = "Mike";

if (users.includes(searchUser)) {
    console.log("User Found");
} else {
    console.log("User Not Found");
}

15. Count Occurrence of a Value

Scenario

Find how many times a particular product was purchased.

const products = [
    "Laptop",
    "Mobile",
    "Laptop",
    "Tablet",
    "Laptop",
    "Mobile"
];

const searchProduct = "Laptop";

let count = 0;

for (let product of products) {
    if (product === searchProduct) {
        count++;
    }
}

console.log("Laptop purchased:", count, "times");

16. Find Common Elements Between Two Arrays

Scenario

Find users who are present in both applications.

const app1Users = ["John", "David", "Mike", "Alex"];
const app2Users = ["Mike", "Alex", "Robert", "Sam"];

const commonUsers = [];

for (let user of app1Users) {

    if (app2Users.includes(user)) {
        commonUsers.push(user);
    }
}

console.log(commonUsers);

Output:

["Mike", "Alex"]

17. Find Unique Elements From Two Arrays

const teamA = ["John", "David", "Mike"];
const teamB = ["Mike", "Alex", "David"];

const result = [];

for (let user of [...teamA, ...teamB]) {

    if (!result.includes(user)) {
        result.push(user);
    }
}

console.log(result);

18. Find Failed Test Cases

Scenario

A Playwright test execution produces test statuses.

const statuses = [
    "passed",
    "failed",
    "passed",
    "skipped",
    "failed",
    "passed"
];

const failedTests = [];

for (let status of statuses) {

    if (status === "failed") {
        failedTests.push(status);
    }
}

console.log("Failed Tests:", failedTests.length);

19. Separate Positive and Negative Numbers

const numbers = [10, -5, 20, -8, 15, -2];

const positive = [];
const negative = [];

for (let number of numbers) {

    if (number >= 0) {
        positive.push(number);
    } else {
        negative.push(number);
    }
}

console.log("Positive:", positive);
console.log("Negative:", negative);

20. Move All Zeros to the End

Scenario

An API returns an array containing zero values. Move all zero values to the end.

const numbers = [0, 5, 0, 3, 8, 0, 2];

const result = [];

let zeroCount = 0;

for (let number of numbers) {

    if (number === 0) {
        zeroCount++;
    } else {
        result.push(number);
    }
}

for (let i = 0; i < zeroCount; i++) {
    result.push(0);
}

console.log(result);

Output:

[5, 3, 8, 2, 0, 0, 0]

21. Find First Non-Repeated Element

Scenario

Find the first unique transaction ID.

const ids = [101, 102, 101, 103, 102, 104];

for (let id of ids) {

    let count = 0;

    for (let value of ids) {

        if (id === value) {
            count++;
        }
    }

    if (count === 1) {
        console.log("First non-repeated ID:", id);
        break;
    }
}

Output:

First non-repeated ID: 103

22. Find Maximum Consecutive Number

const numbers = [10, 20, 30, 25, 50, 60];

let maxDifference = 0;
let firstNumber;
let secondNumber;

for (let i = 0; i < numbers.length - 1; i++) {

    const difference = numbers[i + 1] - numbers[i];

    if (difference > maxDifference) {
        maxDifference = difference;
        firstNumber = numbers[i];
        secondNumber = numbers[i + 1];
    }
}

console.log(firstNumber, secondNumber);

23. Pagination Scenario

Scenario

An API returns 50 records. Display records for page 3 where each page contains 10 records.

const users = Array.from({ length: 50 }, (_, i) => `User-${i + 1}`);

const page = 3;
const pageSize = 10;

const startIndex = (page - 1) * pageSize;

const pageData = users.slice(
    startIndex,
    startIndex + pageSize
);

console.log(pageData);

Output:

[
 "User-21",
 "User-22",
 ...
 "User-30"
]

24. Search Products by Keyword

const products = [
    "iPhone 15",
    "Samsung Galaxy",
    "MacBook Pro",
    "iPad Air",
    "Samsung TV"
];

const keyword = "Samsung";

const result = products.filter(product =>
    product.toLowerCase().includes(keyword.toLowerCase())
);

console.log(result);

25. Apply Discount to Product Prices

Scenario

Apply a 10% discount to all products.

const prices = [1000, 2500, 5000, 7500];

const discountedPrices = prices.map(price => {
    return price - (price * 10 / 100);
});

console.log(discountedPrices);

Output:

[900, 2250, 4500, 6750]

26. Find Products Within a Price Range

const prices = [500, 1200, 2500, 3500, 4500, 6000];

const min = 1000;
const max = 4000;

const result = prices.filter(price =>
    price >= min && price <= max
);

console.log(result);

Output:

[1200, 2500, 3500]

27. Find the Most Frequent Element

Scenario

Find the product that appears most frequently in orders.

const products = [
    "Laptop",
    "Mobile",
    "Laptop",
    "Tablet",
    "Mobile",
    "Laptop"
];

let maxCount = 0;
let mostFrequent;

for (let product of products) {

    let count = 0;

    for (let value of products) {
        if (product === value) {
            count++;
        }
    }

    if (count > maxCount) {
        maxCount = count;
        mostFrequent = product;
    }
}

console.log("Most Frequent:", mostFrequent);
console.log("Count:", maxCount);

28. Compare Expected and Actual Results

Scenario

This is especially useful for API/UI automation validation.

const expected = ["Login", "Dashboard", "Logout"];
const actual = ["Login", "Dashboard", "Logout"];

let isMatching = true;

if (expected.length !== actual.length) {
    isMatching = false;
} else {

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

        if (expected[i] !== actual[i]) {
            isMatching = false;
            break;
        }
    }
}

console.log("Result:", isMatching);

29. Find Missing Values Between Two Arrays

const expected = [101, 102, 103, 104, 105];
const actual = [101, 103, 105];

const missing = [];

for (let id of expected) {

    if (!actual.includes(id)) {
        missing.push(id);
    }
}

console.log("Missing:", missing);

Output:

Missing: [102, 104]

30. Flatten Nested Array

Scenario

An API returns nested categories.

const categories = [
    ["Electronics", "Mobile"],
    ["Furniture", "Chair"],
    ["Books", "Novel"]
];

const result = categories.flat();

console.log(result);

Output:

[
    "Electronics",
    "Mobile",
    "Furniture",
    "Chair",
    "Books",
    "Novel"
]

31. QA/SDET Scenario: Validate API Response IDs

const apiResponse = [
    { id: 101, name: "John" },
    { id: 102, name: "David" },
    { id: 103, name: "Mike" }
];

const ids = apiResponse.map(user => user.id);

const expectedIds = [101, 102, 103];

console.log(
    JSON.stringify(ids) === JSON.stringify(expectedIds)
        ? "Test Passed"
        : "Test Failed"
);

32. QA/SDET Scenario: Find Failed Test Names

const testResults = [
    { name: "Login Test", status: "passed" },
    { name: "Search Test", status: "failed" },
    { name: "Checkout Test", status: "passed" },
    { name: "Payment Test", status: "failed" }
];

const failedTests = testResults
    .filter(test => test.status === "failed")
    .map(test => test.name);

console.log(failedTests);

Output:

["Search Test", "Payment Test"]

33. QA/SDET Scenario: Calculate Test Execution Summary

const results = [
    "passed",
    "passed",
    "failed",
    "skipped",
    "passed",
    "failed",
    "passed"
];

const summary = {
    passed: 0,
    failed: 0,
    skipped: 0
};

for (let result of results) {
    summary[result]++;
}

console.log(summary);

Output:

{
    passed: 4,
    failed: 2,
    skipped: 1
}

34. Find Duplicate Test Case IDs

const testCases = [
    "TC001",
    "TC002",
    "TC003",
    "TC001",
    "TC004",
    "TC002"
];

const duplicates = [];

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

    for (let j = i + 1; j < testCases.length; j++) {

        if (
            testCases[i] === testCases[j] &&
            !duplicates.includes(testCases[i])
        ) {
            duplicates.push(testCases[i]);
        }
    }
}

console.log("Duplicate Test Cases:", duplicates);

Output:

Duplicate Test Cases: ["TC001", "TC002"]

35. Advanced Interview Scenario: Find Two Numbers Whose Sum Equals Target

Scenario

Find two product prices whose total is ₹3000.

const prices = [500, 1200, 1800, 2500, 1500];

const target = 3000;

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

    for (let j = i + 1; j < prices.length; j++) {

        if (prices[i] + prices[j] === target) {
            console.log(
                prices[i],
                "+",
                prices[j],
                "=",
                target
            );
        }
    }
}

Output:

1200 + 1800 = 3000
1500 + 1500 = 3000

Interview Practice Set

For your JavaScript/Playwright/SDET training sessions, these are particularly good interview exercises:

Beginner

  1. Find maximum number.
  2. Find minimum number.
  3. Calculate array sum.
  4. Calculate average.
  5. Count even and odd numbers.
  6. Reverse an array.
  7. Search an element.
  8. Find positive and negative numbers.
  9. Remove duplicates.
  10. Count occurrences.

Intermediate

  1. Find second maximum without sorting.
  2. Find duplicate elements.
  3. Find missing numbers.
  4. Find common elements between arrays.
  5. Find unique elements.
  6. Move zeros to the end.
  7. Find first non-repeated element.
  8. Find most frequent element.
  9. Find elements above average.
  10. Find values within a range.

Advanced

  1. Two-sum problem.
  2. Compare two arrays.
  3. Find array intersection.
  4. Find array difference.
  5. Flatten nested arrays.
  6. Group test results.
  7. Validate API response arrays.
  8. Find duplicate test case IDs.
  9. Implement pagination using arrays.
  10. Process and summarize test execution results.

How to Perform File Download Using Playwright (TypeScript)

File download is one of the most common scenarios in UI automation. Playwright provides built-in support for handling downloads without relying on browser-specific configurations.

This guide explains everything from basic file downloads to advanced scenarios with practical examples.


Prerequisites

Install Playwright:

npm init playwright@latest

Import Playwright:

import { test, expect } from '@playwright/test';

How Playwright Handles Downloads

Whenever a download starts, Playwright creates a Download object.

You can:

  • Wait for the download event
  • Get download information
  • Save the file
  • Verify file name
  • Verify file content
  • Delete downloaded files

The download object provides methods like:

MethodDescription
download.path()Returns downloaded file path
download.saveAs()Save file to custom location
download.suggestedFilename()Returns original filename
download.failure()Returns download failure reason
download.delete()Deletes downloaded file
download.createReadStream()Reads downloaded file

Example Website

Suppose clicking this button downloads a PDF.

<button>Download Report</button>

Example 1: Basic File Download

import { test, expect } from '@playwright/test';

test('Download File', async ({ page }) => {

    await page.goto('https://example.com');

    const downloadPromise = page.waitForEvent('download');

    await page.getByText('Download Report').click();

    const download = await downloadPromise;

    console.log(download.suggestedFilename());

});

What happens?

Click Button
      │
      ▼
Browser Starts Download
      │
      ▼
Playwright Creates Download Object
      │
      ▼
You Can Save or Verify File

Example 2: Save Download to Custom Folder

import path from 'path';

test('Save Download', async ({ page }) => {

    await page.goto('https://example.com');

    const downloadPromise = page.waitForEvent('download');

    await page.locator('#download').click();

    const download = await downloadPromise;

    await download.saveAs(
        path.join('downloads', download.suggestedFilename())
    );

});

Downloaded folder:

Project

│
├── downloads
│      report.pdf
│
├── tests

Example 3: Get File Name

const fileName = download.suggestedFilename();

console.log(fileName);

Output

report.pdf

Example 4: Get Download Path

const path = await download.path();

console.log(path);

Example Output

C:\Users\Deepesh\AppData\Local\Temp\playwright-downloads\12345.pdf

Example 5: Verify Downloaded File Exists

import fs from 'fs';

const filePath = await download.path();

expect(fs.existsSync(filePath!)).toBeTruthy();

Example 6: Verify File Extension

expect(download.suggestedFilename()).toContain('.pdf');

or

expect(download.suggestedFilename()).toMatch(/\.pdf$/);

Example 7: Verify File Size

import fs from 'fs';

const filePath = await download.path();

const stats = fs.statSync(filePath!);

console.log(stats.size);

Assertion

expect(stats.size).toBeGreaterThan(1000);

Example 8: Verify Downloaded CSV Content

import fs from 'fs';

const filePath = await download.path();

const content = fs.readFileSync(filePath!, 'utf-8');

expect(content).toContain('Employee Name');

Example 9: Verify Downloaded Text File

const filePath = await download.path();

const text = fs.readFileSync(filePath!, 'utf-8');

expect(text).toContain('Welcome');

Example 10: Download Multiple Files

const download1 = page.waitForEvent('download');
await page.click('#download1');
const file1 = await download1;

const download2 = page.waitForEvent('download');
await page.click('#download2');
const file2 = await download2;

console.log(file1.suggestedFilename());
console.log(file2.suggestedFilename());

Example 11: Using Promise.all()

This is the recommended approach because it avoids missing the download event.

const [download] = await Promise.all([
    page.waitForEvent('download'),
    page.locator('#download').click()
]);

await download.saveAs(
    `downloads/${download.suggestedFilename()}`
);

Example 12: Verify Download Failure

const failure = await download.failure();

expect(failure).toBeNull();

If download fails

Network Error

or

Cancelled

Example 13: Delete Downloaded File

await download.delete();

Example 14: Read Download Stream

const stream = await download.createReadStream();

stream?.on('data', chunk => {
    console.log(chunk.toString());
});

Example 15: Download After Login

test('Download Invoice', async ({ page }) => {

    await page.goto('https://example.com/login');

    await page.fill('#username', 'admin');
    await page.fill('#password', 'admin123');

    await page.click('#login');

    const [download] = await Promise.all([
        page.waitForEvent('download'),
        page.click('text=Download Invoice')
    ]);

    await download.saveAs(
        `downloads/${download.suggestedFilename()}`
    );

});

Download PDF Example

const [download] = await Promise.all([
    page.waitForEvent('download'),
    page.getByText('Download PDF').click()
]);

expect(download.suggestedFilename()).toContain('.pdf');

Download Excel Example

const [download] = await Promise.all([
    page.waitForEvent('download'),
    page.getByRole('button', { name: 'Export Excel' }).click()
]);

expect(download.suggestedFilename()).toContain('.xlsx');

Download ZIP Example

const [download] = await Promise.all([
    page.waitForEvent('download'),
    page.click('#zip')
]);

await download.saveAs(
    `downloads/${download.suggestedFilename()}`
);

Browser Download Behavior

BrowserSupported
Chromium✅
Firefox✅
WebKit✅

No browser-specific download configuration is required in Playwright.


Best Practices

  • Always use Promise.all() to wait for the download event and trigger the download simultaneously.
  • Save downloads to a dedicated folder (for example, downloads/) to keep test artifacts organized.
  • Verify both the filename and file extension.
  • Validate the file contents whenever possible instead of checking only that a file exists.
  • Clean up downloaded files after the test to avoid consuming unnecessary disk space.
  • Use download.failure() to detect download issues early.
  • Avoid hard-coded delays such as waitForTimeout() when handling downloads.
  • Use download.suggestedFilename() instead of assuming a fixed filename.

Common Interview Questions

1. How do you handle file downloads in Playwright?

Use page.waitForEvent('download') together with the action that triggers the download, preferably inside Promise.all(). Then use the Download object to save or verify the file.


2. Why should you use Promise.all() for downloads?

It ensures Playwright starts listening for the download event before the click occurs, preventing race conditions where the download starts before the listener is attached.


3. How do you save a downloaded file to a custom location?

Use:

await download.saveAs('downloads/report.pdf');

4. How do you verify a file was downloaded successfully?

You can:

  • Check that await download.failure() returns null.
  • Verify the file exists using fs.existsSync().
  • Validate the filename with download.suggestedFilename().
  • Check the file size or inspect its contents.

5. Can Playwright verify the contents of a downloaded file?

Yes. After obtaining the file path with download.path(), use Node.js modules like fs (or libraries such as xlsx for Excel or pdf-parse for PDFs) to read and validate the file contents.


Summary

Playwright’s download API is simple yet powerful. By using the Download object and the Promise.all() pattern, you can reliably automate downloading PDFs, Excel files, ZIP archives, CSVs, and other file types while verifying filenames, sizes, and contents. This approach works consistently across Chromium, Firefox, and WebKit, making it suitable for both functional and end-to-end automation tests.

Integrating Allure Report with Playwright (Step-by-Step Guide)

Allure Report is one of the most popular reporting tools for Playwright automation projects. It provides interactive HTML reports with test execution history, screenshots, attachments, environment information, categories, and detailed execution steps.

This guide explains how to integrate Allure Report into a Playwright project from scratch, based on your project configuration.


What is Allure Report?

Allure Report is an advanced test reporting framework that provides:

  • Beautiful HTML reports
  • Test execution history
  • Test retries
  • Screenshots
  • Videos
  • Trace attachments
  • Execution duration
  • Environment information
  • Categories of failures
  • Test hierarchy
  • Dashboard and statistics

Example Report Structure

Dashboard
│
├── Overview
├── Behaviors
├── Suites
├── Graphs
├── Timeline
├── Categories
└── Packages

Prerequisites

Before integrating Allure, make sure you have:

  • Node.js installed
  • Playwright project already created
  • npm installed

Verify versions

node -v
npm -v
npx playwright --version

Step 1: Install Required Packages

Install the Allure reporter and command-line utility.

npm install --save-dev allure-playwright allure-commandline

These packages serve different purposes:

PackagePurpose
allure-playwrightGenerates Allure result files during test execution
allure-commandlineConverts result files into an interactive HTML report

This is the first step required to enable Allure reporting.


Step 2: Configure Playwright Reporter

Open:

playwright.config.ts

Update the reporter section:

reporter: [
  ['list'],
  ['html', { open: 'never', outputFolder: 'playwright-report' }],
  ['allure-playwright', {
      outputFolder: 'allure-results',
      suiteTitle: false
  }]
]

Explanation:

List Reporter

['list']

Displays test execution in the terminal.

Example

✓ Login Test
✓ Logout Test
✓ Search Product

HTML Reporter

['html', {
    open: 'never',
    outputFolder: 'playwright-report'
}]

Generates Playwright’s built-in HTML report.

Output folder:

playwright-report/

Allure Reporter

['allure-playwright', {
    outputFolder: 'allure-results',
    suiteTitle: false
}]

This reporter creates raw execution data.

Output folder:

allure-results/

These settings match the Playwright configuration used in your project.


Step 3: Add npm Scripts

Open

package.json

Add:

{
  "scripts": {
    "test": "playwright test",
    "test:allure": "playwright test --reporter=list,allure-playwright",
    "allure:generate": "allure generate allure-results -o allure-report --clean",
    "allure:open": "allure open allure-report"
  }
}

Meaning of each script:

Run tests with Allure

npm run test:allure

Generates:

allure-results/

Generate HTML Report

npm run allure:generate

Creates:

allure-report/

Open Report

npm run allure:open

Starts a local web server and opens the report in your default browser.

These scripts are defined in your project’s package.json.


Step 4: Execute Playwright Tests

Run:

npm run test:allure

Example output:

Running 10 tests

✓ Login Test
✓ Logout Test
✓ Add Product
✓ Delete Product

10 passed

After execution, a new folder is created:

allure-results/

This folder contains files such as:

allure-results
│
├── *.json
├── *.txt
├── attachments
└── executor.json

These are the raw files used to build the final report.


Step 5: Generate the HTML Report

Run:

npm run allure:generate

Expected output:

Report successfully generated.

A new directory is created:

allure-report/

Inside:

allure-report
│
├── index.html
├── app.js
├── plugins
├── widgets
└── history

The report generation command produces the allure-report folder.


Step 6: Open the Report

Run:

npm run allure:open

Allure starts a local server:

http://127.0.0.1:5050

The report opens automatically in your default browser, allowing you to explore dashboards, suites, graphs, and test details.


Project Folder Structure

Playwright Project
│
├── tests
├── node_modules
├── playwright.config.ts
├── package.json
│
├── allure-results
│     ├── *.json
│     └── attachments
│
├── allure-report
│     ├── index.html
│     └── widgets
│
└── playwright-report

What Information Does Allure Capture?

By default, Allure records:

  • Test name
  • Execution status
  • Duration
  • Start and end time
  • Test suite
  • Error messages
  • Stack trace
  • Retries
  • Execution timeline

You can also enhance reports with:

  • Screenshots
  • Videos
  • Trace files
  • Environment details
  • Custom labels
  • Custom steps
  • Links to requirements or test cases

Common Commands

CommandPurpose
npm run test:allureExecute tests and generate Allure result files
npm run allure:generateBuild the HTML report
npm run allure:openOpen the generated report
npx playwright testRun Playwright tests only
npx playwright show-reportOpen Playwright’s built-in HTML report

Troubleshooting

Report is Empty

Possible causes:

  • Tests were not executed.
  • allure-results folder is empty.
  • Reporter is not configured correctly.

Solution:

npm run test:allure
npm run allure:generate

allure Command Not Found

Cause: allure-commandline is missing or not installed correctly.

Solution:

npm install --save-dev allure-commandline

Or run via:

npx allure generate allure-results -o allure-report --clean

Report Not Updating

Clean previous reports before regenerating:

rm -rf allure-results
rm -rf allure-report

Run the tests again and regenerate the report.


Best Practices

  • Keep both Playwright HTML and Allure reports enabled for different reporting needs.
  • Exclude allure-results and allure-report from version control to avoid committing generated artifacts.
  • Add screenshots and trace files for failed tests to improve debugging.
  • Generate a fresh report after every test execution.
  • Publish the allure-report folder as a CI/CD artifact in Jenkins or GitHub Actions for easy access.

Conclusion

Integrating Allure with Playwright provides a professional and feature-rich reporting solution that goes far beyond the default Playwright HTML report. By installing the required packages, configuring the Playwright reporter, adding npm scripts, executing tests, generating the report, and opening it locally, you can produce interactive reports that simplify debugging, improve test visibility, and make automation results easier to share with teams and stakeholders.

JavaScript Object Programs (Without Solution)

The following exercises are designed for developers who already understand JavaScript objects and want to practice solving real-world problems. Each program includes a scenario, input, expected output, and requirements without providing the solution.


1. Find the Employee with the Highest Salary

Scenario

A company stores employee details in an object. Find the employee who has the highest salary.

Input

const employees = {
    emp1: { name: "John", salary: 55000 },
    emp2: { name: "Alice", salary: 72000 },
    emp3: { name: "David", salary: 68000 }
};

Expected Output

Highest Salary Employee:
Alice
Salary: 72000

2. Count Product Categories

Scenario

An online shopping website stores products with categories. Count how many products belong to each category.

Input

const products = {
    p1: { category: "Electronics" },
    p2: { category: "Furniture" },
    p3: { category: "Electronics" },
    p4: { category: "Books" },
    p5: { category: "Books" }
};

Expected Output

Electronics : 2
Furniture : 1
Books : 2

3. Merge Student Information

Scenario

Merge two student objects into one object.

Input

const personal = {
    name: "Rahul",
    age: 21
};

const academic = {
    course: "B.Tech",
    marks: 88
};

Expected Output

{
    name: "Rahul",
    age: 21,
    course: "B.Tech",
    marks: 88
}

4. Find Missing Properties

Scenario

Check whether every employee object contains an email property.

Input

const employees = {
    emp1: {
        name: "John",
        email: "john@test.com"
    },
    emp2: {
        name: "Alice"
    },
    emp3: {
        name: "David",
        email: "david@test.com"
    }
};

Expected Output

Employee Missing Email:
Alice

5. Calculate Total Shopping Cart Value

Scenario

Calculate the total bill of all products in the shopping cart.

Input

const cart = {
    item1: {
        name: "Mouse",
        price: 700,
        quantity: 2
    },
    item2: {
        name: "Keyboard",
        price: 1200,
        quantity: 1
    },
    item3: {
        name: "Monitor",
        price: 9500,
        quantity: 1
    }
};

Expected Output

Total Cart Value:
12100

6. Remove Null Values from Object

Scenario

Remove all properties whose value is null.

Input

const user = {
    name: "Deepesh",
    phone: null,
    city: "Bhopal",
    email: null,
    age: 30
};

Expected Output

{
    name: "Deepesh",
    city: "Bhopal",
    age: 30
}

7. Find Duplicate Values

Scenario

Identify duplicate values present in an object.

Input

const students = {
    s1: "A",
    s2: "B",
    s3: "A",
    s4: "C",
    s5: "B"
};

Expected Output

Duplicate Values:
A
B

8. Convert Object into Sorted Array

Scenario

Convert the object values into an array and sort them in ascending order.

Input

const marks = {
    maths: 78,
    science: 91,
    english: 65,
    computer: 99
};

Expected Output

[65, 78, 91, 99]

9. Update Nested Object

Scenario

Update the city of the employee.

Input

const employee = {
    id: 101,
    name: "John",
    address: {
        city: "Delhi",
        state: "Delhi"
    }
};

Task

Update city to Mumbai.

Expected Output

{
    id:101,
    name:"John",
    address:{
        city:"Mumbai",
        state:"Delhi"
    }
}

10. Find Average Salary

Scenario

Calculate the average salary of all employees.

Input

const employees = {
    emp1: { salary: 45000 },
    emp2: { salary: 60000 },
    emp3: { salary: 75000 },
    emp4: { salary: 50000 }
};

Expected Output

Average Salary:
57500

11. Inventory Stock Checker

Scenario

Display all products whose quantity is less than 5.

Input

const inventory = {
    p1: { name: "Laptop", quantity: 3 },
    p2: { name: "Keyboard", quantity: 8 },
    p3: { name: "Mouse", quantity: 2 },
    p4: { name: "Monitor", quantity: 10 }
};

Expected Output

Low Stock Products:
Laptop
Mouse

12. Group Employees by Department

Scenario

Group employees based on department.

Input

const employees = {
    emp1: { name: "John", department: "IT" },
    emp2: { name: "Alice", department: "HR" },
    emp3: { name: "David", department: "IT" },
    emp4: { name: "Emma", department: "Finance" }
};

Expected Output

{
    IT: ["John", "David"],
    HR: ["Alice"],
    Finance: ["Emma"]
}

13. Find the Most Expensive Product

Scenario

Find the product with the highest price.

Input

const products = {
    p1: { name: "Phone", price: 25000 },
    p2: { name: "Laptop", price: 65000 },
    p3: { name: "Watch", price: 12000 }
};

Expected Output

Laptop
65000

14. Count Boolean Values

Scenario

Count how many properties have true and false values.

Input

const permissions = {
    read: true,
    write: false,
    delete: true,
    update: false,
    share: true
};

Expected Output

True : 3
False : 2

15. Reverse Key-Value Pairs

Scenario

Swap the keys and values of an object.

Input

const countryCodes = {
    India: "IN",
    America: "US",
    Japan: "JP"
};

Expected Output

{
    IN: "India",
    US: "America",
    JP: "Japan"
}

Top 50 Playwright Assertions Interview Questions and Answers

Assertions are one of the most frequently asked topics in Playwright interviews. They help verify whether the application behaves as expected after performing user actions. Playwright provides a powerful assertion library with auto-waiting, retry mechanisms, and rich error reporting, making tests more reliable and less flaky.

This guide covers beginner, intermediate, and advanced Playwright assertion interview questions with detailed answers and TypeScript examples.


1. What are Assertions in Playwright?

Answer

Assertions are used to verify that the actual result matches the expected result. If the expected condition is not met, the test fails.

Example

import { test, expect } from '@playwright/test';

test('Verify Page Title', async ({ page }) => {
    await page.goto('https://example.com');

    await expect(page).toHaveTitle('Example Domain');
});

2. Why are Assertions important in Automation Testing?

Answer

Assertions ensure that:

  • The application behaves correctly.
  • Test results are validated.
  • Bugs are detected automatically.
  • Expected UI and business logic are verified.

Without assertions, an automation script only performs actions without validating outcomes.


3. What assertion library does Playwright use?

Answer

Playwright Test provides a built-in expect() assertion library.

expect(value).toBe(expected);

4. What makes Playwright assertions better than traditional assertions?

Answer

Playwright assertions provide:

  • Auto-waiting
  • Automatic retries
  • Better error messages
  • Screenshot capture on failures
  • Trace support
  • Reduced flaky tests

5. What is expect() in Playwright?

Answer

expect() is used to validate expected results.

expect(10).toBe(10);

6. What is auto-waiting in Playwright assertions?

Answer

Playwright automatically waits until the expected condition becomes true or the timeout is reached.

Example:

await expect(page.locator('#login')).toBeVisible();

No explicit wait is required.


7. What happens if an assertion fails?

Answer

  • The current test fails.
  • Playwright captures useful diagnostics (such as screenshots and traces, if configured).
  • Remaining steps in the test are skipped unless soft assertions are used.

8. What is the default timeout for assertions?

Answer

By default, Playwright assertions use the configured expect timeout, which is 5 seconds unless changed in the Playwright configuration or overridden for a specific assertion.

Example:

await expect(locator).toBeVisible({
    timeout: 10000
});

9. Difference between toBe() and toEqual()?

Answer

toBe()toEqual()
Checks primitive values using strict equalityDeep comparison for objects and arrays
Best for numbers, strings, booleansBest for objects and arrays

Example:

expect(5).toBe(5);

expect({
    name: 'John'
}).toEqual({
    name: 'John'
});

10. What is not in Playwright assertions?

Answer

Used to verify negative conditions.

expect(5).not.toBe(10);

11. What is toBeTruthy()?

Answer

Checks whether a value is truthy.

expect(true).toBeTruthy();

12. What is toBeFalsy()?

Answer

Checks whether a value is falsy.

expect(false).toBeFalsy();

13. What is toBeNull()?

Answer

Checks if the value is null.

expect(null).toBeNull();

14. What is toBeDefined()?

Answer

Checks whether a variable is defined.

const username = 'Admin';

expect(username).toBeDefined();

15. What is toBeUndefined()?

Answer

Checks if a variable is undefined.

let city;

expect(city).toBeUndefined();

16. What is toContain()?

Answer

Checks whether an array or string contains a value.

expect('Playwright').toContain('wright');

17. What is toHaveLength()?

Answer

Verifies array or string length.

expect([1,2,3]).toHaveLength(3);

18. What is toBeGreaterThan()?

Answer

Checks if a value is greater than another value.

expect(100).toBeGreaterThan(50);

19. What is toBeLessThan()?

Answer

expect(10).toBeLessThan(20);

20. What is toBeCloseTo()?

Answer

Useful for floating-point numbers.

expect(0.1 + 0.2).toBeCloseTo(0.3);

21. What are Locator Assertions?

Answer

Locator assertions validate the state of UI elements.

Examples:

  • toBeVisible()
  • toBeHidden()
  • toBeEnabled()
  • toHaveText()
  • toHaveValue()

22. What is toBeVisible()?

Answer

Checks whether an element is visible.

await expect(
    page.locator('#login')
).toBeVisible();

23. What is toBeHidden()?

Answer

Checks if an element is hidden.

await expect(
    page.locator('.loader')
).toBeHidden();

24. What is toBeEnabled()?

Answer

Verifies that an element is enabled.

await expect(
    page.locator('#submit')
).toBeEnabled();

25. What is toBeDisabled()?

Answer

Checks if an element is disabled.

await expect(
    page.locator('#submit')
).toBeDisabled();

26. What is toBeChecked()?

Answer

Used for checkboxes and radio buttons.

await expect(
page.locator('#remember')
).toBeChecked();

27. What is toHaveText()?

Answer

Verifies exact text.

await expect(
page.locator('h1')
).toHaveText('Dashboard');

28. What is toContainText()?

Answer

Checks partial text.

await expect(
page.locator('.message')
).toContainText('Success');

29. Difference between toHaveText() and toContainText()?

Answer

toHaveText()toContainText()
Exact matchPartial match
Entire text must matchOnly a portion needs to match

30. What is toHaveValue()?

Answer

Checks the value of input fields.

await expect(
page.locator('#username')
).toHaveValue('Admin');

31. What is toHaveAttribute()?

Answer

Checks an HTML attribute.

await expect(
page.locator('#email')
).toHaveAttribute('type','email');

32. What is toHaveClass()?

Answer

Verifies CSS classes.

await expect(
page.locator('.active')
).toHaveClass('active');

33. What is toHaveCount()?

Answer

Checks the number of matching elements.

await expect(
page.locator('.product')
).toHaveCount(5);

34. What is toBeEditable()?

Answer

Checks if an input can be edited.

await expect(
page.locator('#username')
).toBeEditable();

35. What is toHaveCSS()?

Answer

Verifies CSS property values.

await expect(
page.locator('#title')
).toHaveCSS('color','rgb(255, 0, 0)');

36. What are Page Assertions?

Answer

Assertions used directly on the page.

Examples:

  • toHaveTitle()
  • toHaveURL()

37. What is toHaveTitle()?

Answer

Checks the page title.

await expect(page)
.toHaveTitle('Dashboard');

38. What is toHaveURL()?

Answer

Checks the current URL.

await expect(page)
.toHaveURL(/dashboard/);

39. What are Soft Assertions?

Answer

Soft assertions allow the test to continue even if an assertion fails.

expect.soft(title).toBe('Dashboard');

expect.soft(username).toBe('Admin');

40. When should you use Soft Assertions?

Answer

Use soft assertions when:

  • Validating multiple UI elements.
  • Collecting all failures in a single execution.
  • Creating comprehensive UI verification tests.

41. What is expect.poll()?

Answer

expect.poll() repeatedly executes a function until the expected result is achieved or the timeout expires.

await expect.poll(async () => {
    return await page.locator('.counter').textContent();
}).toBe('10');

42. What is the difference between expect() and expect.poll()?

Answer

expect()expect.poll()
Checks an immediate value or locatorRepeatedly evaluates a callback until the condition is met
Best for UI elements and direct valuesBest for values that change over time

43. What are Screenshot Assertions?

Answer

Used for visual regression testing.

await expect(page)
.toHaveScreenshot();

44. Can assertions be customized with messages?

Answer

Yes.

expect(
    total,
    'Total price should be greater than zero'
).toBeGreaterThan(0);

45. How do you verify API responses in Playwright?

Answer

const response = await page.request.get(
'https://reqres.in/api/users/2'
);

expect(response.status()).toBe(200);

expect(response.ok()).toBeTruthy();

46. What are common mistakes when writing assertions?

Answer

  • Using waitForTimeout() before assertions.
  • Verifying text with textContent() instead of toHaveText().
  • Writing unnecessary manual waits.
  • Using exact matches for dynamic values.
  • Overusing hard-coded timeouts.

47. Why are locator assertions preferred over manual value checks?

Answer

Locator assertions automatically wait for the expected condition and retry until the timeout expires, making tests more stable and less flaky.

Instead of:

const text = await page.locator('h1').textContent();
expect(text).toBe('Dashboard');

Prefer:

await expect(page.locator('h1')).toHaveText('Dashboard');

48. Can Playwright assertions be used with regular JavaScript variables?

Answer

Yes.

const total = 100;

expect(total).toBe(100);

49. How do you verify multiple conditions in one test?

Answer

await expect(page).toHaveTitle('Dashboard');

await expect(page).toHaveURL(/dashboard/);

await expect(page.locator('#logout'))
    .toBeVisible();

await expect(page.locator('.product'))
    .toHaveCount(5);

50. What are the best practices for Playwright Assertions?

Answer

  • Use locator assertions (toBeVisible(), toHaveText(), toHaveValue()) instead of manually reading values.
  • Avoid waitForTimeout(); rely on Playwright’s auto-waiting.
  • Use expect.soft() when multiple independent validations should run in the same test.
  • Use expect.poll() for asynchronous values that change over time.
  • Keep assertions specific and focused on a single expected outcome.
  • Use regular expressions for dynamic URLs and text where appropriate.
  • Write descriptive custom messages for critical business validations.
  • Prefer built-in Playwright assertions over custom validation logic whenever possible.

Bonus Interview Questions

1. What is the difference between expect(locator).toHaveText() and expect(await locator.textContent()).toBe()?

Answer:

toHaveText() automatically waits and retries until the expected text appears, making it more reliable for dynamic web pages. textContent() retrieves the current text immediately and does not retry.


2. Why should waitForTimeout() not be used before assertions?

Answer:

waitForTimeout() introduces unnecessary delays and can make tests flaky. Playwright assertions already include built-in waiting and retry mechanisms, so explicit sleep statements are rarely needed.


3. Which Playwright assertions are most commonly asked in interviews?

Answer:

The most frequently discussed assertions are:

  • toBe()
  • toEqual()
  • toContain()
  • toHaveText()
  • toContainText()
  • toBeVisible()
  • toBeHidden()
  • toBeEnabled()
  • toBeDisabled()
  • toHaveValue()
  • toHaveAttribute()
  • toHaveCount()
  • toHaveURL()
  • toHaveTitle()
  • expect.soft()
  • expect.poll()
  • toHaveScreenshot()

Mastering these assertions and understanding when to use each one will prepare you for most Playwright automation interviews, from beginner to advanced levels.

Top 50 Playwright Locator Interview Questions and Answers

Playwright locators are one of the most important interview topics for QA Automation Engineers, SDETs, and Test Automation Engineers. Interviewers frequently ask questions about locator strategies, best practices, auto-waiting, strict mode, and advanced locator chaining.


1. What is a Locator in Playwright?

Answer:

A locator is an object that identifies and interacts with elements on a web page. Unlike traditional selectors, Playwright locators automatically wait for elements to become available before performing actions.

Example

const loginButton = page.locator('#login');

await loginButton.click();

2. Why are Playwright Locators better than CSS or XPath?

Answer:

Playwright locators provide:

  • Auto-waiting
  • Retry mechanism
  • Better readability
  • Improved stability
  • Built-in strict mode
  • Better handling of dynamic pages

3. What is the difference between page.locator() and page.$()?

Answer:

page.locator()page.$()
Auto waitsNo auto wait
RecommendedDeprecated for most use cases
Supports retriesReturns immediately
Better stabilityMore flaky

Example:

await page.locator('#submit').click();

4. What is Strict Mode in Playwright?

Answer:

Strict mode ensures a locator resolves to exactly one element.

If multiple elements match, Playwright throws an error.

Example

await page.locator('button').click();

Error:

Strict mode violation:
Locator resolved to 5 elements.

5. How do you disable Strict Mode?

Answer:

Use methods like:

.first()

.last()

.nth(index)

Example

await page.locator('button').first().click();

6. Explain page.locator().

Answer:

Creates a reusable locator.

const username = page.locator('#username');

await username.fill('Admin');

7. What is getByRole()?

Answer:

Locates elements using their ARIA role.

Example

await page.getByRole('button', {
    name: 'Login'
}).click();

Recommended because it mimics user interaction.


8. Why is getByRole() preferred?

Answer:

  • Accessibility friendly
  • Stable
  • Less affected by UI changes
  • Easy to understand

9. What is getByText()?

Answer:

Finds elements using visible text.

await page.getByText('Sign In').click();

10. Difference between locator('text=Login') and getByText()?

Answer:

getByText() is more readable and recommended.

page.getByText('Login');

instead of

page.locator('text=Login');

11. What is getByLabel()?

Answer:

Locates form fields using associated labels.

await page.getByLabel('Username')
.fill('Admin');

12. What is getByPlaceholder()?

Answer:

Finds input elements using placeholder text.

await page
.getByPlaceholder('Search')
.fill('Laptop');

13. What is getByAltText()?

Answer:

Used for images.

page.getByAltText('Company Logo');

14. What is getByTitle()?

Answer:

Finds elements using the title attribute.

page.getByTitle('Settings');

15. What is getByTestId()?

Answer:

Locates elements using the data-testid attribute.

<button data-testid="login-btn">
page.getByTestId('login-btn');

16. Why is data-testid recommended?

Answer:

  • Independent of UI
  • Stable
  • Easy to maintain
  • Designed for automation

17. What is Locator Chaining?

Answer:

Locating elements inside another locator.

page.locator('.card')
.locator('button');

18. What is filter()?

Answer:

Filters locator results.

page.locator('.product')
.filter({
    hasText:'Laptop'
});

19. What is hasText?

Answer:

Filters elements by text.

page.locator('li').filter({
    hasText:'Apple'
});

20. What is has()?

Answer:

Filters elements containing another locator.

page.locator('.card').filter({

    has: page.locator('button')

});

21. What is nth()?

Answer:

Selects the element at a given index (zero-based).

page.locator('li').nth(2);

22. What is first()?

Answer:

Returns the first matching element.

page.locator('button').first();

23. What is last()?

Answer:

Returns the last matching element.

page.locator('button').last();

24. Difference between nth(0) and first()?

Answer:

Both return the first element, but first() is more readable and expressive.


25. How do you count matching elements?

Answer:

const count =
await page.locator('.product').count();

26. How do you loop through multiple elements?

Answer:

const items = page.locator('.product');

const count = await items.count();

for (let i = 0; i < count; i++) {
    console.log(await items.nth(i).textContent());
}

27. How do you get the text of an element?

Answer:

const text =
await page.locator('h1').textContent();

Prefer assertions when verifying text:

await expect(page.locator('h1'))
    .toHaveText('Dashboard');

28. What is allTextContents()?

Answer:

Returns the text content of all matching elements.

const texts =
await page.locator('li').allTextContents();

29. What is allInnerTexts()?

Answer:

Returns the rendered inner text of all matching elements, excluding hidden text in many cases.

const texts =
await page.locator('li').allInnerTexts();

30. Difference between textContent() and innerText()?

Answer:

textContent()innerText()
Includes hidden textReturns visible rendered text
FasterSlower due to layout calculations
Reads DOM textReads displayed text

31. How do you locate using CSS selectors?

Answer:

page.locator('#username');

page.locator('.login');

page.locator('input');

32. Can Playwright use XPath?

Answer:

Yes.

page.locator('//button');

However, CSS selectors and user-facing locators like getByRole() are generally preferred for readability and maintainability.


33. How do you locate a parent element?

Answer:

Use locator chaining or XPath when appropriate.

Example using chaining:

const card = page.locator('.card').filter({
  has: page.getByText('Product A')
});

34. How do you locate child elements?

Answer:

page.locator('.card')
.locator('button');

35. What is Auto Waiting?

Answer:

Playwright automatically waits until the target element is actionable (e.g., attached, visible, stable, and enabled where applicable) before performing actions.

Example:

await page.locator('#login').click();

36. Can Locators be reused?

Answer:

Yes.

const loginButton =
page.getByRole('button', { name: 'Login' });

await loginButton.click();
await expect(loginButton).toBeVisible();

37. Are Locators Lazy?

Answer:

Yes.

A locator does not immediately search the DOM. It resolves the element when an action or assertion is performed, allowing it to work with dynamic pages.


38. Difference between Locator and ElementHandle?

Answer:

LocatorElementHandle
Lazy evaluationSnapshot of a DOM element
Auto waitsNo automatic retries
RecommendedUse only for advanced scenarios
More resilientCan become stale

39. How do you wait for a Locator?

Answer:

Usually you don’t need to wait manually.

If needed:

await page.locator('#login').waitFor();

40. How do you verify a Locator exists?

Answer:

await expect(
page.locator('#login')
).toBeVisible();

41. How do you locate an element inside an iframe?

Answer:

Use frameLocator().

await page
.frameLocator('#payment-frame')
.getByRole('button', { name: 'Pay Now' })
.click();

42. How do you locate shadow DOM elements?

Answer:

Playwright automatically pierces open shadow DOMs, so standard locators often work without extra APIs.

await page.getByRole('button', { name: 'Submit' }).click();

43. What are the best locator strategies in Playwright?

Answer:

Preferred order:

  1. getByRole()
  2. getByLabel()
  3. getByPlaceholder()
  4. getByTestId()
  5. getByText()
  6. CSS selectors
  7. XPath (only when necessary)

44. Why should XPath be avoided when possible?

Answer:

  • More fragile
  • Harder to read
  • Breaks easily after DOM changes
  • Longer and more complex expressions

45. How do you handle dynamic locators?

Answer:

Use template literals.

const productName = 'Laptop';

await page.getByText(productName).click();

Or:

await page.locator(
    `[data-id="${productName}"]`
).click();

46. How do you locate a button with specific text?

Answer:

await page.getByRole('button', {
    name: 'Submit'
}).click();

47. How do you locate multiple buttons with the same text?

Answer:

Use nth(), first(), or last().

await page
.getByRole('button', { name: 'Edit' })
.nth(1)
.click();

48. How do you debug a locator?

Answer:

Useful techniques include:

  • Use Playwright Inspector (--debug)
  • Use page.pause()
  • Use the Playwright Codegen tool
  • Inspect the locator in browser DevTools
  • Verify uniqueness with assertions like toHaveCount(1)

Example:

await page.pause();

49. What are common locator mistakes?

Answer:

  • Using overly generic selectors like div or button
  • Relying on dynamic CSS classes
  • Depending on long XPath expressions
  • Using nth() unnecessarily when a unique locator is available
  • Adding manual waits instead of relying on locator auto-waiting

50. What are the best practices for Playwright locators?

Answer:

  • Prefer user-facing locators such as getByRole() and getByLabel().
  • Use data-testid for elements without stable accessible attributes.
  • Create reusable locators in Page Object Model classes.
  • Avoid brittle XPath and deeply nested CSS selectors.
  • Keep locators unique and descriptive.
  • Use Playwright assertions (toBeVisible(), toHaveText(), etc.) instead of manual checks.
  • Take advantage of locator chaining and filter() to make selectors more precise.
  • Write locators that reflect user behavior rather than implementation details.

Bonus Interview Question

What is the recommended locator priority in Playwright?

Answer:

The Playwright team recommends choosing locators in roughly this order:

  1. getByRole() – Best for accessibility and user-centric testing.
  2. getByLabel() – Ideal for form controls.
  3. getByPlaceholder() – Useful for inputs with meaningful placeholders.
  4. getByTestId() – Great for stable automation-specific selectors.
  5. getByText() – Suitable for visible text when it uniquely identifies the element.
  6. CSS selectors – Use when semantic locators are unavailable.
  7. XPath – Reserve for cases where no better locator strategy is feasible.

Following this hierarchy produces tests that are more readable, accessible, and resilient to UI changes.