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.

Github Action Example Pipeline

1. Git & GitHub Fundamentals

GitHub Actions relies on Git object mechanics. Workflows are declared as code and committed directly to your repository inside the .github/workflows/ directory. GitHub observes changes to Git references (refs/heads/<branch>, refs/tags/<tag>, refs/pull/<number>/merge) to evaluate trigger rules.

How Git Mechanics Map to Actions

  • Commits & Pushes: Every git push transmits a SHA hash and branch ref that GitHub Actions uses to check out the exact state of your code.
  • Pull Requests: A PR trigger creates a virtual merge commit (refs/pull/PR_NUMBER/merge) combining your source branch with the target branch to test collision-free execution.
  • Tags & Releases: Semantic version tags (v1.0.0) trigger build, package, and publish workflows.

Bash

# Developer Workflow triggering CI
git checkout -b feature/user-auth
git commit -m "feat: implement JWT login"
git push origin feature/user-auth # Triggers push / pull_request events on GitHub

2. YAML Syntax

Workflows are written in YAML (YAML Ain’t Markup Language). YAML uses strictly spaces for indentation (tabs are forbidden) and relies on key-value pairs, scalar types, arrays, and dictionaries.

Key Syntax Rules for GitHub Actions

  • Indentation: standard is 2 spaces per level.
  • Lists/Sequences: Prefixed with a hyphen and a space (- item).
  • Multi-line Strings: Use | to preserve line breaks or > to fold line breaks into spaces.
  • Booleans & Numbers: true, false, 10, 3.14 (unquoted). Quoting forces string representation ("true").

YAML

# Demonstration of YAML data structures
string_scalar: "Hello World"
number_scalar: 42
boolean_scalar: true

# List / Array syntax
browser_list:
  - chromium
  - firefox
  - webkit

# Dictionary / Object syntax
runner_config:
  os: ubuntu-latest
  timeout: 30

# Multi-line script execution block (| preserves newlines)
multi_line_command: |
  echo "Line 1"
  echo "Line 2"
  npm test

3. Creating Your First Workflow

A minimal workflow file must be stored in .github/workflows/main.yml. It requires three root keys: name, on, and jobs.

YAML

# .github/workflows/first-workflow.yml
name: First Workflow

# Event trigger
on:
  push:
    branches: [ "main" ]

# Execution unit
jobs:
  welcome-job:
    runs-on: ubuntu-latest
    steps:
      - name: Print welcome message
        run: echo "GitHub Actions workflow executed successfully!"

      - name: Output commit metadata
        run: |
          echo "Commit SHA: ${{ github.sha }}"
          echo "Triggered by: ${{ github.actor }}"

4. Events and Triggers (on)

The on key determines when a workflow runs. You can listen to single events, array events, or apply fine-grained activity filters and path filters.

Filtering Rules

  • branches: Restrict runs to specific target branches.
  • paths / paths-ignore: Trigger only when specific files change.
  • tags: Trigger on Git tags matching glob patterns.

YAML

name: Event Trigger Masterclass

on:
  # Trigger on pushes to main or release branches, but only if code inside src/ changed
  push:
    branches:
      - main
      - 'releases/v*'
    paths:
      - 'src/**'
      - 'package.json'
    paths-ignore:
      - '**.md'

  # Trigger on Pull Requests targeting main branch when opened or synchronized
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - main

  # Trigger on tag creation matching v1.0.0, v2.1.0, etc.
  push:
    tags:
      - 'v*.*.*'

5. Jobs and Steps

  • Job: A set of steps running on a specific host environment (runs-on). Jobs run in parallel by default.
  • Step: An individual task executed sequentially inside a job. Steps share a filesystem and environment state on the runner VM.

YAML

name: Job Dependency Pipeline

on: push

jobs:
  compile:
    runs-on: ubuntu-latest
    steps:
      - name: Step 1 - Build
        run: echo "Compiling assets..."

  test:
    needs: compile # Forces 'test' to wait until 'compile' finishes successfully
    runs-on: ubuntu-latest
    steps:
      - name: Step 1 - Unit Test
        run: echo "Executing unit tests..."

  deploy:
    needs: [compile, test] # Waits for both upstream jobs
    runs-on: ubuntu-latest
    steps:
      - name: Step 1 - Deploy
        run: echo "Deploying to production..."

6. Using Marketplace Actions

Instead of writing raw shell scripts for every task, you can import community and official actions from the GitHub Marketplace using the uses: keyword.

Versioning Actions

  • @v4 (Major version tag – receives non-breaking updates).
  • @v4.1.2 (Exact semantic version).
  • @8f4b7f8... (Full commit SHA – most secure, immutable).

YAML

jobs:
  setup-environment:
    runs-on: ubuntu-latest
    steps:
      # Action 1: Clone repository code
      - name: Checkout Repository
        uses: actions/checkout@v4

      # Action 2: Provision Node.js runtime environment
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      # Step 3: Native shell execution
      - name: Install dependencies
        run: npm ci

7. Environment Variables and Secrets

GitHub Actions handles environment configuration at the workflow, job, or step scope. Sensitive credentials must be stored as Encrypted Secrets in repository/organization settings.

YAML

name: Environment & Secrets Demo

on: push

# Workflow-level environment variables
env:
  GLOBAL_APP_NAME: "MyEnterpriseApp"
  LOG_LEVEL: "debug"

jobs:
  process-payment:
    runs-on: ubuntu-latest
    # Job-level environment variables
    env:
      JOB_ENV: "payment-processor"

    steps:
      - name: Secure API Call
        # Step-level environment variables
        env:
          PAYMENT_API_KEY: ${{ secrets.PAYMENT_GATEWAY_KEY }} # Injecting secret
          DYNAMIC_VAR: "step-specific-value"
        run: |
          echo "Processing payment for $GLOBAL_APP_NAME"
          # Accessing secret safely via environment variable in shell
          python process.py --key "$PAYMENT_API_KEY"

      - name: Set dynamic environment variable for subsequent steps
        run: |
          echo "BUILD_TIMESTAMP=$(date +'%Y-%m-%d_%H-%M-%S')" >> $GITHUB_ENV

      - name: Read dynamic variable
        run: |
          echo "Timestamp was: $BUILD_TIMESTAMP"

