If you are learning TypeScript, one of the first things you need to understand is variables.
Don’t worry if the word “variable” sounds technical.
It is actually a very simple idea.
Imagine you have a small box.
You put a toy inside the box.
Later, you take the toy out and put another toy inside.
That box is similar to a variable in programming.
A variable is simply a named place where your program can store information.
For example:
let name = "Rahul";
Here, name is the variable and "Rahul" is the value stored inside it.
You can imagine it like this:
Variable
|
↓
+-------------+
| name |
|-------------|
| "Rahul" |
+-------------+
But TypeScript adds something special.
It can also understand what kind of value the variable contains.
For example:
let age: number = 10;
Now TypeScript knows:
“The
agevariable 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
letconstvar- 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;
We now have three variables.
studentName → "Rahul"
studentAge → 10
studentMarks → 95
You can use these values later.
console.log(studentName);
console.log(studentAge);
console.log(studentMarks);
Output:
Rahul
10
95
So why not simply write "Rahul" everywhere?
Because programs become much easier to manage when we give information meaningful names.
Imagine an application containing 100 different places where a user’s name is required.
Instead of repeatedly writing:
"Rahul"
you can use:
studentName
This makes your program easier to understand and maintain.
Why Do We Need Variables?
Let’s imagine you are creating an online shopping application.
You might need to store:
Product Name
Product Price
Product Quantity
Customer Name
Customer Email
Order Status
Payment Status
Without variables, managing this information would be extremely difficult.
With variables:
const productName = "Laptop";
const price = 75000;
let quantity = 2;
const customerName = "Rahul";
let paymentStatus = "Pending";
Now your program can work with this information.
For example:
const totalPrice = price * quantity;
console.log(totalPrice);
Output:
150000
The important idea is:
Variables allow programs to remember and work with information.
Creating Your First TypeScript Variable
The simplest syntax is:
let variableName = value;
For example:
let name = "Rahul";
Let’s break it down.
let → tells TypeScript we are creating a variable
name → variable name
= → assignment operator
"Rahul" → value
So:
let name = "Rahul";
means:
Create a variable called
nameand store"Rahul"inside it.
The Three Ways to Declare Variables
TypeScript supports three JavaScript variable declaration keywords:
let
const
var
You will mostly use:
let
const
var is an older JavaScript approach that you may encounter in existing applications.
Let’s understand all three.
Understanding let
Use let when you expect the value to change.
Example:
let age = 20;
age = 21;
console.log(age);
Output:
21
Initially:
age → 20
After reassignment:
age → 21
Think of let as a box whose contents can be replaced.
+----------------+
| age |
|----------------|
| 20 |
+----------------+
↓
+----------------+
| age |
|----------------|
| 21 |
+----------------+
This is useful for values such as:
- Counters
- Scores
- Status
- Current page
- Retry count
- Shopping cart quantity
For example:
let retryCount = 0;
retryCount = retryCount + 1;
console.log(retryCount);
Output:
1
Understanding const
Now imagine you have a box with a special lock.
Once you put something inside, you don’t want to replace the box’s value.
That’s similar to const.
Example:
const country = "India";
You cannot do:
country = "USA";
TypeScript will report an error because a const variable cannot be reassigned.
Use const when the variable should not be reassigned.
For example:
const companyName = "SQA Tools";
const browserName = "Chrome";
const applicationUrl = "https://example.com";
These values are not expected to change during the execution of the program.
let vs const
This is one of the most common interview questions.
The basic difference is:
| Feature | let | const |
|---|---|---|
| Can be reassigned? | Yes | No |
| Block scoped? | Yes | Yes |
| Must be initialized immediately? | No | Yes |
| Modern JavaScript/TypeScript | Yes | Yes |
| Common usage | Changing values | Values not reassigned |
Example:
let score = 10;
score = 20;
Valid.
But:
const score = 10;
score = 20;
Invalid.
A simple rule:
Use
constby default. Useletwhen you need reassignment.
What Is var?
Before let and const became standard, JavaScript developers commonly used:
var name = "Rahul";
TypeScript still supports var.
However, modern TypeScript development generally prefers:
let
and:
const
Why?
Because var has different scoping behavior that can lead to confusing situations.
For example:
if (true) {
var message = "Hello";
}
console.log(message);
The variable can still be accessed outside the block.
Compare that with let:
if (true) {
let message = "Hello";
}
console.log(message);
Here, message is not available outside the block.
This concept is called block scope.
We’ll look at it shortly.
Variable Naming Rules
You can’t give variables just any name you want.
For example:
let studentName = "Rahul";
is valid.
But:
let 123student = "Rahul";
is invalid.
Variable names generally:
- Can contain letters
- Can contain numbers
- Can contain
_ - Can contain
$ - Cannot start with a number
- Cannot contain spaces
- Cannot use reserved keywords
For example:
let firstName = "Rahul";
let student1 = "Amit";
let _count = 10;
let $price = 500;
These are valid syntax.
Use Meaningful Variable Names
This is one of the most important programming habits.
Avoid:
let x = "Rahul";
let y = 25;
let z = true;
Someone reading the code may wonder:
What is
x?
Instead:
let userName = "Rahul";
let userAge = 25;
let isLoggedIn = true;
Now the code explains itself.
Compare:
if (x) {
// ...
}
with:
if (isLoggedIn) {
// ...
}
Which one is easier to understand?
Obviously:
isLoggedIn
Good variable names are like good labels on boxes.
Camel Case in TypeScript
A common naming convention in TypeScript is camelCase.
Examples:
firstName
lastName
userName
emailAddress
phoneNumber
isLoggedIn
totalAmount
productPrice
The first word starts with lowercase, and the next words start with uppercase.
For example:
firstName
↑
capital N
This convention is widely used in JavaScript and TypeScript codebases.
Type Annotations
Now let’s add the feature that makes TypeScript different from ordinary JavaScript.
You can explicitly tell TypeScript what type of value a variable should contain.
Example:
let age: number = 25;
The : number part is called a type annotation.
Another example:
let name: string = "Rahul";
And:
let isActive: boolean = true;
Think of this as putting a label on the box.
+---------------------+
| age |
|---------------------|
| TYPE: number |
| VALUE: 25 |
+---------------------+
Now TypeScript understands exactly what you expect.
TypeScript Variables With Common Types
String
let userName: string = "Rahul";
A string stores text.
Number
let age: number = 25;
A number stores numeric values.
Boolean
let isLoggedIn: boolean = true;
A boolean stores:
true
or:
false
Type Inference
Here’s a very useful TypeScript feature.
You don’t always have to tell TypeScript the type.
For example:
let name = "Rahul";
TypeScript looks at "Rahul" and understands:
name → string
Similarly:
let age = 25;
TypeScript understands:
age → number
And:
let isActive = true;
TypeScript understands:
isActive → boolean
This is called type inference.
Think of TypeScript as a smart teacher.
You don’t need to tell the teacher:
“This is a red apple.”
The teacher can see the apple and understand what it is.
Similarly, TypeScript can often look at the initial value and determine the type.
Type Annotation vs Type Inference
Compare these:
let age: number = 25;
and:
let age = 25;
In many situations, TypeScript can infer that age is a number.
So you don’t necessarily need to write:
: number
every time.
A clean approach is:
const name = "Rahul";
const age = 25;
const isActive = true;
TypeScript understands their types automatically.
When Should You Use Type Annotations?
Type annotations are useful when they provide additional clarity or when TypeScript cannot infer the intended type.
For example:
let userName: string;
Later:
userName = "Rahul";
You can also use them when defining function parameters, object structures, API models, and other important contracts.
For example:
let userId: string | number;
Here the annotation communicates something important:
userIdcan be a string or a number.
Reassigning Variables
A variable declared with let can be reassigned.
let city = "Indore";
city = "Mumbai";
console.log(city);
Output:
Mumbai
But you cannot reassign a const variable:
const city = "Indore";
city = "Mumbai";
This produces an error.
The important word here is reassignment.
A Common const Confusion
Many beginners think:
“If I use
const, absolutely nothing can change.”
That’s not completely correct.
Consider:
const user = {
name: "Rahul",
age: 25
};
You cannot replace the entire object:
user = {
name: "Amit",
age: 30
};
But you can potentially change a property:
user.name = "Amit";
Why?
Because const prevents reassignment of the variable binding.
It does not automatically make every object property immutable.
If you need that behavior, TypeScript provides other tools such as readonly.
Variables With Arrays
Variables can store arrays too.
const fruits: string[] = [
"Apple",
"Banana",
"Mango"
];
You can access values:
console.log(fruits[0]);
Output:
Apple
You can also modify the array:
fruits.push("Orange");
The variable is still const.
Why?
Because we aren’t replacing the array itself.
We are modifying its contents.
This distinction is important when explaining const during interviews.
Variables With Objects
A variable can also store an object.
const user = {
name: "Rahul",
age: 25
};
You can access:
console.log(user.name);
Output:
Rahul
You can also create more complex objects:
const employee = {
id: 101,
name: "Rahul",
department: "QA",
experience: 8
};
This becomes especially important when we start learning interfaces.
Variables Inside Functions
Variables can be created inside functions.
function calculateTotal() {
const price = 100;
const quantity = 2;
return price * quantity;
}
Here:
price
quantity
are local variables.
They exist inside the function.
You can think of a function as a room.
Variables created inside the room normally belong to that room.
Understanding Scope
Scope means where a variable can be accessed.
This is an important concept for interviews.
Consider:
let globalName = "Rahul";
function printName() {
console.log(globalName);
}
The function can access globalName.
But consider:
function printName() {
let name = "Rahul";
}
console.log(name);
This will not work because name exists only inside the function.
Block Scope
let and const are block scoped.
A block is usually represented by:
{
// block
}
For example:
if (true) {
let message = "Hello";
console.log(message);
}
This works.
But:
if (true) {
let message = "Hello";
}
console.log(message);
The second console.log() cannot access message.
The variable belongs to the block.
Why Scope Matters in Automation?
If you work with Playwright and TypeScript, scope becomes very important.
For example:
test("Login Test", async ({ page }) => {
const username = "admin";
await page.getByLabel("Username").fill(username);
});
Here, username belongs to that test block.
You cannot automatically expect it to be available everywhere else.
Understanding scope helps you avoid bugs related to variables being unavailable where you need them.
TypeScript Variables in Playwright
Now let’s connect the concept to something practical.
Suppose you are writing a Playwright test.
You might have:
const url = "https://example.com";
const username = "testuser";
const password = "Password123";
Then:
await page.goto(url);
await page.getByLabel("Username").fill(username);
await page.getByLabel("Password").fill(password);
Variables make your test much easier to maintain.
Imagine the URL changes.
Instead of searching through 50 test cases for:
https://example.com
you can update one variable.
This is one of the practical benefits of using meaningful variables.
Variables for Test Configuration
You might create:
const browserName = "chromium";
const baseUrl = "https://example.com";
const timeout = 30000;
const headless = true;
Now these values can be reused across your framework.
For example:
test.setTimeout(timeout);
This makes automation frameworks more configurable and easier to maintain.
Variables for Test Data
You can also create test data:
const username = "testuser";
const password = "Password123";
const expectedTitle = "Dashboard";
Then:
await page.getByLabel("Username").fill(username);
await page.getByLabel("Password").fill(password);
await expect(page).toHaveTitle(expectedTitle);
This is much cleaner than putting values directly into every statement.
Variables With Environment Values
In real automation frameworks, sensitive information should not normally be hardcoded directly into the test.
Instead of:
const password = "MyRealPassword";
you might read configuration from environment variables:
const password = process.env.PASSWORD;
Now your test can use an environment-specific value.
For example:
Development → Development password
QA → QA password
Staging → Staging password
Production → Production credentials
This is an important concept when you move from beginner automation scripts to professional frameworks.
Common Mistakes With TypeScript Variables
Mistake 1: Using var Everywhere
Avoid writing modern TypeScript like this:
var name = "Rahul";
Prefer:
const name = "Rahul";
or:
let name = "Rahul";
depending on whether reassignment is needed.
Mistake 2: Using let When const Is Better
Instead of:
let companyName = "ABC";
if you never reassign it, prefer:
const companyName = "ABC";
This communicates your intention more clearly.
Mistake 3: Poor Variable Names
Avoid:
let a = "Rahul";
let b = 25;
let c = true;
Prefer:
const userName = "Rahul";
const userAge = 25;
const isActive = true;
Mistake 4: Using any Without a Reason
Avoid:
let data: any;
when you know what the data should contain.
TypeScript’s biggest advantage is type safety.
Don’t throw that advantage away unnecessarily.
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.
Example:
const languages: string[] = [
"JavaScript",
"TypeScript"
];
Add three more.
Program 4
Create an object representing a QA engineer.
Include:
name
experience
primarySkill
isAutomationEngineer
Program 5
Create variables representing a Playwright test:
baseUrl
username
password
timeout
browser
Choose appropriate variable declarations.
Mini Challenge
Can you predict the output?
let score = 10;
score = 20;
console.log(score);
Answer:
20
Now try:
const score = 10;
score = 20;
console.log(score);
What happens?
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.