TypeScript Data Types: The Ultimate Beginner-Friendly Guide
Learn TypeScript data types with simple explanations, interactive examples, visual learning, and interview questions.
If you have already learned TypeScript variables, you are ready for the next important step:
TypeScript data types.
Don’t let the words “data type” scare you.
A data type is simply a way of telling TypeScript what kind of thing a value is.
Think about a child’s toy room.
You may have a box for cars, a box for dolls, a box for balls, a box for books, and a box for crayons.
You don’t randomly throw everything into every box. You know that a car is a car, a book is a book, and a ball is a ball.
TypeScript works in a similar way.
It helps us describe what kind of information a variable contains.
let name: string = "Rahul";
let age: number = 10;
let isStudent: boolean = true;
Here:
name → text
age → number
isStudent → true/false
Simple definition: A data type tells TypeScript what kind of value something is.
What You Will Learn
By the end of this tutorial, you will understand:
What a data type is
Why TypeScript needs data types
string
number
boolean
Arrays
Tuples
Objects
any
unknown
null
undefined
Union types
Literal types
void
never
Type inference
Type narrowing
Real-world examples
Playwright examples
Interview questions
Practice challenges
Meet the TypeScript Type Detective
Before learning individual types, imagine that TypeScript is a little detective.
It looks at a value and asks:
“What are you?”
If it sees:
10
it understands that the value is a number.
If it sees:
"Hello"
it understands that the value is a string.
If it sees:
true
it understands that the value is a boolean.
Every value has a job. The type tells TypeScript what that job is.
Why Do We Need Data Types?
Imagine you have a box.
You put a number inside it:
let age: number = 25;
This tells TypeScript:
“The age variable should contain a number.”
If you later write:
age = "twenty five";
TypeScript can tell you that something is wrong.
Think of TypeScript as a safety guard. It doesn’t stop you from building your application. It simply helps catch many mistakes before they become runtime problems.
TypeScript Data Types at a Glance
Type
What It Stores
Example
string
Text
"Hello"
number
Numbers
100
boolean
True/false
true
Array
List of values
[1,2,3]
Tuple
Fixed structure
["Rahul",10]
Object
Related properties
{name:"Rahul"}
any
Almost anything
any
unknown
Unknown value
unknown
null
Intentional absence
null
undefined
Missing/unassigned
undefined
Union
One of multiple types
string | number
void
No useful return
void
never
Never normally completes
never
1. String: The Type for Text
A string represents text.
let name: string = "Rahul";
Other examples:
let firstName: string = "Deepesh";
let city: string = "Indore";
let message: string = "Welcome to TypeScript";
Easy way to remember: String = words or text.
Interactive Example: String
let name: string = "Rahul";
console.log(name);
Try It: Replace "Rahul" with your own name and predict the output.
2. Number: The Type for Numbers
The number type represents numeric values.
let age: number = 10;
let price: number = 999;
let marks: number = 95;
let temperature: number = 32.5;
Interview tip: TypeScript normally uses number for both integer-like and decimal numeric values.
Interactive Number Challenge
let price: number = 100;
let quantity: number = 3;
let total = price * quantity;
console.log(total);
Answer:300
3. Boolean: The Yes-or-No Type
A boolean has only two values:
true
false
let isLoggedIn: boolean = true;
let testPassed: boolean = false;
Think about a light switch:
ON → true
OFF → false
Interactive Boolean Challenge
const age = 20;
const isAdult = age >= 18;
console.log(isAdult);
Answer:true
4. Arrays: One Box With Many Values
An array stores multiple values.
Imagine five toy cars. Instead of using five separate boxes, you can put them into one larger box.
Think of an object as a student card: name, age, grade, email, phone number, and other related information all belong together.
7. any: The “Anything Goes” Type
Think of any as a box with no label.
let data: any = "Hello";
data = 100;
data = true;
data = {
name: "Rahul"
};
Warning: Using any removes much of TypeScript’s type-safety benefit. Use it only when there is a good reason.
8. unknown: The Mystery Box
Imagine receiving a box but not knowing what’s inside.
You shouldn’t immediately pretend it contains a toy car. First, you check.
let data: unknown = "Hello";
if (typeof data === "string") {
console.log(data.toUpperCase());
}
Remember:unknown means “I don’t know yet. Check me first.”
any vs unknown
Feature
any
unknown
Can hold any value?
Yes
Yes
Type checking
Mostly disabled
Preserved
Requires narrowing?
No
Yes
Safer choice?
Usually no
Usually yes
Easy memory trick: any → “Do whatever you want.” unknown → “Check me before you use me.”
9. null: Intentionally Empty
null represents an intentional absence of a value.
let selectedUser = null;
A common real-world example is:
let selectedUser: User | null = null;
This means the variable can contain a User, or intentionally contain no user.
10. undefined: Nothing Has Been Provided
undefined commonly means that a value hasn’t been assigned or isn’t currently available.
let nickname: string | undefined;
Easy memory trick: null → “I intentionally have no value.” undefined → “A value hasn’t been provided.”
11. Union Types: This OR That
A union type allows a variable to contain one of several known types.
let userId: string | number;
Both are valid:
userId = 101;
userId = "USER101";
But this is not:
userId = true;
Remember: The | symbol means OR.
Interactive Union Challenge
Which assignments are valid?
let id: string | number;
id = 100;
id = "ABC100";
id = true;
Answer: 1 and 2 are valid. 3 is invalid because boolean isn’t part of the union.
12. Literal Types: Only These Exact Values
A literal type allows only specific values.
let browser: "Chrome" | "Firefox" | "Safari";
These are valid:
browser = "Chrome";
browser = "Firefox";
But:
browser = "Edge";
would not match the declared type.
Real-world use: Literal types are excellent when an application supports a small, known list of values.
13. void: A Function That Returns Nothing Useful
You’ll usually see void as a function return type.
function sayHello(): void {
console.log("Hello");
}
The function performs an action but doesn’t return a useful value.
14. never: A Function That Never Normally Finishes
never is more advanced.
For example, a function that always throws an error never successfully returns:
function throwError(message: string): never {
throw new Error(message);
}
Easy memory trick:never means normal completion never happens.
Type Inference: TypeScript Is a Detective
You don’t always have to explicitly specify a type.
const name = "Rahul";
const age = 10;
const passed = true;
TypeScript can infer:
name → string
age → number
passed → boolean
This is called type inference.
Type Narrowing: Let TypeScript Find the Right Type
Sometimes a value can have multiple types.
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
if (typeof value === "number") {
console.log(value.toFixed(2));
}
}
At first TypeScript thinks:
Could be string OR number.
After the typeof check, TypeScript can narrow the value to the appropriate type.
TypeScript Data Types in Playwright
If you are learning TypeScript for Playwright automation, these concepts become very practical.
These values can then be used by your Playwright tests.
Real-World API Example
Imagine an API returns a user ID as either a number or a string.
let userId: string | number;
This is better than using any because you’ve clearly documented the two allowed possibilities.
Common Beginner Mistakes
Mistake 1: Using any Everywhere
Using any simply because TypeScript reports an error defeats much of the purpose of TypeScript.
Mistake 2: Confusing Arrays and Tuples
string[]
means an array of strings.
[string, number]
means a tuple with a string followed by a number.
Mistake 3: Using String Instead of string
Prefer the lowercase primitive type:
let name: string;
rather than using the boxed-object form:
let name: String;
Must-Know TypeScript Data Type Interview Questions
Interview Tip: Don’t just memorize the answer. Understand the simple idea behind it. Interviewers often ask follow-up questions.
1. What are data types in TypeScript?
Answer: Data types describe what kind of value a variable can contain. Examples include string, number, boolean, arrays, tuples, objects, unions, and other TypeScript types.
2. What are the common primitive types?
Answer: Common JavaScript primitive types include string, number, boolean, bigint, symbol, null, and undefined.
3. What is the difference between any and unknown?
Answer:any largely disables type checking for the value. unknown can hold any value, but TypeScript requires you to narrow or check the value before performing type-specific operations.
4. What is a union type?
Answer: A union type allows a value to be one of several possible types.
let id: string | number;
5. What is the difference between an array and a tuple?
Answer: An array generally represents a collection of values, while a tuple describes a fixed structure where each position can have a specific type.
6. What is type inference?
Answer: Type inference is TypeScript automatically determining the type of a value based on its context.
const age = 25;
TypeScript infers age as a number.
7. What is never?
Answer:never represents a value that never occurs. It is commonly used for functions that never successfully complete, such as functions that always throw an error.
8. What is void?
Answer:void is commonly used for functions that do not return a useful value.
9. What is the difference between null and undefined?
Answer: A simple explanation is that null usually represents an intentional absence of a value, while undefined commonly indicates that a value has not been assigned or provided.
10. Does TypeScript have separate integer and floating-point types?
Answer: No. Ordinary numeric values use the number type.
Scenario-Based Interview Questions
Scenario 1: API Returns String or Number
An API sometimes returns:
101
and sometimes:
"101"
Answer:
let userId: string | number;
Scenario 2: Completely Unknown API Response
Would you use any or unknown?
Answer: Prefer unknown when the data is genuinely unknown and you can validate or narrow it before using it.
Scenario 3: Browser Configuration
Your automation framework supports only:
chromium
firefox
webkit
A literal union is a good choice:
type BrowserName =
| "chromium"
| "firefox"
| "webkit";
This prevents accidental values outside the supported list.
Final Interactive Type Detective Challenge
Don’t look at the answer immediately. Try to identify the type of every variable.
Don’t stop after reading. Try these exercises yourself.
Practice 1: Student Information
Create variables for:
Name
Age
Grade
Whether the student passed
Practice 2: Shopping Cart
Create variables for product name, price, quantity, and stock status. Calculate the total price.
Practice 3: Employee
Create an employee object containing ID, name, department, experience, and active status.
Practice 4: Browser Configuration
Create a literal union containing chromium, firefox, and webkit.
Practice 5: User ID
Create a variable that accepts a number or string but rejects a boolean.
TypeScript Data Types Cheat Sheet
Type
Easy Meaning
Example
string
Words/text
"Hello"
number
Numbers
100
boolean
Yes/no
true
Array
List
[1,2,3]
Tuple
Fixed positions
["A",10]
Object
Related information
{name:"A"}
any
Anything
any
unknown
Mystery value
unknown
null
Intentionally empty
null
undefined
Not provided
undefined
Union
This OR that
string | number
void
No useful return
void
never
Never normally completes
never
Final Takeaway
If you are a beginner, don’t try to memorize every TypeScript type today.
Instead, remember the idea behind each one.
String → text
Number → numbers
Boolean → yes or no
Array → collection
Tuple → fixed structure
Object → related information
any → “Don’t check me.”
unknown → “Check me first.”
Union → “This OR that.”
void → “I don’t return a useful value.”
never → “Normal completion never happens.”
Don’t just read TypeScript. Practice it.
Write code. Break it. Read the error. Fix it. Repeat.
Frequently Asked Questions
What are the most important TypeScript data types for beginners?
Start with string, number, boolean, array, and object. Then learn tuples, unions, any, unknown, null, and undefined. After that, move into literal types, void, never, generics, and utility types.
Is any bad in TypeScript?
any is not forbidden, but excessive use removes much of TypeScript’s type-safety benefit. When a value is genuinely unknown, unknown is often a safer choice.
What is the difference between an array and a tuple?
An array generally represents a collection of values, while a tuple represents a fixed structure where each position can have a specific type.
What is a union type?
A union type allows a value to be one of several possible types. For example, string | number means the value can be a string or a number.
Why is unknown safer than any?
With unknown, TypeScript requires you to check or narrow the value before performing operations that depend on a particular type. With any, those checks are largely bypassed.
Learning Tip: Save this article and revisit the cheat sheet whenever you forget a TypeScript data type. The fastest way to master these concepts is to write small programs and predict their output before running them.
It can also understand what kind of value the variable contains.
For example:
let age: number = 10;
Now TypeScript knows:
“The age variable should contain a number.”
This extra information is one of the reasons TypeScript is so useful for large applications, automation frameworks, and modern web development.
In this tutorial, we will learn TypeScript variables from the absolute beginning and gradually move toward real-world examples, common mistakes, interview questions, and Playwright automation examples.
What You Will Learn
By the end of this article, you will understand:
What a variable is
Why variables are needed
let
const
var
Variable naming rules
Type annotations
Type inference
Reassigning variables
Constants
Scope
Block scope
Global scope
Variables with objects
Variables with arrays
Variables in functions
Variables in TypeScript automation
Common mistakes
Interview questions and answers
Practice questions
Let’s start from the very beginning.
What Is a Variable?
A variable is a named container for storing a value.
That’s it.
You don’t need a complicated definition.
Think about your school bag.
Your bag may contain:
Books
Pencils
Eraser
Lunch Box
Water Bottle
Similarly, a program needs places to store information.
For example:
let studentName = "Rahul";
let studentAge = 10;
let studentMarks = 95;
TypeScript Variable Interview Questions and Answers
Now let’s move into the part that many learners really need.
Interview preparation.
Understanding a topic is one thing.
Explaining it confidently during an interview is another.
Let’s practice.
Interview Question 1: What is a variable in TypeScript?
Answer:
A variable is a named container used to store a value.
For example:
let age = 25;
Here, age is the variable and 25 is its value.
TypeScript can also associate a type with the variable:
let age: number = 25;
Interview Question 2: What are the different ways to declare variables in TypeScript?
Answer:
TypeScript supports:
var
let
const
However, modern TypeScript development generally prefers let and const.
let is used when a variable may be reassigned, while const is used when the variable should not be reassigned.
Interview Question 3: What is the difference between let and const?
Answer:
The main difference is reassignment.
Example:
let count = 10;
count = 20;
This is valid.
But:
const count = 10;
count = 20;
This causes an error because const variables cannot be reassigned.
Both let and const are block scoped.
Interview Question 4: What is the difference between var, let, and const?
Answer:
var is function scoped, while let and const are block scoped.
let allows reassignment.
const does not allow reassignment after initialization.
Example:
let score = 10;
score = 20;
Valid.
const score = 10;
score = 20;
Invalid.
For modern TypeScript development, let and const are generally preferred over var.
Interview Question 5: What is type inference?
Answer:
Type inference is TypeScript’s ability to automatically determine the type of a variable from its value.
Example:
let name = "Rahul";
TypeScript automatically infers:
name → string
Similarly:
let age = 25;
is inferred as:
age → number
This means explicit type annotations are not always necessary.
Interview Question 6: What is a type annotation?
Answer:
A type annotation explicitly specifies the expected type of a variable.
Example:
let age: number = 25;
Here, : number is the type annotation.
Another example:
let name: string = "Rahul";
Interview Question 7: Can a const object be modified?
Answer:
Yes, its properties can generally be modified.
For example:
const user = {
name: "Rahul"
};
user.name = "Amit";
This is allowed.
However, reassigning the entire object is not allowed:
user = {
name: "Amit"
};
const prevents reassignment of the variable binding; it does not automatically make the object’s contents immutable.
Interview Question 8: What is variable scope?
Answer:
Scope defines where a variable can be accessed.
For example:
function test() {
const name = "Rahul";
}
The name variable is available inside the function but not outside it.
Similarly, let and const are block scoped.
Interview Question 9: Why should we prefer const over let when possible?
Answer:
Because const communicates that the variable will not be reassigned.
For example:
const browser = "Chrome";
This tells other developers that browser is not expected to point to another value.
It also reduces accidental reassignment.
Interview Question 10: Why is var generally avoided in modern TypeScript?
Answer:
var has function-level scoping and behavior that can make code harder to reason about.
let and const provide block scope and clearer rules around reassignment.
Therefore, modern TypeScript code generally prefers let and const.
Scenario-Based Interview Questions
Now let’s make the questions more realistic.
These are the kinds of questions that can separate a beginner from someone who understands the concept.
Scenario 1: Which declaration would you use?
You have:
const baseUrl = "https://example.com";
The URL never changes.
Would you use let or const?
Answer:
Use:
const baseUrl = "https://example.com";
because the variable does not need reassignment.
Scenario 2: Retry Counter
You have:
let retryCount = 0;
Every time an API request fails, you increase the counter.
Would you use let or const?
Answer:
Use:
let retryCount = 0;
retryCount++;
because the value changes.
Scenario 3: Playwright Browser
You have:
const browserName = "chromium";
The browser name does not change during the test.
Which declaration should you use?
Answer:
const.
const browserName = "chromium";
Quick Interview Revision
Before an interview, remember these five points:
1. Variable = named storage location
2. let = can be reassigned
3. const = cannot be reassigned
4. var = older function-scoped declaration
5. Type inference = TypeScript automatically determines the type
If you understand these five points, you already have a strong foundation.
Practice Programs
Don’t stop after reading.
Try writing these programs yourself.
Program 1
Create variables for:
Name
Age
City
IsStudent
Use appropriate types.
Program 2
Create a variable called score.
Start it with:
50
Then change it to:
100
Use the correct variable declaration.
Program 3
Create an array containing five programming languages.
The program produces a TypeScript error because score is declared using const and cannot be reassigned.
TypeScript Variables Cheat Sheet
Keyword/Concept
Meaning
let
Variable that can be reassigned
const
Variable that cannot be reassigned
var
Older function-scoped declaration
Type annotation
Explicitly defines a type
Type inference
TypeScript automatically determines the type
Scope
Where a variable can be accessed
Block scope
Scope inside {}
string
Text
number
Numeric value
boolean
true or false
Final Takeaway
Variables are one of the smallest concepts in TypeScript, but they are also one of the most important.
Every time your application remembers something, there is a good chance a variable is involved.
A username?
Variable.
A password?
Variable.
A product price?
Variable.
A Playwright URL?
Variable.
A test timeout?
Variable.
A retry counter?
Variable.
Once you understand variables, you have started learning the language’s basic building blocks.
The most important rules to remember are simple:
const name = "Rahul";
Use const when you don’t need reassignment.
let score = 10;
score = 20;
Use let when the value needs to change.
And:
let age: number = 25;
Use a type annotation when you want to explicitly communicate the expected type.
Finally, remember this:
Don’t learn TypeScript by memorizing syntax. Learn it by understanding why the syntax exists.
When you understand that a variable is simply a named place for storing information, let, const, types, scope, and type inference become much easier.
And this is only the beginning.
The next step is to understand TypeScript data types, where we will explore strings, numbers, booleans, arrays, tuples, objects, unions, any, unknown, null, undefined, and practical examples.
Frequently Asked Questions
1. What is a variable in TypeScript?
A variable is a named container used to store a value.
let age = 25;
Here, age stores the value 25.
2. Should I use let or const?
Use const by default when you don’t need to reassign the variable.
Use let when the value needs to change.
const name = "Rahul";
let score = 10;
score = 20;
3. Is var still supported in TypeScript?
Yes, TypeScript supports var because it is part of JavaScript.
However, modern TypeScript code generally prefers let and const because they provide clearer block-scoping behavior.
4. What is type inference in TypeScript?
Type inference is when TypeScript automatically determines the type of a value.
const name = "Rahul";
TypeScript understands that name is a string without you explicitly writing:
const name: string = "Rahul";
5. Can a const object be changed?
The object variable itself cannot be reassigned:
const user = {
name: "Rahul"
};
But its properties can generally be changed:
user.name = "Amit";
If you need properties that cannot be reassigned, TypeScript provides features such as readonly.
AI is rapidly becoming an important part of modern QA automation. Senior QA engineers and SDETs are increasingly expected to understand not only traditional automation frameworks such as Playwright and Selenium, but also AI-assisted testing, AI agents, MCP, intelligent test generation, debugging, and self-healing automation.
This guide contains practical AI + QA Automation interview questions and answers designed for Senior QA Engineers, SDETs, QA Automation Architects, and professionals working with Playwright and AI-assisted automation.
Interview Tip: AI should be presented as an engineering accelerator, not a replacement for QA engineering judgment. The QA engineer remains responsible for business validation, test coverage, risk assessment, and final automation quality.
1. How Are You Using AI in Your Day-to-Day QA Automation Work?
Interview Answer
I use AI as an engineering assistant across the complete QA lifecycle rather than only for generating automation scripts. I use it for requirement analysis, test-case generation, identifying edge cases, creating Playwright scripts, locator suggestions, debugging failures, improving existing automation, generating test data, code reviews, and documentation.
In my Playwright automation work, I also use AI with Playwright MCP to allow an AI agent to interact with the application, explore the UI, understand the actual behavior, identify locators, and then generate or refine automation code.
I do not blindly trust AI-generated output. I treat AI as an accelerator while the QA engineer remains responsible for validating business logic, test coverage, framework standards, and final automation quality.
Key Points
Requirement analysis
Test design and edge cases
Playwright automation
Locator identification
Failure analysis and debugging
Refactoring and code review
Test data generation
Documentation
2. How Do You Use AI to Generate Test Cases From a Requirement?
Interview Answer
I provide the requirement, acceptance criteria, business rules, and relevant application context. I ask AI to analyze the requirement and generate positive, negative, boundary, accessibility, integration, error-handling, and regression scenarios.
I then review the generated cases against the actual business requirements because AI can produce technically valid but business-incorrect scenarios. After validation, I categorize the cases and decide which scenarios should be automated.
Example
For a subscription purchase workflow, AI can help identify scenarios such as:
Valid payment
Invalid card
Expired card
Payment failure
Session timeout
Address boundary conditions
Keyboard navigation
Screen-reader behavior
Security of sensitive data
A useful practice is to ask AI to clearly distinguish between explicit requirements and assumptions.
3. How Do You Use AI With Playwright to Generate Automation Scripts?
Interview Answer
I use a structured workflow instead of simply asking AI to generate a Playwright test.
First, I provide the requirement and scenario. Then I allow the AI to understand the application and existing framework. Where appropriate, I use Playwright MCP to explore the application and identify actual UI elements and behavior.
AI can then generate the Playwright test using existing page objects, fixtures, utilities, assertions, and coding conventions.
I execute the test, analyze failures, refine the implementation, and perform a human review before committing the code.
AI-Assisted Playwright Workflow
Requirement
↓
AI Analysis
↓
Test Scenario
↓
Browser Exploration
↓
Locator Discovery
↓
Code Generation
↓
Test Execution
↓
Failure Analysis
↓
Refinement
↓
Human Review
What Should You Validate?
Fixtures
Page objects
Test data
Assertions
Cleanup
Stable locators
Framework conventions
4. What Is Playwright MCP and How Does It Help QA Automation?
Interview Answer
Playwright MCP is an MCP-based integration that allows an AI agent to interact with a browser through Playwright capabilities.
Instead of relying only on static source code, the agent can explore the application, inspect the UI, perform browser actions, observe results, and use that context to generate or refine Playwright automation.
Traditional AI Automation
Requirement + Code/Context
↓
Generated Script
MCP-Assisted Automation
Requirement
↓
AI Agent
↓
Browser Exploration
↓
Inspect Elements
↓
Perform Actions
↓
Observe Results
↓
Generate/Refine Test
Playwright MCP improves application interaction, but it does not automatically provide business understanding. Requirements and business rules remain essential.
5. What Are Playwright Planner, Generator and Healer?
Interview Answer
These can be understood as three stages of an AI-assisted automation workflow.
Planner
The Planner determines what should be tested. It analyzes requirements, acceptance criteria, and user journeys to create a test plan.
Generator
The Generator determines how the test should be automated. It converts the test plan into Playwright tests, locators, assertions, and supporting code.
Healer
The Healer analyzes why automation failed and proposes a repair. For example, it may identify changed locators or synchronization issues.
Important: AI-based healing should be treated as a proposed fix that requires validation. Automatic healing can otherwise hide a real application regression.
6. How Do You Use AI When a Playwright Test Fails?
Interview Answer
I use AI as a debugging assistant. I provide the test code, failure message, stack trace, screenshot, trace information, and relevant application behavior.
AI can help classify the failure as an application defect, locator problem, synchronization issue, test-data issue, environment problem, or automation defect.
I reproduce and validate the proposed fix before accepting it.
Information I Analyze
Stack trace
Playwright trace
Screenshot
DOM snapshot
Console errors
Network failures
Test code
The objective is root-cause analysis, not merely producing a passing test.
Avoid using arbitrary hard waits such as waitForTimeout() simply to make a test green.
7. Can AI Completely Automate Testing? What Are Its Limitations?
Interview Answer
AI can automate a significant portion of repetitive QA activities, but completely autonomous testing is risky.
Testing requires business understanding, risk assessment, exploratory thinking, and judgment. AI can misunderstand requirements, hallucinate APIs or locators, generate redundant tests, create incorrect assertions, or incorrectly heal tests.
Major Limitations of AI in Testing
Business-context limitations
Hallucinations and incorrect assumptions
False confidence from realistic-looking tests
Incorrect assertions
Maintenance and self-healing risks
Exploratory and usability testing limitations
Security and privacy concerns
Dependence on the quality of provided context
8. How Do You Validate AI-Generated Test Cases or Automation Code?
Interview Answer
I use a human-in-the-loop validation process.
I validate the AI-generated output against requirements, acceptance criteria, business rules, framework standards, and existing automation patterns.
Then I execute the test and verify that the assertions actually prove the intended behavior.
Validation Checklist
Requirement coverage
Positive scenarios
Negative scenarios
Boundary scenarios
Locator stability
Meaningful assertions
Synchronization
Framework compatibility
Test isolation
Data management
Cleanup
Security
CI execution
Flakiness
A particularly important validation is to run the test repeatedly and verify that the test actually fails when the intended application behavior is broken.
9. Which AI Tools Have You Used in QA Automation?
Interview Answer
I have worked with AI coding assistants such as GitHub Copilot and Claude-based coding workflows, and I have explored AI-assisted browser automation using Playwright MCP.
I use different tools for different parts of the QA lifecycle rather than expecting one tool to solve everything.
AI Tool
Typical Usage
GitHub Copilot
Code generation, refactoring and test generation
Claude Code
Repository-level reasoning, codebase analysis and implementation assistance
Playwright MCP
Browser exploration and AI-assisted Playwright automation
ChatGPT
Requirement analysis, test design, debugging and documentation
AI Agents
Multi-step exploration and automation workflows
Interview Tip: Only mention AI tools that you can genuinely describe and demonstrate from your own experience.
10. Give Me a Real Project Example Where AI Improved Your QA Automation Process
Interview Answer
In a web QA automation project, I worked on subscription and checkout-related functionality involving user journeys such as subscription selection, checkout, payment, cancellation, and switching plans.
I used AI-assisted automation to accelerate test design and Playwright implementation. I provided requirements and acceptance criteria to identify important journeys and edge cases, used browser exploration to understand the actual UI and locators, and used AI to generate an initial Playwright implementation following the existing framework.
After execution, I used AI to analyze failures and distinguish application issues from automation, synchronization, test-data, or environment problems.
The improvement was not simply generating code faster. AI reduced repetitive analysis, scaffolding, locator discovery, debugging, and documentation while I remained responsible for business validation and final test quality.
Important Interview Tip
Do not invent productivity percentages. If asked for metrics, provide measured figures only.
Useful metrics include:
Automation development time
Maintenance effort
Execution stability
Defect coverage
11. How Would You Integrate GitHub Copilot or Claude Code With Your VS Code Project?
Interview Answer
I would not expect an AI coding assistant to understand the framework simply because it is installed in VS Code.
I would provide structured repository context and engineering instructions. I would make framework conventions explicit through documentation, architecture guidance, coding standards, test examples, and the supported repository instruction mechanism for the chosen AI tool.
I would also ask the agent to inspect the repository before generating code.
Repository Areas to Analyze
package.json
playwright.config.ts
Tests
Page objects
Fixtures
Utilities
Configuration
Test data
Framework Information to Document
Automation architecture
Page-object guidelines
Locator strategy
Authentication approach
Test-data strategy
Coding standards
After implementation, validate the generated code using linting, TypeScript compilation, Playwright execution, code review, and CI.
12. If Copilot Generates an Automation Script, What Would You Validate?
Interview Answer
I would validate the requirement coverage, test objective, locator quality, assertions, synchronization, framework compatibility, test isolation, test data, cleanup, error handling, maintainability, security, CI compatibility, and flakiness.
Validation Checklist
Requirement and business behavior
Stable locators
Meaningful assertions
No unnecessary hard waits
Reuse of fixtures, page objects and utilities
Independent test execution
Reliable test data and cleanup
No secrets or sensitive data
Repeated execution
CI execution
Failure behavior
Maintainability
13. How Would You Leverage Copilot to Understand Your Framework and Codebase?
Interview Answer
I would use Copilot as a codebase analysis assistant before using it as a code generator.
I would ask it to map the architecture, test execution flow, authentication mechanism, fixtures, page objects, utilities, configuration, and existing patterns.
Once it understands those relationships, I would ask it to identify the best existing components to reuse before creating new code.
Useful Questions to Ask the AI Assistant
Explain the automation architecture.
Trace how a Playwright test moves from the spec through fixtures, configuration and browser initialization.
Identify the authentication fixture for a new authenticated test.
Find page objects and their public methods.
Identify the recommended test-data approach.
Find similar existing tests and explain their common pattern.
Identify impacted tests before modifying a shared page object.
Detect duplicate utilities before creating new ones.
Advanced: AI-Powered QA Automation Architecture
A senior-level AI-powered QA automation architecture can be represented as follows:
Requirement
↓
AI Test Planner
↓
Test Scenarios
↓
Browser Exploration / Playwright MCP
↓
AI Test Generator
↓
Playwright Tests
↓
Execution
↓
┌───────────────┐
│ │
PASS FAIL
│ │
↓ ↓
CI/CD AI Debugger / Healer
↓
Proposed Fix
↓
Human Review
↓
CI/CD
The objective is intelligent, context-aware and maintainable automation rather than blindly autonomous testing.
Key Interview Language for AI + QA Roles
Human-in-the-loop
Requirement-to-test automation
Context-aware code generation
Repository-level understanding
Browser exploration
Root-cause analysis
Self-healing / AI-assisted healing
Test coverage optimization
Framework-aware automation
AI as an accelerator, not a replacement
60-Second AI + QA Interview Introduction
I have been using AI as an engineering accelerator across different stages of the QA automation lifecycle, rather than using it only for code generation.
For requirement analysis, I use AI to identify test scenarios, edge cases, negative scenarios and potential risks. With Playwright automation, I use AI-assisted workflows and Playwright MCP to explore the application, understand the UI, identify locators and generate automation code based on actual application behavior.
I also use AI for debugging Playwright failures by analyzing stack traces, screenshots, traces, locators and application behavior.
For repository-level development, I use AI coding assistants such as GitHub Copilot or Claude-based workflows to understand existing framework patterns, fixtures, page objects and utilities before generating new automation.
The key principle I follow is human-in-the-loop automation: I validate requirements, business logic, test coverage, locator stability, assertions, framework compatibility and execution results before committing automation.
Strong Closing Statement for the Interview
My approach is to use AI to reduce repetitive engineering effort while increasing the depth and speed of testing.
I use AI for requirement analysis, test design, automation generation, browser exploration, debugging, code review and documentation.
With Playwright and MCP-based workflows, I can move toward a more agentic approach where the system can understand a requirement, explore the application, create a test plan, generate automation and analyze failures.
However, I don’t consider AI-generated output automatically trustworthy. The QA engineer still owns business validation, risk assessment, test coverage and the final quality of the automation.
The goal is intelligent, context-aware and maintainable automation with humans making the important quality decisions.
Final Takeaway
For senior QA and SDET interviews, the important message is not simply that you know how to use AI to generate test scripts.
You should be able to explain how AI fits into the complete QA lifecycle:
Understand the requirement.
Generate and analyze test scenarios.
Explore the application.
Identify reliable locators.
Generate framework-compatible automation.
Execute the tests.
Analyze failures.
Propose fixes.
Validate the fixes.
Maintain high-quality automation through CI/CD.
The strongest approach is to combine AI capabilities with QA engineering expertise. AI can accelerate repetitive engineering activities, but human judgment remains essential for business validation, risk assessment, test coverage, and quality.
Below is a full set of 100 interview questions with answers, organized by topic. Each answer is written to be interview-ready.
Section 1: Fundamentals & Architecture (Q1–Q15)
Q1. What is Playwright? Playwright is an open-source end-to-end testing framework by Microsoft that drives Chromium, Firefox, and WebKit through a single API. It supports auto-waiting, network interception, multiple browser contexts, and cross-language bindings including TypeScript.
Q2. Why use TypeScript with Playwright? TypeScript gives static typing for locators, fixtures, and page objects, catching errors at compile time. It also provides IDE autocompletion for the Playwright API and makes refactoring safer in large suites.
Q3. What are the core components of Playwright? Browser, BrowserContext, Page, Locator, Frame, Request/Response, and the Test Runner (@playwright/test).
Q4. Difference between Playwright and Selenium? Playwright communicates with browsers via the DevTools protocol and its own patched builds, giving auto-waiting, network interception, and multi-context isolation out of the box. Selenium relies on WebDriver and generally requires explicit waits and separate drivers per browser.
Q5. What is auto-waiting? Before performing an action, Playwright waits for the element to be attached, visible, stable, enabled, and to receive events. This eliminates most manual sleep calls.
Q6. What browsers does Playwright support? Chromium (Chrome/Edge), Firefox, and WebKit (Safari engine).
Q7. What is a BrowserContext? An isolated session inside a browser with its own cookies, localStorage, and cache. It behaves like an incognito window and is the unit of test isolation.
Q8. Can one browser have multiple contexts? Yes. One browser instance can host many contexts, each fully isolated, enabling parallel tests and multi-user scenarios.
Q9. What is the difference between page and context? A context is the session; a page is a single tab within that session. Multiple pages can exist in one context and share cookies.
Q10. What is a Locator? A Locator is a lazy reference to an element that is re-resolved on every action, so it never goes stale after a re-render.
Q11. Difference between Locator and ElementHandle? Locators are auto-waiting, re-resolved, and preferred. ElementHandles are static references that can become detached and are considered legacy.
Q12. What test runners can be used with Playwright? The official @playwright/test runner, plus Jest, Mocha, Vitest, or Cucumber if configured manually.
Q13. What is playwright.config.ts? The central configuration file defining test directory, timeouts, retries, reporters, projects, and global setup/teardown.
Q14. How do you run a single test file? npx playwright test tests/login.spec.ts
Q15. How do you run tests in headed mode? npx playwright test --headed
Section 2: Locators & Selectors (Q16–Q30)
Q16. Why prefer getByRole() over CSS selectors? It targets elements by ARIA role and accessible name, matching how users perceive the page. It survives DOM and class-name refactoring.
Q17. List Playwright’s built-in locators. getByRole, getByText, getByLabel, getByPlaceholder, getByAltText, getByTitle, getByTestId, and locator() for CSS/XPath.
Q18. How do you locate by test ID? page.getByTestId('submit-btn') — the attribute is configurable via testIdAttribute in config.
Q19. Difference between getByText and getByRole? getByText matches visible text; getByRole matches semantic role plus optional name. Role-based is more robust.
Q20. How do you chain locators? page.getByRole('row').filter({ hasText: 'Alice' }).getByRole('button', { name: 'Edit' })
Q21. What does .filter({ hasText }) do? Narrows a locator to elements containing the given text.
Q22. How do you select the nth element? locator.nth(0) for the first, locator.first(), locator.last().
Q23. What is locator.all()? Returns an array of all matching elements resolved at call time — useful for iteration but not for auto-waiting.
Q24. How do you handle strict mode violations? Make the locator more specific, or use .first(), .nth(), or .filter().
Q25. What is strict mode? Playwright throws if a locator resolves to more than one element during an action, preventing ambiguous interactions.
Q26. Can you use XPath? Yes: page.locator('xpath=//button[@id="save"]'), though it’s discouraged.
Q27. How do you locate inside an iframe? page.frameLocator('#frame').getByRole('button')
Q28. How do you locate inside shadow DOM? Playwright pierces open shadow DOM automatically with CSS locators.
Q29. What is locator.waitFor()? Waits for the locator to reach a state: attached, detached, visible, or hidden.
Q30. How do you count matching elements? await locator.count()
Section 3: Actions & Assertions (Q31–Q45)
Q31. How do you click an element? await page.getByRole('button', { name: 'Submit' }).click()
Q32. Difference between fill() and type()? fill() sets the value directly and is fast; type() (deprecated in favor of pressSequentially) simulates keystrokes.
Q33. How do you handle a dropdown? await page.getByLabel('Country').selectOption('IN')
Q34. How do you check a checkbox? await page.getByLabel('Terms').check()
Q35. How do you hover? await page.getByText('Menu').hover()
Q36. How do you drag and drop? await page.locator('#src').dragTo(page.locator('#dst'))
Q37. How do you upload a file? await page.getByLabel('Upload').setInputFiles('path/to/file.pdf')
Q38. How do you handle a native dialog?
typescript
page.on('dialog', async d => { await d.accept(); });
Q39. Difference between expect(locator).toBeVisible() and locator.isVisible()? expect retries until timeout; isVisible() returns immediately and does not wait.
Q40. What is web-first assertion? An assertion that retries automatically, e.g. await expect(locator).toHaveText('Done').
Q41. How do you assert a URL? await expect(page).toHaveURL(/dashboard/)
Q42. How do you assert a title? await expect(page).toHaveTitle('Home')
Q43. How do you assert an attribute? await expect(locator).toHaveAttribute('disabled', '')
Q44. How do you assert element count? await expect(locator).toHaveCount(3)
Q45. What is expect.soft()? A soft assertion that records failure but continues the test instead of aborting.
Section 4: Waits & Timing (Q46–Q55)
Q46. Why is page.waitForTimeout() discouraged? It introduces fixed delays, making tests slow and flaky. Prefer web-first assertions or waitFor.
Q47. How do you wait for a network response? await page.waitForResponse(r => r.url().includes('/api/users') && r.status() === 200)
Q48. How do you wait for navigation? await page.waitForURL('**/dashboard')
Q49. How do you wait for load state? await page.waitForLoadState('networkidle')
Q50. What are the load states? load, domcontentloaded, and networkidle.
Q51. What is a floating promise? An async call without await, causing the next line to run before the action completes — the top cause of flakiness.
Q57. How do you abort a request? await page.route('**/*.png', route => route.abort())
Q58. How do you modify a response? Fetch the original with route.fetch(), modify the body, then route.fulfill().
Q59. Difference between page.request and request fixture? page.request shares the page’s cookie jar (authenticated as the user); the request fixture has its own isolated cookie jar.
Q60. How do you mock an API response? await page.route('**/api/login', r => r.fulfill({ json: { token: 'abc' } }))
Q61. How do you wait for multiple responses? await Promise.all([page.waitForResponse(...), page.click(...)])
Q62. How do you test a REST API directly? const res = await request.get('/users'); expect(res.ok()).toBeTruthy();
Q63. Can Playwright test GraphQL? Yes, via request.post() with a JSON query body, or by intercepting the endpoint.
Q64. How do you record HAR? await page.routeFromHAR('trace.har', { update: true }) or via config recordHar.
Q65. How do you replay a HAR? await page.routeFromHAR('trace.har')
Section 6: Authentication & State (Q66–Q72)
Q66. How do you reuse authentication across tests? Save storageState once during setup, then reference it via test.use({ storageState: 'auth.json' }).
Q67. How do you save storage state? await context.storageState({ path: 'auth.json' })
Q68. What does storageState contain? Cookies and localStorage origins.
Q69. How do you run a setup project? Define a project named setup in config and add dependencies: ['setup'] to test projects.
Q70. How do you log in via API instead of UI? Use the request fixture to POST credentials, then save the resulting storage state.
Q71. How do you test multiple users in parallel? Create separate contexts with different storage states.
Q72. How do you clear cookies mid-test? await context.clearCookies()
Section 7: Fixtures & Test Structure (Q73–Q82)
Q73. What is a fixture? A reusable setup/teardown unit injected into tests, replacing beforeEach boilerplate.
Q85. Why should navigation methods return the next page object? It enforces flow correctness at compile time and chains steps fluently.
Q86. How do you share page objects across tests? Expose them as fixtures in a custom test.extend.
Q87. What is as const used for in Playwright tests? Freezing literal types, e.g. role arrays or config maps, so TypeScript narrows them correctly.
Q88. How do you type a locator array? const rows: Locator[] = await page.getByRole('row').all();
Q89. How do you type a network response body? const data = await res.json() as UserDto; or use a Zod schema for runtime validation.
Q90. Should page objects contain assertions? Prefer keeping assertions in tests; page objects should expose state and actions. Some teams allow lightweight assertions in page objects for reuse.
Section 9: Debugging & Reporting (Q91–Q95)
Q91. How do you debug a failing test? Run with --debug (Playwright Inspector), --headed, or use page.pause().
Q92. What is the Trace Viewer? A tool that replays a test with DOM snapshots, network, console, and source — enabled via trace: 'on-first-retry'.
Q93. How do you enable tracing? In config: use: { trace: 'on' } or per context: context.tracing.start({ screenshots: true, snapshots: true }).
Q94. How do you view a trace? npx playwright show-trace trace.zip
Q95. What reporters ship with Playwright? list, line, dot, html, json, junit, and blob.
Section 10: CI/CD & Best Practices (Q96–Q100)
Q96. How do you run Playwright in CI? Install browsers with npx playwright install --with-deps, then run npx playwright test. Use the official Docker image or GitHub Action.
Q97. How do you parallelize tests? Playwright parallelizes by file by default. Use fullyParallel: true for test-level parallelism and configure workers.
Q98. How do you handle retries? Set retries: 2 in config or --retries=2. Combine with trace: 'on-first-retry' for diagnosis.
Q99. How do you shard tests across CI machines? npx playwright test --shard=1/4
Q100. What are the top best practices for Playwright + TypeScript?
100 Advanced Playwright + TypeScript Interview Questions and Answers
Below is a full set of 100 advanced interview questions with answers, assuming you have already mastered the fundamentals covered in the previous set. Each answer is written to be interview-ready and focuses on production-grade patterns, edge cases, and architectural decisions.
Q1. How does Playwright’s auto-waiting actually work under the hood? Playwright injects an actionability check before every interaction. The element must pass five conditions: attached to DOM, visible, stable (not animating), enabled, and receiving events (not obscured). Each check retries until timeout. This is implemented via injected scripts that poll the element state and a set of heuristics comparing bounding boxes across animation frames.
Q2. What causes “element is not stable” errors and how do you fix them? The element’s bounding box changed between two consecutive animation frames, typically due to CSS animations, transitions, or layout shifts. Fixes: disable animations in config (animations: 'disabled'), wait for a stable parent, or target a non-animated ancestor.
Q3. When does getByRole fail to find an element that exists? When the element lacks an implicit or explicit ARIA role, or when its accessible name is computed from hidden content. Also, custom components that render interactive elements without proper roles (e.g., a <div> styled as a button without role="button") won’t be found.
Q4. How do you handle a locator that matches multiple elements intentionally? Use .filter(), .nth(), or iterate with .all(). For lists, prefer scoping: page.getByRole('row').filter({ hasText: 'Alice' }).getByRole('button'). Never rely on .first() in production tests; it’s a flakiness signal.
Q5. What is the difference between locator.waitFor({ state: 'attached' }) and locator.waitFor({ state: 'visible' })? attached means the element exists in the DOM even if hidden. visible means it has a non-empty bounding box and is not display: none or visibility: hidden. For interaction, you almost always want visible.
Q6. How do you locate an element by its text that is split across child elements? getByText normalizes whitespace and matches against the element’s full text content, so <span>Hello <b>World</b></span> is matched by getByText('Hello World'). For partial matches, pass { exact: false } (default) or use a regex.
Q7. What is a “strict mode violation” and when is it desirable? Playwright throws when a locator resolves to more than one element during an action. This is desirable because it forces you to write specific locators. To opt out for intentional multi-element operations, use .all(), .nth(), or .first() with explicit intent.
Q8. How do you handle elements inside closed shadow DOM? You cannot pierce closed shadow DOM from the page context. Options: expose a test hook on the component, use evaluate to access the shadow root if the host exposes it, or switch to component testing where you mount the component directly.
Q9. What is the “receives events” check and when does it cause false negatives? Playwright checks that the element at the click point is the target or a descendant. It fails when an overlay, tooltip, or invisible element intercepts the click. Fix: dismiss the overlay, use force: true (last resort), or click the actual receiving element.
Q10. How do you write a locator that survives a component library upgrade? Avoid internal class names, data attributes not part of the public contract, and deeply nested selectors. Prefer role-based locators, accessible names, and data-testid attributes that the team commits to maintaining.
Section 2: Network Interception & API Testing (Q11–Q25)
Q11. What is the difference between route.fulfill(), route.continue(), and route.fetch()? fulfill() returns a mock response without hitting the server. continue() lets the request proceed, optionally with modified headers, method, or body. fetch() sends the request to the real server and returns the response so you can modify it before fulfilling .
Q12. How do you modify a response body while preserving the original headers and status? Use route.fetch(), parse the response, modify the data, then route.fulfill({ response, body: JSON.stringify(modified) }). Passing the original response object preserves headers and status .
Q13. What is the page.request vs request fixture distinction in advanced scenarios? page.request shares the page’s cookie jar and is authenticated as the current user. The request fixture has its own isolated cookie jar, making it suitable for admin operations, setup/teardown, or unauthenticated API checks .
Q14. How do you record and replay network traffic with HAR files? Record with routeFromHAR(path, { update: true }) during development. Replay with routeFromHAR(path) in tests. HAR files capture request/response headers, bodies, and timings, providing realistic test data without hitting live services .
Q15. How do you simulate network throttling in Playwright? Use CDP: client.send('Network.emulateNetworkConditions', { offline: false, downloadThroughput: speed * 1024 / 8, uploadThroughput: speed * 1024 / 8, latency: ms }). This lets you test loading states, timeouts, and retry logic .
Q16. What is the “Cookie header override” caveat with route.continue()? You cannot override the Cookie header via route.continue({ headers }). The browser fills cookies from its own cookie jar. To change cookie state, use context.addCookies() or modify storageState.
Q17. How do you test a WebSocket connection in Playwright? Playwright doesn’t have native WebSocket mocking, but you can: (a) evaluate window.ws.readyState in the page context , (b) use MSW (Mock Service Worker) to intercept WebSocket handlers , or (c) expose the socket on window and assert its state.
Q18. How do you validate API response schemas in Playwright tests? Use Zod, AJV, or the playwright-schema-validator plugin. Fetch the response, then run schema.parse(await response.json()). This catches contract violations that status code checks miss .
Q19. How do you handle OAuth/SSO flows without driving the IdP UI every time? Best practice: perform token exchange via API in a setup project, inject tokens into localStorage via addInitScript, navigate to the app, then save storageState. Keep one slow, real SSO test tagged @auth-integration for nightly runs .
Q20. How do you test retry logic with Playwright’s route mocking? Set up a counter in the route handler. Return 503 for the first N requests, then 200. Assert the UI eventually shows the success state and that the counter equals the expected retry count .
Q21. What is the maxRedirects option in route.fetch() and when would you use it? It controls how many redirects route.fetch() follows before returning the response. Useful for auth flows that redirect through multiple endpoints; you can assert on the final response or simulate a redirect loop failure.
Q22. How do you abort requests selectively by resource type? Use route.request().resourceType() inside the handler: if (['image', 'font'].includes(type)) route.abort(); else route.continue();. This speeds up tests and lets you test offline/blocked-resource behavior .
Q23. What is route.fallback() and when do you need it? fallback() continues to the next matching route handler instead of fulfilling immediately. Use it when you have multiple route handlers for the same URL and want conditional logic layered across them.
Q24. How do you test that your app handles a 500 error gracefully? Intercept the API route, call route.fetch() to get the real response (or skip it), then route.fulfill({ status: 500, body: ... }). Assert the error UI appears .
Q25. Can you intercept requests made by a service worker? By default, service workers bypass Playwright’s route interception. Set serviceWorkers: 'block' in context options to force all requests through the page’s network stack, making them interceptable .
Section 3: Advanced Fixtures & Test Architecture (Q26–Q40)
Q26. What is the difference between test.extend and mergeTests? test.extend creates a new test object with additional fixtures, typically in one file. mergeTests combines multiple extended test objects into one, useful for composing fixtures from different domains (API, UI, auth) .
Q27. How do you create a fixture that depends on another fixture? Declare the dependency in the fixture function’s argument destructuring: myFixture: async ({ page, request }, use) => { ... }. Playwright resolves dependencies automatically.
Q28. What is the “automatic fixture” pattern and when is it useful? An automatic fixture runs even if not explicitly requested, via test.extend({ autoFixture: [async ({}, use) => { ... }, { auto: true }] }). Useful for global setup like console error monitoring or network logging.
Q29. How do you scope a fixture to run once per worker instead of per test? Use { scope: 'worker' } in the fixture options. The fixture is initialized when the worker starts and torn down when it exits, ideal for expensive resources like database connections.
Q30. What is the “boxed fixture” pattern for safe teardown? Wrap the value in an object with a dispose method so teardown always runs even if the test fails mid-use. Playwright 1.50+ supports explicit resource management with await using.
Q31. How do you share authentication state across parallel workers? Create the auth state file in a setup project, then reference it via test.use({ storageState: 'auth/user.json' }). All workers read the same file, avoiding redundant login flows .
Q32. What is a “fixture override” and when should you avoid it? Overriding a built-in fixture (like page) changes behavior for all tests in scope. Avoid it unless you need global instrumentation; prefer creating a new fixture that wraps the original.
Q33. How do you pass parameters to fixtures from test files? Use a test.use({ myOption: value }) at the file or describe level, and declare the option as a fixture that reads the value. This is the “option fixture” pattern.
Q34. What is the difference between test.describe.serial and test.describe.parallel? serial runs tests in order and stops on first failure, useful for dependent flows. parallel is the default and runs tests concurrently within the describe block.
Q35. How do you create a fixture that provides a typed page object?
This gives type-safe access to loginPage in every test .
Q36. What is the “fixture composition” pattern for cross-cutting concerns? Layer fixtures: base.extend(authFixtures).extend(apiFixtures).extend(loggingFixtures). Each layer adds one concern, keeping fixtures focused and testable.
Q37. How do you clean up test data in a worker-scoped fixture? Create a unique namespace per worker (e.g., worker-${workerInfo.workerIndex}), seed data in the fixture setup, and delete all data matching that namespace in teardown.
Q38. What is the “test data factory” pattern and how does it integrate with fixtures? A factory is a function that creates entities via API with unique names. Expose it as a fixture that also tracks created entities and cleans them up in teardown.
Q39. How do you handle flaky tests at the framework level? Set retries: 2 in config, trace: 'on-first-retry' for diagnosis, and use test.fail() to mark known flaky tests. Quarantine persistent flakes in a separate project and fix root causes rather than relying on retries.
Q40. What is test.step and how does it improve debuggability? test.step('Login as admin', async () => { ... }) creates labeled sections in the trace viewer and reports. Steps can be nested and are useful for documenting multi-phase tests.
Section 4: Component Testing (Q41–Q50)
Q41. What is Playwright component testing and how does it differ from E2E? Component testing mounts individual UI components in a real browser without the full application. It tests rendering, props, and interactions in isolation, running faster than E2E .
Q42. Which frameworks does Playwright component testing support? React (@playwright/experimental-ct-react), Vue, and Svelte. It requires a separate config (playwright-ct.config.ts) and uses the mount fixture .
Q43. What is the “story” concept in Playwright’s newer component testing model? A story is a wrapper that embeds a component in a specific scenario (props, providers, mock data). Stories live in *.story.tsx files and are rendered by a “gallery” page .
Q44. How does the mount fixture work? const component = await mount(<App />) renders the component in the gallery and returns a Locator scoped to the component root. You can then use component.getByRole(...) for interactions .
Q45. How do you test a component that makes API calls? Use route interception in the component test just like E2E: page.route('**/api/data', ...). Alternatively, pass mock data via props or a provider wrapper.
Q46. Can you use Playwright’s trace viewer with component tests? Yes. Enable trace: 'on-first-retry' in playwright-ct.config.ts. The trace shows component interactions, DOM snapshots, and network calls .
Q47. What is the “gallery” in Playwright component testing? A single page served by your dev server that exposes window.mount() and window.unmount(). It discovers *.story.* files and renders the selected story into a root element .
Q48. How do you test component state changes (e.g., toggles, accordions)? Mount the component, assert initial state via toContainText or toHaveAttribute, perform the interaction, then assert the new state. The trace captures each step for debugging .
Q49. What are the limitations of Playwright component testing? It’s experimental; the API may change. It doesn’t test routing, full-page layout, or backend integration. You still need E2E tests for those concerns .
Q50. When would you choose component testing over E2E? For design system components, complex form controls, and UI states that are hard to trigger in a full app (e.g., error states, loading skeletons). Component tests run faster and are less flaky.
Q51. How does toHaveScreenshot() work? On first run, it captures a baseline PNG. On subsequent runs, it compares the current screenshot pixel-by-pixel against the baseline within configured tolerances .
Q52. What are the key config options for reducing false positives in visual tests? animations: 'disabled' freezes CSS animations, caret: 'hide' hides text cursors, scale: 'css' normalizes DPI differences, and maxDiffPixelRatio: 0.01 allows 1% pixel difference .
Q53. How do you mask dynamic content in a screenshot? Pass a mask array of locators: toHaveScreenshot({ mask: [page.locator('.timestamp')] }). The masked areas are rendered as solid rectangles in both baseline and comparison .
Q54. How do you update visual baselines when the UI changes intentionally? Run npx playwright test --update-snapshots and commit the new PNGs. Review the diff before committing to ensure changes are intentional .
Q55. What is the “stability gate” pattern in visual testing? Before taking a screenshot, assert that a critical element is visible (e.g., a heading or data row). This ensures the page has fully rendered and prevents capturing a blank or mid-render state .
Q56. How do you test accessibility with Playwright? Use @axe-core/playwright: const results = await new AxeBuilder({ page }).analyze(); expect(results.violations).toEqual([]);. Run it as a separate test or integrate into existing tests.
Q57. What are the limitations of visual regression testing? It catches pixel changes but not semantic regressions (e.g., a button that looks right but has wrong behavior). It can be flaky across OS/browser versions. It doesn’t test responsiveness unless you run multiple viewports.
Q58. How do you handle visual tests across different browsers? Playwright generates separate baselines per browser and platform by default (e.g., screenshot-chromium-darwin.png). Commit all variants or run visual tests on a single canonical browser in CI.
Q59. What is toMatchSnapshot() vs toHaveScreenshot()? toMatchSnapshot() compares arbitrary data (strings, objects). toHaveScreenshot() compares rendered page images. Use the former for DOM snapshots or API responses.
Q60. How do you test responsive design with Playwright? Create projects with different viewport sizes (devices['iPhone 13'], devices['Desktop Chrome']), or use page.setViewportSize() within a test. Assert layout changes via element visibility or position.
Section 6: Debugging & Diagnostics (Q61–Q70)
Q61. What is the Trace Viewer and what does it capture? A timeline of every action, DOM snapshot before/after each step, network requests, console logs, and source code. Enable via trace: 'on-first-retry' and view with npx playwright show-trace trace.zip.
Q62. How do you use page.pause() effectively? It opens the Playwright Inspector and pauses execution, letting you step through actions, inspect locators, and resume. Use it for interactive debugging, not in committed tests.
Q63. What is the “floating promise” pattern and how do you detect it? Calling an async method without await: page.click('button') instead of await page.click('button'). ESLint rules (@typescript-eslint/no-floating-promises) and Playwright’s own warnings help detect it.
Q64. How do you debug a test that fails only in CI? Enable trace: 'on-first-retry', run with --workers=1 to rule out concurrency, check for timezone/locale differences, and compare CI viewport to local. The trace viewer is the primary tool.
Q65. What does the “Call log” in the trace viewer show? A chronological list of Playwright API calls with their parameters, return values, and timing. It helps identify which action hung or returned unexpected data.
Q66. How do you capture console errors during a test?
typescript
const errors: string[] = [];
page.on('console', msg => {
if (msg.type() === 'error') errors.push(msg.text());
});
// after test:
expect(errors).toEqual([]);
Q67. What is the “Snapshot” tab in the trace viewer? A DOM snapshot of the page at the selected point in the timeline. You can inspect elements, see computed styles, and verify what the page looked like when an action ran.
Q68. How do you debug locator resolution? Use page.locator('...').highlight() to visually highlight matched elements, or inspect the locator in the Playwright Inspector. The trace viewer shows which element each action targeted.
Q69. What is the “Network” tab in the trace viewer? A list of all network requests with headers, bodies, timings, and status codes. Useful for diagnosing API failures, slow responses, or unexpected requests.
Q70. How do you record a video of a test run? Set video: 'retain-on-failure' or 'on' in config. Videos are attached to the test result and viewable in the HTML report.
Q71. How do you parallelize tests across files vs within files? By default, Playwright parallelizes by file. fullyParallel: true enables test-level parallelism within files, requiring tests to be independent .
Q72. What is sharding and how do you use it? npx playwright test --shard=1/4 splits tests across 4 machines. Each shard runs a deterministic subset, enabling horizontal scaling in CI.
Q73. How do you configure multiple projects for different browsers and devices? In playwright.config.ts, define a projects array with different use options: { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, etc. Tests run against all projects by default.
Q74. What is the webServer config option? It starts a dev server before tests and shuts it down after. Configure with command, url, and reuseExistingServer: !process.env.CI.
Q75. How do you set per-project timeouts? Add timeout to the project’s use object, or override at the test level with test.setTimeout(ms).
Q76. What is globalSetup vs a setup project? globalSetup is a single function that runs once before all projects. A setup project is a full Playwright project that runs before dependent projects and can use fixtures, reporters, and traces.
Q77. How do you run tests only on changed files in CI? Use --only-changed (Playwright 1.42+) or integrate with your CI’s change detection to pass specific file paths.
Q78. What is the blob reporter and when is it useful? It produces a report.zip that can be merged from multiple shards into a single HTML report using npx playwright merge-reports.
Q79. How do you configure retries per project? Add retries: 2 to the project’s use object. Different projects can have different retry policies (e.g., flaky visual tests get more retries).
Q80. What is expect.configure() and when would you use it? It creates a customized expect with default options: const slowExpect = expect.configure({ timeout: 10000 }). Useful for slow-running assertions in specific test suites.
Section 8: CI/CD & Production Patterns (Q81–Q90)
Q81. How do you cache Playwright browsers in GitHub Actions? Cache ~/.cache/ms-playwright keyed on the Playwright version from package.json. This avoids re-downloading browsers on every run.
Q82. How do you handle test data isolation in parallel CI runs? Use unique prefixes per worker/run (e.g., run-${process.env.GITHUB_RUN_ID}-worker-${workerIndex}). Clean up in worker teardown.
Q83. What is the “smoke test” project pattern? A subset of critical tests tagged @smoke that run on every PR. Full suite runs on merge to main or nightly.
Q84. How do you report test results to a dashboard like TestDino or Allure? Add the reporter to playwright.config.ts and set the API token via environment variable. Results stream during the run .
Q85. How do you handle secrets in CI? Use GitHub Actions secrets or your CI’s secret store. Never commit credentials. For auth state, generate it in a setup step and pass the file path via env var.
Q86. What is the “merge reports” workflow for sharded runs? Each shard uploads a blob report. A final job downloads all blobs and runs npx playwright merge-reports --reporter=html ./blobs.
Q87. How do you prevent flaky tests from blocking merges? Run flaky tests in a separate non-blocking job, quarantine persistent flakes, and use test.fixme() with a tracking issue. Retries buy time but don’t fix root causes.
Q88. How do you test against a staging environment with real data? Use environment-specific configs (baseURL from env), seed test data via API in setup, and clean up in teardown. Never run destructive tests against staging data.
Q89. What is the “canary” pattern for test selection? Run a small, fast subset of tests on every commit, a medium suite on PR, and the full suite nightly. This balances feedback speed with coverage.
Q90. How do you version and migrate visual baselines? Store baselines in the repo, update them when UI changes are intentional, and review diffs in PR. Use a dedicated branch for baseline updates to avoid noise.
This creates a fluent, type-safe navigation chain .
Q92. What is the satisfies operator and how does it help Playwright tests? const config = { retries: 2 } satisfies PlaywrightTestConfig validates the shape without widening the type. Useful for config objects where you want both validation and literal inference.
Q93. How do you type network response bodies safely? Define a Zod schema and parse: const data = UserSchema.parse(await response.json()). This gives you a typed, validated object at runtime.
Q94. What is the Locator type and how do you store locators in a page object? Locator is the return type of page.locator() and page.getByRole(). Store them as readonly class properties initialized in the constructor.
Q95. How do you type a custom fixture that wraps a page object?
typescript
type Fixtures = { loginPage: LoginPage };
export const test = base.extend<Fixtures>({ ... });
The generic parameter gives full type safety for test and test.use.
Q96. What is the Page vs Locator return type distinction? Page represents a tab; Locator represents an element. Page objects typically take Page in the constructor and expose Locator properties.
Q97. How do you use discriminated unions for test data?
typescript
type User = { role: 'admin'; permissions: string[] } | { role: 'viewer' };
This forces exhaustive handling and prevents invalid combinations in test factories.
Q98. What is the as const pattern for locator arrays? const roles = ['button', 'link'] as const preserves literal types, enabling roles.map(r => page.getByRole(r)) with proper narrowing.
Q99. How do you type page.evaluate() return values? const title = await page.evaluate<string>(() => document.title) — pass the expected return type as a generic. For complex objects, define an interface and cast.
Q100. What is the “branded type” pattern for test IDs?
typescript
type TestId = string & { __brand: 'TestId' };
This prevents accidentally passing a raw string where a test ID is expected, catching mix-ups at compile time.
To build an automated test framework using Playwright, Cucumber (BDD), and the Page Object Model (POM) pattern with TypeScript, follow this structured setup.
5.Write the Feature File:Define BDD scenarios using Gherkin.
Create src/tests/features/login.feature:
Gherkin
Feature: User Authentication
Scenario: Successful login with valid credentials
Given I navigate to "https://www.saucedemo.com/"
When I log in with username "standard_user" and password "secret_sauce"
Then I should see the inventory page title "Swag Labs"
6.Implement Step Definitions:Map Feature steps to Page Object code.
Create src/tests/steps/loginSteps.ts:
TypeScript
import { Given, When, Then } from '@cucumber/cucumber';
import { expect } from '@playwright/test';
import { page } from '../../hooks/hooks';
import { LoginPage } from '../../pages/LoginPage';
let loginPage: LoginPage;
Given('I navigate to {string}', async (url: string) => {
loginPage = new LoginPage(page);
await loginPage.navigateTo(url);
});
When('I log in with username {string} and password {string}', async (username: string, password: string) => {
await loginPage.login(username, password);
});
Then('I should see the inventory page title {string}', async (expectedTitle: string) => {
const actualTitle = await page.title();
expect(actualTitle).toBe(expectedTitle);
});
7.Add Execution Script & Run Tests:Execute tests via npm.
Update your package.json file to include a test command:
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().
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.
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.
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.
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.
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.
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.
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.
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
1
What is JavaScript?
Fundamentals
2
What is the difference between var, let, and const?
Variables
3
What is hoisting?
Execution
4
What is TDZ?
let/const
5
What is the difference between == and ===?
Equality
6
What is a closure?
Scope
7
What is this?
Context
8
Arrow function vs normal function?
Functions
9
What is a Promise?
Asynchronous JavaScript
10
What is async/await?
Asynchronous JavaScript
11
What is Promise.all()?
Concurrency
12
What is the event loop?
Runtime
13
Microtask vs task?
Async execution
14
map() vs filter()?
Arrays
15
find() vs filter()?
Arrays
16
Spread vs rest?
ES6
17
What is destructuring?
ES6
18
What is prototype inheritance?
OOP
19
What are JavaScript modules?
Code organization
20
What 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.
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.
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.
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.
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.
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.
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));
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.
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);
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.
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.
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.
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).
GitHub Actions handles environment configuration at the workflow, job, or step scope. Sensitive credentials must be stored as Encrypted Secrets in repository/organization settings.
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).
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.
GitHub Actions runners come pre-configured with Docker, enabling step containers, containerized jobs, service containers (databases/queues), and image publishing.
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.