8. Expressions and Conditional Execution

Expressions let you evaluate programmatic conditions and access context objects (github, env, runner, steps, secrets). Use if: directives to skip jobs or steps dynamically.

YAML

jobs:
  conditional-job:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Execute on main branch only
        if: github.ref == 'refs/heads/main'
        run: echo "This step runs ONLY on pushes to main."

      - name: Execute step with custom status check functions
        id: test_step
        run: npm test

      # Runs ONLY if the previous step failed
      - name: Report Failure
        if: failure() && steps.test_step.outcome == 'failure'
        run: echo "The test execution step failed!"

      # Runs ALWAYS, regardless of prior step pass/fail state
      - name: Always Cleanup
        if: always()
        run: echo "Cleaning up temporary test artifacts..."

9. Matrix Strategy

A Matrix Strategy generates multiple job runs by defining input variables across OSs, runtimes, or database versions. GitHub Actions expands these configurations into a parallel execution grid.

YAML

jobs:
  matrix-build:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false # Keep running other matrix jobs even if one fails
      max-parallel: 4 # Limit concurrent runners
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        node-version: [18, 20]
        # Include specific additional configuration
        include:
          - os: ubuntu-latest
            node-version: 22
            experimental: true
        # Exclude invalid or unwanted combinations
        exclude:
          - os: windows-latest
            node-version: 18

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
      - run: node -v

10. Caching Dependencies

To speed up workflow runs, use actions/cache or built-in caching inside setup actions. Caches persist archive files between workflow runs using a unique cache key (typically hashed from lockfiles).

YAML

jobs:
  cache-demo:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # Method A: Built-in setup action caching (Recommended)
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip' # Automatically hashes requirements.txt/Pipfile

      # Method B: Manual Cache Configuration via actions/cache
      - name: Cache Custom Directory
        uses: actions/cache@v4
        with:
          path: ~/.custom_cache_dir
          # Primary lookup key
          key: ${{ runner.os }}-custom-${{ hashFiles('**/lockfile.json') }}
          # Fallback lookup keys if primary key misses
          restore-keys: |
            ${{ runner.os }}-custom-

      - name: Install Dependencies
        run: pip install -r requirements.txt

11. Uploading and Downloading Artifacts

Artifacts allow you to persist output files (build binaries, test reports, coverage HTML) beyond the runner’s ephemeral lifecycle and pass data between independent jobs.

YAML

jobs:
  build-job:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: mkdir dist && echo "Compiled App Code" > dist/app.bin

      # Upload artifacts
      - name: Upload Build Binaries
        uses: actions/upload-artifact@v4
        with:
          name: compiled-app-artifact
          path: dist/
          retention-days: 7

  deploy-job:
    needs: build-job # Must wait for build-job to upload
    runs-on: ubuntu-latest
    steps:
      # Download artifacts generated in upstream job
      - name: Download Build Binaries
        uses: actions/download-artifact@v4
        with:
          name: compiled-app-artifact
          path: downloaded-dist/

      - name: Verify Downloaded Assets
        run: cat downloaded-dist/app.bin

12. Manual and Scheduled Workflows

Workflows can run on cron schedules or be triggered manually via the GitHub UI/API with custom user inputs (workflow_dispatch).

YAML

name: Manual & Scheduled Execution

on:
  # Cron trigger: Runs every Monday at 08:00 UTC
  schedule:
    - cron: '0 8 * * 1'

  # Manual trigger with interactive input forms
  workflow_dispatch:
    inputs:
      target_env:
        description: 'Target Deployment Environment'
        type: choice
        required: true
        options:
          - staging
          - production
      perform_cleanup:
        description: 'Run deep database cleanup?'
        type: boolean
        default: false

jobs:
  execute:
    runs-on: ubuntu-latest
    steps:
      - name: Print Trigger Context
        run: |
          echo "Trigger event: ${{ github.event_name }}"
          echo "Selected Environment: ${{ inputs.target_env }}"
          echo "Perform Cleanup: ${{ inputs.perform_cleanup }}"

13. Reusable Workflows and Composite Actions

Composite Action (.github/actions/setup-stack/action.yml)

Bundles multiple run steps into a single reusable step block.

YAML

name: 'Setup Project Stack'
description: 'Standardized setup steps for project'
runs:
  using: 'composite'
  steps:
    - uses: actions/setup-node@v4
      with:
        node-version: '20'
    - run: npm ci
      shell: bash # Shell directive is mandatory for composite actions

Reusable Workflow (.github/workflows/reusable-ci.yml)

Encapsulates complete jobs for consumption across callers.

YAML

name: Reusable CI Core
on:
  workflow_call:
    inputs:
      node-version:
        type: string
        default: '20'
jobs:
  run-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ inputs.node-version }}
      - run: npm test

Calling Workflow (.github/workflows/caller.yml)

YAML

jobs:
  invoke-reusable:
    uses: ./.github/workflows/reusable-ci.yml
    with:
      node-version: '22'

14. Docker Integration

GitHub Actions runners come pre-configured with Docker, enabling step containers, containerized jobs, service containers (databases/queues), and image publishing.

YAML

jobs:
  # Integration testing using a Database Service Container
  database-tests:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_PASSWORD: mysecretpassword
          POSTGRES_DB: testdb
        ports:
          - 5432:5432
        # Health checks to ensure DB is ready before test steps start
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - uses: actions/checkout@v4
      - name: Verify PostgreSQL Connection
        run: |
          PGPASSWORD=mysecretpassword psql -h localhost -U postgres -d testdb -c "SELECT 1;"

  # Build & Publish Docker Container Image
  docker-build-push:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Log in to GitHub Container Registry (GHCR)
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ghcr.io/${{ github.repository }}/app:latest

15. Cloud Deployments (AWS/Azure/GCP)

To deploy safely to modern cloud infrastructure, never use long-lived access key secrets. Use OpenID Connect (OIDC) to request temporary, short-lived tokens using IAM Role assumption.

