- Abstract class
- Annotations
- Array
- Asserts
- Casting
- Class
- Comments
- Conditional types
- Const
- Data types
- Date object
- Decorators
- Default parameter
- Dictionary
- Enum
- Exclude type
- Extract type
- For loop
- forEach()
- Function
- Generic types
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- Intersection types
- Keyof type operator
- Let
- Map type
- Mixin
- Module
- Namespace
- Never
- Object type
- Omit type
- Operator
- Optional parameter
- Partial type
- Pick type
- Promise
- Property
- Readonly type
- Record type
- Required type
- Satisfies operator
- Tuples
- Type alias
- Type assertion
- Type guard
- Type narrowing
- Typeof Type Operator
- Union
- Utility types
- Var
- Void
TYPESCRIPT
TypeScript Var: Syntax, Usage, and Examples
The var keyword in TypeScript declares variables with function or global scope. While it's still supported, developers generally prefer let and const for better scoping and fewer surprises. Understanding how TypeScript var behaves will help you read older code and avoid subtle bugs in newer projects.
How to Use var in TypeScript
The syntax is identical to JavaScript:
var count = 10;
You can declare variables using var in global scope, inside functions, or even inside blocks. But here's the catch: var doesn't obey block scope. Instead, it "hoists" the variable to the top of its enclosing function or global context.
Consider this example:
function testVarScope() {
if (true) {
var message = "Hello from inside the block!";
}
console.log(message); // Accessible here because of var's function scope
}
Even though message is declared inside the block, it’s available throughout the function. This behavior is one of the main reasons TypeScript developers now favor let and const.
When to Use var in TypeScript
While var has fallen out of favor, there are still a few situations where it might appear:
- Legacy Codebases – If you're working in older TypeScript or JavaScript projects, you'll often encounter
var. - Function-Scoped Logic – In rare cases, function scope might be desirable for backward compatibility or porting older APIs.
- Quick Scripts and Examples – Some devs use
varin simple snippets or debugging scripts because it's fast and flexible (but not recommended for production).
Generally, you should avoid using var in modern TypeScript code unless there's a specific reason tied to external dependencies or compatibility.
Examples of var in TypeScript
Example 1: Global Scope
var greeting = "Hi there!";
console.log(greeting); // Output: Hi there!
This works as expected. But because var declarations are hoisted, they may behave unexpectedly in more complex code.
Example 2: Inside a Function
function greetUser() {
var user = "Sasha";
console.log("Welcome, " + user);
}
greetUser();
// console.log(user); // Error: user is not defined (outside function scope)
Here, user is scoped to the function, which is the intended behavior.
Example 3: Block Scope Confusion
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i); // Will log "3" three times
}, 100);
}
Because var is function-scoped, not block-scoped, the variable i isn’t reset on each loop iteration. This causes all callbacks to log 3, not 0, 1, and 2. You can fix this by using let instead.
Learn More About var in TypeScript
Variable Hoisting with var
When you use var, TypeScript hoists the declaration (but not the initialization) to the top of the function or global scope.
function example() {
console.log(x); // Output: undefined
var x = 10;
}
Even though x is logged before it's initialized, the declaration still exists due to hoisting. This can be very confusing, especially to beginners.
Declare Var in TypeScript
You can explicitly declare a var in TypeScript just like in JavaScript:
declare var $: any; // Used for global variables, like in jQuery
This declare var TypeScript pattern is useful when working with third-party scripts or external variables that exist outside the TypeScript context.
If you're integrating older libraries or scripts with no type definitions, using declare var gives you access without triggering compiler errors.
Const vs Let vs Var in TypeScript
Understanding the difference between these three can help you avoid bugs and improve code clarity.
- Use
constwhen the value won’t change. - Use
letwhen you need to reassign the variable. - Avoid
varunless you're dealing with legacy code or a specific function-scoped need.
Here's an example that illustrates the difference:
const pi = 3.14; // Can't be reassigned
let age = 30; // Can be updated
var language = "TypeScript"; // Old-school way, avoid when possible
The const vs let vs var TypeScript debate boils down to safety and scoping. Prefer const and let for clean and modern TypeScript code.
ESLint and No Unused Vars
If you're using ESLint with TypeScript, you’ve likely encountered the no-unused-vars rule. This rule flags variables that are declared but never used:
var unused = 42; // Warning: 'unused' is defined but never used
To fix it, either use the variable or remove the declaration. The typescript-eslint plugin also provides tighter control over this rule with options for function arguments, rest siblings, and more.
You can also disable it temporarily if needed:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
var debugMode = true;
This is useful during debugging or when scaffolding a new module.
TypeScript Let vs Var: Why Let Wins
Most developers prefer let over var because it introduces block scope, reduces hoisting confusion, and behaves more predictably inside loops and conditionals.
Let’s revisit the earlier loop problem, but with let:
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i); // Output: 0, 1, 2
}, 100);
}
Now each iteration gets its own i, so the callback logs the expected values.
The TypeScript let vs var comparison really shows how far JavaScript has come. TypeScript builds on that by catching scoping issues early during compilation.
Should You Ever Use var in Modern TypeScript?
In most situations, no. You’ll find that let and const provide better behavior, clearer scope, and stricter safety. However, if you’re reading or converting older codebases—or working in mixed JS/TS environments—you’ll need to understand how var works.
You might also use declare var in TypeScript for global objects in libraries that don’t come with type definitions. In these cases, var serves as a bridge rather than a modern best practice.
Summary of Best Practices
- Avoid
varin favor ofletandconst. - If you're debugging legacy code, expect function-scoped behavior.
- Use
declare varfor external global variables when needed. - Let ESLint catch unused
vardeclarations before they clutter your code. - Prefer block-scoped variables (
let) in loops and conditionals. - Use
constwhen the value should never change.
The TypeScript var keyword still has a place in the language, mainly for backward compatibility and certain legacy workflows. While it offers flexibility, it lacks the clarity and safety of let and const.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.