YAML

name: Keyless OIDC AWS Deployment

on:
  push:
    branches: [ "main" ]

jobs:
  deploy-aws:
    runs-on: ubuntu-latest
    # Required permission to request the OIDC JWT token from GitHub
    permissions:
      id-token: write
      contents: read

    steps:
      - uses: actions/checkout@v4

      - name: Authenticate with AWS via OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsDeploymentRole
          aws-region: us-east-1

      - name: Deploy to S3 Static Bucket
        run: |
          aws s3 sync ./dist s3://my-production-app-bucket --delete

16. Enterprise CI/CD Patterns and Security

Production enterprise workflows require strict security practices: Zero Trust permissions, Pinned Action Hashes, Concurrency Controls, and Protected Environments.

YAML

name: Enterprise Secure Pipeline

on:
  push:
    branches: [ "main" ]

# Prevent race conditions by cancelling in-progress runs on same branch
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

# Hardened Security Rule 1: Set Least-Privilege permissions globally
permissions: {}

jobs:
  secure-build:
    runs-on: ubuntu-latest
    permissions:
      contents: read # Read-only code access
      id-token: write # For OIDC deployment step

    # Attach workflow to protected GitHub Environment (Approval rules & secrets)
    environment:
      name: production
      url: https://my-app.company.com

    steps:
      # Hardened Security Rule 2: Pin Actions to full immutable commit SHAs
      - name: Checkout Code
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2

      - name: Setup Node.js
        uses: actions/setup-node@39370e3970a6d050c080011e813206d11393d18e # v4.1.0
        with:
          node-version: '20'

      - name: Run Dependency Vulnerability Audit
        run: npm audit --audit-level=high

      - name: Build Application
        run: npm run build

GitHub Actions Hands-on Practice Projects

1. Hello World Workflow

A minimal workflow to test trigger mechanics, job execution, and basic logging in GitHub Actions.

YAML

name: Hello World

on:
  push:
    branches: [ "main" ]
  workflow_dispatch:

jobs:
  say-hello:
    runs-on: ubuntu-latest
    steps:
      - name: Print Welcome Message
        run: echo "Hello World from GitHub Actions!"
      
      - name: Display Runner Details
        run: |
          echo "Triggered event: ${{ github.event_name }}"
          echo "Running on branch: ${{ github.ref_name }}"
          echo "Executed by: ${{ github.actor }}"

2. Node.js Build Pipeline

Automates dependencies installation, build scripts execution, and unit tests using Node.js with package manager caching.

YAML

name: Node.js CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build-and-test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run linter
        run: npm run lint --if-present

      - name: Build application
        run: npm run build --if-present

      - name: Execute unit tests
        run: npm test

3. Python CI Pipeline

Runs static analysis, dependency installation, and pytest execution for Python projects.

YAML

name: Python CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
          pip install pytest flake8

      - name: Lint with flake8
        run: |
          # stop the build if there are Python syntax errors or undefined names
          flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
          # exit-zero treats all errors as warnings.
          flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics

      - name: Run Pytest
        run: pytest

4. Java Maven Pipeline

Sets up OpenJDK, caches local Maven dependencies, builds the project, and runs integration tests.

YAML

name: Java CI with Maven

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'
          cache: maven

      - name: Build with Maven
        run: mvn -B package --file pom.xml

      - name: Run Tests
        run: mvn test

5. Playwright Automation Workflow

Installs system dependencies and browser binaries required to execute Playwright end-to-end tests headless in CI.

YAML

name: Playwright Tests

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  playwright-tests:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Install Playwright Browsers & OS Dependencies
        run: npx playwright install --with-deps

      - name: Run Playwright tests
        run: npx playwright test

      - name: Upload Playwright Report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 30

6. Selenium Pytest Workflow

Executes Selenium browser automation tests using headless Chrome in a Python environment.

YAML

name: Selenium Pytest Pipeline

on:
  push:
    branches: [ "main" ]

jobs:
  selenium-tests:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'
          cache: 'pip'

      - name: Install Dependencies
        run: |
          pip install --upgrade pip
          pip install selenium pytest pytest-xdist

      - name: Run Selenium Tests (Headless Chrome)
        run: pytest tests/ui/ --headless

7. Parallel Browser Execution with a Matrix Strategy

Spins up isolated, parallel runners for multiple browser engine combinations simultaneously to accelerate test execution.

YAML

name: Cross-Browser Matrix Execution

on:
  push:
    branches: [ "main" ]

jobs:
  matrix-test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        browser: [chromium, firefox, webkit]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npm ci

      - name: Install Matrix Browser (${{ matrix.browser }})
        run: npx playwright install ${{ matrix.browser }} --with-deps

      - name: Run Tests on ${{ matrix.browser }}
        run: npx playwright test --project=${{ matrix.browser }}

8. Scheduled Nightly Test Execution

Uses cron scheduling syntax to trigger automated regression suites at a designated time without manual intervention.

YAML

name: Nightly Regression Suite

on:
  schedule:
    # Runs at 00:00 UTC every day
    - cron: '0 0 * * *'
  workflow_dispatch: # Allows manual trigger if needed

jobs:
  nightly-tests:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install Dependencies
        run: npm ci

      - name: Execute Nightly Regression
        run: npm run test:regression

9. Manual Workflow with User Inputs

Presents interactive inputs in the GitHub UI for standard testing parameters like target environment, target browser, and debug flags.

YAML

name: Manual Test Trigger

on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Target Deployment Environment'
        required: true
        default: 'staging'
        type: choice
        options:
          - dev
          - qa
          - staging
          - production
      browser:
        description: 'Browser Choice'
        required: true
        default: 'chrome'
        type: choice
        options:
          - chrome
          - firefox
          - safari
      headless:
        description: 'Run in Headless Mode?'
        required: true
        type: boolean
        default: true

jobs:
  run-custom-test:
    runs-on: ubuntu-latest
    steps:
      - name: Print User Parameters
        run: |
          echo "Running tests against: ${{ inputs.environment }}"
          echo "Selected Browser: ${{ inputs.browser }}"
          echo "Headless mode: ${{ inputs.headless }}"

      - name: Checkout code
        uses: actions/checkout@v4

      - name: Run Suite
        run: |
          echo "Executing test CLI commands with flags..."
          # Example CLI invocation:
          # npm test -- --env=${{ inputs.environment }} --browser=${{ inputs.browser }} --headless=${{ inputs.headless }}

10. Upload HTML and Allure Reports

Executes tests, generates report output, and attaches compiled HTML and Allure report assets to the workflow summary using if: always().

YAML

name: Test Suite with Allure Reporting

on:
  push:
    branches: [ "main" ]

jobs:
  test-and-report:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install Dependencies
        run: |
          pip install pytest allure-pytest

      - name: Run Tests & Generate Allure Results
        run: pytest --alluredir=allure-results
        continue-on-error: true

      - name: Install Allure CLI & Generate HTML Report
        run: |
          sudo wget https://github.com/allure-framework/allure2/releases/download/2.24.0/allure-2.24.0.tgz
          sudo tar -zxvf allure-2.24.0.tgz -C /opt/
          sudo ln -s /opt/allure-2.24.0/bin/allure /usr/bin/allure
          allure generate allure-results --clean -o allure-report

      - name: Upload Allure HTML Report Artifact
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: allure-html-report
          path: allure-report/
          retention-days: 14

11. Reusable Workflow for Common Test Execution

Defines a modular, parameterized reusable workflow (workflow_call) and demonstrates how a caller workflow invokes it across repositories or jobs.

Standard Reusable Workflow (.github/workflows/reusable-test.yml)

YAML

name: Shared Test Runner

on:
  workflow_call:
    inputs:
      test_suite:
        required: true
        type: string
      node_version:
        required: false
        type: string
        default: '20'
    secrets:
      API_TOKEN:
        required: true

jobs:
  execute-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ inputs.node_version }}
      - run: npm ci
      - name: Run Test Suite
        env:
          API_TOKEN: ${{ secrets.API_TOKEN }}
        run: npm run test:${{ inputs.test_suite }}

Caller Workflow (.github/workflows/main-pipeline.yml)

YAML

name: Main Pipeline

on:
  push:
    branches: [ "main" ]

jobs:
  run-smoke-tests:
    uses: ./.github/workflows/reusable-test.yml
    with:
      test_suite: 'smoke'
      node_version: '20'
    secrets:
      API_TOKEN: ${{ secrets.SMOKE_API_TOKEN }}

12. Docker Build and Publish Pipeline

Authenticates to Docker Hub (or GHCR), configures Docker Buildx, and pushes a multi-arch container image.

YAML

name: Docker Build and Publish

on:
  push:
    tags:
      - 'v*.*.*'
    branches:
      - 'main'

jobs:
  docker-build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Extract Metadata (Tags, Labels)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ secrets.DOCKERHUB_USERNAME }}/my-app

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

13. Deploy to AWS EC2

Connects to AWS using OpenID Connect (OIDC) and deploys updated application builds to an EC2 target via SSH.

YAML

name: Deploy to AWS EC2

on:
  push:
    branches: [ "main" ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      - name: Configure AWS Credentials (OIDC)
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsEC2DeployRole
          aws-region: us-east-1

      - name: Deploy to EC2 via SSH
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ec2-user
          key: ${{ secrets.EC2_SSH_PRIVATE_KEY }}
          script: |
            cd /var/www/myapp
            git pull origin main
            npm install --production
            pm2 restart all

14. Trigger One Workflow from Another

Uses the workflow_run event trigger to execute a downstream automation workflow automatically after an upstream workflow finishes.

Downstream Workflow (.github/workflows/deploy-on-ci-success.yml)

YAML

name: Deployment Triggered by CI Success

on:
  workflow_run:
    workflows: ["Node.js CI"]  # Name of upstream workflow
    types:
      - completed

jobs:
  on-success:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - name: Run Downstream Task
        run: echo "Upstream CI succeeded! Starting deployment process..."
        
  on-failure:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'failure' }}
    steps:
      - name: Notify Team of Failure
        run: echo "Upstream CI failed. Aborting downstream triggers."

15. Multi-Environment Deployment (Dev → QA → Staging → Production)

Establishes sequential environment promotion chains using needs conditions, protected environments, and manual gating rules.

YAML

name: Multi-Environment Promotion Pipeline

on:
  push:
    branches: [ "main" ]

jobs:
  deploy-dev:
    name: Deploy to Development
    runs-on: ubuntu-latest
    environment: dev
    steps:
      - uses: actions/checkout@v4
      - name: Run Dev Deployment
        run: echo "Deploying build commit ${{ github.sha }} to DEV environment"

  deploy-qa:
    name: Deploy to QA
    needs: deploy-dev
    runs-on: ubuntu-latest
    environment: qa
    steps:
      - uses: actions/checkout@v4
      - name: Run QA Deployment
        run: echo "Deploying build commit ${{ github.sha }} to QA environment"

  deploy-staging:
    name: Deploy to Staging
    needs: deploy-qa
    runs-on: ubuntu-latest
    environment: staging
    steps:
      - uses: actions/checkout@v4
      - name: Run Staging Deployment
        run: echo "Deploying build commit ${{ github.sha }} to STAGING environment"

  deploy-production:
    name: Deploy to Production
    needs: deploy-staging
    runs-on: ubuntu-latest
    # Requires manual reviewer approval set up under GitHub Environment rules
    environment: production
    steps:
      - uses: actions/checkout@v4
      - name: Run Production Deployment
        run: echo "Deploying build commit ${{ github.sha }} to PRODUCTION environment"

Github Fundamentals Intermediate

1. What is Matrix Strategy?

A matrix strategy lets you run a single job multiple times using variations of inputs (like different OSs, runtime versions, or build flags). GitHub Actions automatically creates a parallel job for every possible combination of matrix variables.

YAML

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest]
        node-version: [18, 20, 22]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm test

This example runs 6 parallel jobs ($2 \text{ OSs} \times 3 \text{ Node versions}$).

2. Explain Caching

Caching stores dependencies (such as node_modules, Maven packages, or Docker layers) across workflow runs. Because runner VMs are completely wiped after every job, downloading dependencies repeatedly wastes time and bandwidth.

You can use actions/cache@v4 or built-in caching options inside setup actions (like actions/setup-node).

YAML

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      # Built-in caching for NPM dependencies
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'
      - run: npm ci

When a cache key matches, the runner downloads the pre-packaged dependencies instead of reinstalling them from the internet.

3. How Do You Upload Artifacts?

Artifacts are files or directories generated during a job (e.g., compiled binaries, test coverage logs, APKs) that you want to save after the runner VM is destroyed.

You use the actions/upload-artifact@v4 action to attach files to the workflow run.

YAML

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm run build
      - name: Save build output
        uses: actions/upload-artifact@v4
        with:
          name: web-dist
          path: dist/

Uploaded artifacts can be downloaded manually from the GitHub UI or programmatically by other jobs.

4. How Do Jobs Communicate?

Because every job executes in a completely isolated virtual machine, they do not share filesystem memory or local variables directly. Jobs communicate in two primary ways:

Method A: Job Outputs (For Small Data / Strings)

Pass scalar values (like commit IDs, version numbers, or status flags) via $GITHUB_OUTPUT.

YAML

jobs:
  generator:
    runs-on: ubuntu-latest
    outputs:
      app_version: ${{ steps.set_version.outputs.version }}
    steps:
      - id: set_version
        run: echo "version=1.2.3" >> $GITHUB_OUTPUT

  receiver:
    needs: generator
    runs-on: ubuntu-latest
    steps:
      - run: echo "The version is ${{ needs.generator.outputs.app_version }}"

Method B: Artifacts (For Files / Directories)

Pass files between jobs using actions/upload-artifact in Job 1 and actions/download-artifact in Job 2.

5. Explain Reusable Workflows

Reusable Workflows allow you to avoid duplicating workflow code across repositories or within the same repository. Instead of copying and pasting pipeline definitions, you create a central workflow file and invoke it from caller workflows.

A reusable workflow must use the workflow_call trigger:

YAML

# .github/workflows/reusable-build.yml (Called Workflow)
name: Reusable Build Component
on:
  workflow_call:
    inputs:
      target-env:
        type: string
        required: true

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Building for ${{ inputs.target-env }}"

Caller workflow usage:

YAML

# .github/workflows/main.yml (Caller Workflow)
jobs:
  run-reusable:
    uses: ./.github/workflows/reusable-build.yml
    with:
      target-env: 'production'

6. Difference Between uses and run

Featurerunuses
PurposeExecutes inline shell commands or scripts.Executes a pre-packaged Action or Reusable Workflow.
SourceRuns directly on the runner shell (Bash, PowerShell, zsh).Fetched from GitHub Marketplace, local files, or public repositories.
Examplerun: npm testuses: actions/checkout@v4

7. What is needs?

By default, jobs in a workflow execute in parallel. The needs keyword defines dependency requirements to force sequential execution or form an execution chain (DAG).

YAML

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - run: npm test

  deploy:
    needs: test # Waits for 'test' job to complete successfully
    runs-on: ubuntu-latest
    steps:
      - run: ./deploy.sh

If test fails, deploy is automatically skipped.

8. How Do You Trigger Workflows Conditionally?

You can run workflows, jobs, or individual steps conditionally using if expressions or trigger filters:

Method A: Step or Job Level if Condition

YAML

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to Prod
        # Runs only if the event is a push to main branch
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: ./deploy-prod.sh

Method B: Event Path/Branch Filtering (on)

YAML

on:
  push:
    branches:
      - main
    paths:
      - 'src/**' # Triggers only if files in src/ change

9. What are Environments?

Environments describe continuous deployment targets like production, staging, or development. They allow you to attach security controls and configuration variables directly to a deployment target.

Key features of Environments:

  • Required Reviewers: Pause workflow execution until specified team members manually approve.
  • Wait Timers: Delay deployment after a trigger (e.g., wait 15 minutes before pushing).
  • Environment Secrets/Variables: Restrict deployment keys so they are only accessible when running against that specific environment.

YAML

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment:
      name: production
      url: https://myapp.com
    steps:
      - run: ./deploy.sh

10. What are Concurrency Groups?

Concurrency Groups ensure that only a single job or workflow run within a designated group executes at any given time. If a new run starts while a previous run is in progress, GitHub Actions can automatically cancel the old run or queue the new run.

This prevents deployment race conditions or redundant builds when developers rapidly push multiple commits.

YAML

name: Deploy Pipeline
on: push

# Prevents simultaneous deployments on the same branch
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true # Cancels any previous run still processing

GitHub Actions Advanced Concept

1. What is OIDC Authentication?

OpenID Connect (OIDC) allows GitHub Actions to authenticate directly with cloud providers (AWS, Azure, GCP) using short-lived JWT tokens rather than long-lived, hardcoded credentials or API keys.

  1. The runner requests an OIDC JSON Web Token (JWT) from GitHub’s OIDC provider.
  2. The runner sends this JWT to the cloud provider (e.g., AWS Security Token Service).
  3. The cloud provider validates the signature, evaluates claims (such as repository name, branch, or environment), and exchanges the JWT for short-lived cloud credentials.

2. How Do You Deploy Securely to AWS?

Use OIDC alongside the official aws-actions/configure-aws-credentials action instead of storing AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY inside repository secrets.

YAML

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # Grants permission to fetch the OIDC JWT token
      contents: read
    steps:
      - uses: actions/checkout@v4
      
      - name: Authenticate with AWS via OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsDeployRole
          aws-region: us-east-1

      - name: Deploy AWS Infrastructure
        run: aws s3 sync ./dist s3://my-production-bucket

3. How Do You Optimize Large Workflows?

  • Smart Caching: Cache dependency directories (~/.npm, ~/.m2, target folders) using build-tool-native caching options.
  • Path & Branch Filtering: Use paths and paths-ignore so workflows run only when relevant code changes.
  • Job Dependencies (needs): Fail fast by placing cheap checks (linting, static analysis) before heavy build/test jobs.
  • Matrix Filtering / Cancellation: Set fail-fast: true inside matrix strategies so remaining matrix combinations cancel immediately if one fails.
  • Concurrency Cancellation: Set cancel-in-progress: true inside concurrency blocks to terminate stale builds on new commits.

YAML

on:
  push:
    paths:
      - 'src/**'  # Ignore documentation or root README changes

4. How Do You Reuse Workflows Across Repositories?

Reference a reusable workflow stored in an external repository using the {owner}/{repo}/.github/workflows/{filename}.yml@{ref} syntax. The target repository must have its visibility set to public or shared within an organization.

YAML

# In repo: caller-org/app-repo
jobs:
  call-shared-ci:
    # References shared pipeline from security-team/shared-workflows repo
    uses: security-team/shared-workflows/.github/workflows/ci-template.yml@v2.1
    with:
      environment: 'staging'
    secrets: inherit # Automatically passes caller secrets to called workflow

5. What are Composite Actions?

A Composite Action aggregates multiple step commands or actions into a single reusable action. Unlike reusable workflows (which encompass full jobs), composite actions run as a single step within a job.

They are defined in an action.yml file and require runs.using: 'composite' and an explicit shell: directive on every run step.

YAML

# .github/actions/setup-node-and-cache/action.yml
name: 'Setup Node and Cache'
description: 'Custom setup wrapper for project standard initialization'

inputs:
  node-version:
    default: '20'

runs:
  using: 'composite'
  steps:
    - uses: actions/setup-node@v4
      with:
        node-version: ${{ inputs.node-version }}
        cache: 'npm'
    - name: Install dependencies
      shell: bash  # Required in composite actions
      run: npm ci

6. How Do You Secure Secrets?

  • Use Least Privilege: Restrict secret exposure using Environment Secrets gated behind approval environments.
  • Never Print Secrets: Avoid passing secrets directly into shell scripts where set -x or debug flags could print them to standard output.
  • Avoid PR Triggers from Forks: Workflows triggered by pull_request from fork repositories do not receive access to repository secrets by default.
  • Pass Secrets via Environment Variables: Pass secrets to scripts using env blocks rather than raw string replacement inside commands to avoid process listing injection.

YAML

steps:
  - name: Run Secure Script
    env:
      DB_PASSWORD: ${{ secrets.DB_PASSWORD }} # Passed as env var, not inline text
    run: python db_migrate.py

7. What is Least-Privilege Workflow Permission?

By default, GITHUB_TOKEN may inherit read/write permissions depending on organization settings. To enforce least privilege, set global workflow permissions to read-all or contents: read, and grant specific elevated scopes only to the jobs that require them.

YAML

name: Security Standard Pipeline
on: push

# Deny all permissions globally by default
permissions: {}

jobs:
  build_and_test:
    runs-on: ubuntu-latest
    permissions:
      contents: read # Read-only access to code
    steps:
      - uses: actions/checkout@v4
      - run: npm test

  publish_release:
    needs: build_and_test
    runs-on: ubuntu-latest
    permissions:
      contents: write # Granted write access ONLY for release generation
    steps:
      - uses: actions/checkout@v4
      - run: gh release create v1.0.0
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

8. How Do You Handle Rollbacks?

Automate rollbacks using conditional steps (if: failure()) or a dedicated rollback workflow triggered by deployment checks.

YAML

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Deploy Release
        id: deploy_step
        run: ./deploy-app.sh

      - name: Healthcheck Target
        id: healthcheck
        run: ./verify-endpoint.sh

      - name: Trigger Automated Rollback
        if: failure() && steps.deploy_step.outcome == 'success'
        run: ./rollback-to-previous-image.sh

9. How Do You Implement Blue-Green Deployment?

Deploy the new application version to an isolated “Green” environment, perform health checks, and swap live traffic routing (e.g., DNS, Load Balancer, or ingress route) from “Blue” to “Green”.

YAML

jobs:
  blue_green_deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4

      - name: Deploy to Green Environment
        run: ./deploy-green.sh --version ${{ github.sha }}

      - name: Run Integration Tests Against Green
        run: ./test-target.sh --url https://green.internal.myapp.com

      - name: Switch Traffic (Blue -> Green)
        run: ./switch-load-balancer.sh --target green

10. How Do You Debug Failed Workflows?

  • Enable Runner Diagnostic / Step Debug Logging: Set repository secrets ACTIONS_STEP_DEBUG = true and ACTIONS_RUNNER_DEBUG = true to produce verbose log outputs.
  • Re-run Jobs with Debug Logging Enabled: Click Re-run jobs -> check Enable debug logging from the GitHub UI interface.
  • Inspect Artifacts: Save log files, crash dumps, or screenshots using actions/upload-artifact@v4 inside an if: always() step.

YAML

steps: – name: Run Test Suite run: npm test – name: Capture Failure Logs if: failure() uses: actions/upload-artifact@v4 with: name: test-failure-logs path: ./logs/

GitHub Actions Fundamentals for Beginners

1. What is GitHub Actions?

GitHub Actions is an automated CI/CD (Continuous Integration and Continuous Delivery) platform built directly into GitHub. It allows you to automate software workflows directly from your repository—such as building code, running tests, publishing packages, or deploying applications—whenever specific GitHub events occur.

YAML

# Simple example: Running tests whenever code is pushed
name: CI Pipeline
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm install
      - run: npm test

2. What is a Workflow?

A Workflow is an automated, configurable process defined in a .yml (or .yaml) file stored inside your repository’s .github/workflows/ directory. A repository can have multiple workflows (e.g., one for unit testing, one for code linting, and one for production deployments).

Workflows are triggered by events (like a push, pull_request, or schedule) and consist of one or more jobs.

YAML

# .github/workflows/greeting.yml
name: Daily Greeting
on:
  schedule:
    - cron: '0 9 * * 1-5' # Runs every weekday at 9 AM UTC

jobs:
  greet:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Good morning, team!"

3. What is a Runner?

A Runner is an application or server that executes the jobs inside a GitHub Actions workflow. When a workflow is triggered, GitHub assigns a runner to listen for available jobs, run the steps, and stream the logs and results back to GitHub.

Runners come pre-installed with standard development tooling (Git, Node.js, Python, Docker, Docker Compose, CLI tools, etc.).

4. Difference Between Job and Step

  • Job: A group of steps that execute on the same runner instance. By default, if a workflow has multiple jobs, they run in parallel unless configured to run sequentially using needs.
  • Step: An individual task within a job. Steps run sequentially on the runner and share the same environment and filesystem. A step can either run a shell command (run) or execute a reusable action (uses).
FeatureJobStep
ExecutionRuns in parallel (default) or sequentiallyAlways runs sequentially inside its parent job
EnvironmentRuns on its own separate virtual machine / runnerShares the virtual machine environment with other steps in the job
Data SharingFilesystem is isolated from other jobsShares local filesystem changes directly with subsequent steps

YAML

jobs:
  build_job: # JOB 1
    runs-on: ubuntu-latest
    steps:
      - name: Step 1 # STEP 1.1
        run: echo "Compiling code..."
      - name: Step 2 # STEP 1.2
        run: echo "Creating build artifact..."

  deploy_job: # JOB 2 (Depends on JOB 1)
    needs: build_job
    runs-on: ubuntu-latest
    steps:
      - name: Step 1 # STEP 2.1
        run: echo "Deploying build..."

5. What is YAML?

YAML (“YAML Ain’t Markup Language”) is a human-readable data format used for configuration files. GitHub Actions uses YAML to structure workflows. It relies strictly on indentation (spaces, never tabs) and key-value pairs to establish hierarchy.

YAML

# Basic YAML structure rules:
string_key: "value"
number_key: 100
boolean_key: true

list_example:
  - item1
  - item2

nested_object:
  parent:
    child: "value"

6. What are GitHub-Hosted Runners?

GitHub-hosted runners are fully managed virtual machines hosted by GitHub. Every time a job runs, GitHub spins up a fresh, ephemeral VM running your choice of operating system (Ubuntu Linux, Windows, or macOS), runs the job, and destroys the VM afterward.

  • Pros: Zero maintenance, completely clean environment per run, automatically updated software packages.
  • Syntax: runs-on: ubuntu-latest, runs-on: windows-latest, or runs-on: macos-latest.

YAML

jobs:
  check-os:
    runs-on: macos-latest
    steps:
      - run: sw_vers # Checks macOS version

7. What are Self-Hosted Runners?

Self-hosted runners are machines (physical servers, local VMs, cloud instances on AWS/Azure, or Docker containers) that you set up and manage yourself, then register with GitHub.

  • Pros: Access to private internal networks/databases, custom hardware requirements (e.g., GPUs for AI/ML training), faster builds through persistent caching.
  • Cons: You are responsible for OS updates, security, and scaling.
  • Syntax: runs-on: self-hosted.

YAML

jobs:
  internal-deploy:
    runs-on: self-hosted
    steps:
      - run: ./deploy-to-private-datacenter.sh

8. What are GitHub Secrets?

GitHub Secrets are encrypted environment variables stored securely in repository, organization, or environment settings. They allow you to store sensitive credentials (e.g., API keys, database passwords, deployment tokens) without hardcoding them into your source code.

GitHub automatically masks secrets in workflow logs (replacing secret values with ***).

YAML

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Login to Docker Hub
        run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}

9. What is workflow_dispatch?

workflow_dispatch is an event trigger that allows you to run a workflow manually. Once added to on:, a “Run workflow” button appears in the GitHub Actions tab UI. It can also accept custom input parameters (text, drop-downs, booleans).

YAML

name: Manual Release
on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Target deployment environment'
        required: true
        default: 'staging'
        type: choice
        options:
          - staging
          - production

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Deploying to ${{ inputs.environment }}"

10. What is actions/checkout?

actions/checkout is an official, reusable action (actions/checkout@v4) provided by GitHub.

When a job starts, the runner’s workspace is completely empty. actions/checkout clones your repository’s code into the workspace so that subsequent steps (like linter checks, test runs, or build tools) can access and execute against your project files.

YAML

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # Without checkout, npm build will fail because package.json is missing
      - name: Download repository code
        uses: actions/checkout@v4

      - name: Build project
        run: npm run build

GitHub Actions Complete Roadmap (Beginner to Advanced)

Step-by-Step Learning Guide with Practical Examples

This roadmap is designed specifically for QA Engineers, SDET, DevOps Beginners, and Developers who want to master GitHub Actions from scratch.

By the end of this guide, you’ll be able to build production-ready CI/CD pipelines for:

  • Selenium
  • Playwright
  • Cypress
  • API Testing
  • Python
  • Java
  • Node.js
  • Docker
  • AWS Deployment

Learning Path

LevelTopicsOutcome
Level 1GitHub FundamentalsUnderstand Git & GitHub
Level 2GitHub Actions BasicsRun first workflow
Level 3Workflow SyntaxLearn YAML
Level 4Events & TriggersControl execution
Level 5Jobs & StepsMulti-job pipelines
Level 6Variables & SecretsSecure pipelines
Level 7Matrix StrategyMultiple OS/Browsers
Level 8ArtifactsUpload Reports
Level 9CachingFaster execution
Level 10Advanced WorkflowsReusable workflows
Level 11DockerRun inside containers
Level 12DeploymentsAWS/Azure/GCP
Level 13Enterprise ConceptsProduction CI/CD

Module 1 — GitHub Fundamentals

Topics

  • What is Git?
  • What is GitHub?
  • Repository
  • Branch
  • Commit
  • Push
  • Pull
  • Merge
  • Pull Request
  • Fork
  • Clone

Example

git init

git add .

git commit -m "Initial Commit"

git push origin main

Module 2 — What is GitHub Actions?

GitHub Actions is GitHub’s built-in automation platform.

It automatically performs tasks whenever an event occurs.

Examples

  • Run tests
  • Build applications
  • Deploy websites
  • Send email
  • Upload reports
  • Publish packages

Module 3 — GitHub Actions Architecture

Understand these components:

Repository

↓

Workflow

↓

Jobs

↓

Steps

↓

Actions

↓

Runner

Workflow

.github/workflows/main.yml

Job

A workflow may contain multiple jobs.

jobs:
  test:

Step

steps:

Each job contains multiple steps.


Runner

GitHub provides runners.

Examples

ubuntu-latest

windows-latest

macos-latest

Action

Reusable automation.

Example

actions/checkout

Module 4 — First Workflow

name: My First Workflow

on: push

jobs:

  hello:

    runs-on: ubuntu-latest

    steps:

      - name: Print Message
        run: echo "Hello GitHub Actions"

Output

Hello GitHub Actions

Module 5 — YAML Basics

Topics

  • Indentation
  • Keys
  • Values
  • Lists
  • Mapping

Example

name: Demo

on:
  push:

jobs:

  build:

    runs-on: ubuntu-latest

    steps:

      - run: echo Hello

Module 6 — Workflow Triggers

Push

on:
  push:

Pull Request

on:
  pull_request:

Manual Trigger

on:
  workflow_dispatch:

Schedule

on:

  schedule:

    - cron: "0 6 * * *"

Runs every day.


Multiple Events

on:

  push:

  pull_request:

  workflow_dispatch:

Module 7 — Jobs

Single Job

jobs:

  test:

    runs-on: ubuntu-latest

Multiple Jobs

jobs:

  build:

  test:

  deploy:

Dependent Jobs

needs:

  build

Module 8 — Steps

steps:

- uses: actions/checkout@v4

- run: npm install

- run: npm test

Module 9 — GitHub Marketplace Actions

Popular Actions

actions/checkout

actions/setup-node

actions/cache

actions/upload-artifact

actions/download-artifact

actions/setup-python

Module 10 — Setup Programming Languages

NodeJS

- uses: actions/setup-node@v4

  with:

    node-version: 22

Python

- uses: actions/setup-python@v5

  with:

    python-version: 3.13

Java

- uses: actions/setup-java@v4

.NET

actions/setup-dotnet

Module 11 — Running Scripts

steps:

- run: ls

- run: pwd

- run: npm install

- run: npm test

Module 12 — Environment Variables

env:

  URL: https://example.com

Use

echo $URL

Windows

echo %URL%

Module 13 — Secrets

Repository

Settings

↓

Secrets and Variables

↓

Actions

Example

${{ secrets.USERNAME }}

${{ secrets.PASSWORD }}

Module 14 — Expressions

${{ github.actor }}

${{ github.repository }}

${{ github.ref }}

${{ github.sha }}

${{ runner.os }}

Module 15 — Conditional Execution

if:

  github.ref == 'refs/heads/main'

Example

- name: Deploy

  if: github.ref == 'refs/heads/main'

Module 16 — Matrix Strategy

Run on multiple operating systems.

strategy:

  matrix:

    os:

      - ubuntu-latest

      - windows-latest

      - macos-latest

Multiple Node versions

matrix:

  node:

    - 18

    - 20

    - 22

Module 17 — Caching

uses:

actions/cache@v4

Cache

  • npm
  • Maven
  • Gradle
  • Pip

Improves build speed.


Module 18 — Upload Artifacts

Example

- uses:

actions/upload-artifact@v4

with:

  name: TestReport

  path: reports/

Download later.


Module 19 — Download Artifacts

actions/download-artifact

Module 20 — Service Containers

Run databases.

MySQL

PostgreSQL

Redis

MongoDB

Module 21 — Docker

Build Docker Image

docker build .

Push Docker Hub

docker push

Module 22 — Reusable Workflows

workflow_call

Used in enterprise projects.


Module 23 — Composite Actions

Create your own custom action.

action.yml

Module 24 — Inputs

workflow_dispatch:

inputs:

Example

Branch Name

Environment

Browser

Module 25 — Outputs

Pass values between jobs.

outputs:

Module 26 — Self Hosted Runner

Instead of GitHub Runner

Your Server

↓

GitHub Runner Installed

↓

Workflow Executes

Module 27 — Deployments

Deploy to

  • AWS EC2
  • Azure
  • GCP
  • Kubernetes
  • Docker
  • IIS

Module 28 — Notifications

Examples

  • Email
  • Slack
  • Microsoft Teams
  • Discord

Module 29 — Playwright CI

Workflow

Checkout

↓

Setup Node

↓

Install Dependencies

↓

Install Browsers

↓

Execute Tests

↓

Upload HTML Report

Module 30 — Selenium Python CI

Checkout

↓

Setup Python

↓

Install Requirements

↓

Run Pytest

↓

Upload Allure Report

Module 31 — API Automation

Run

  • Postman
  • Newman
  • Rest Assured
  • Pytest API

Module 32 — Advanced Concepts

  • Reusable workflows
  • Composite actions
  • Dependency graph
  • Workflow permissions
  • OIDC authentication
  • Concurrency
  • Environments
  • Required reviewers
  • Branch protection
  • Deployment approvals
  • Environment protection rules

Module 33 — Enterprise CI/CD Pipeline

Developer

↓

Push Code

↓

Build

↓

Static Code Analysis

↓

Unit Test

↓

Integration Test

↓

Automation Test

↓

Package

↓

Docker Build

↓

Security Scan

↓

Deploy Staging

↓

Approval

↓

Deploy Production

↓

Notification

Module 34 — Real-World Project Examples

Project 1

Node.js Application CI

  • Install dependencies
  • Run ESLint
  • Run Unit Tests
  • Upload Coverage

Project 2

Python Project

  • Install Python
  • Install Requirements
  • Execute Pytest
  • Generate HTML Report

Project 3

Playwright Automation

  • Install Node
  • Install Browsers
  • Execute Tests
  • Upload HTML Report
  • Upload Allure Report

Project 4

Java Selenium

  • Setup Java
  • Setup Maven
  • Execute TestNG
  • Publish Report

Project 5

Docker Deployment

  • Build Image
  • Push Docker Hub
  • Deploy EC2

Project 6

AWS Deployment

  • Build
  • SCP Files
  • Restart Service

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.