0
0
Typescriptprogramming~20 mins

Declaring global variables in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Global Variable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Output of accessing a global variable inside a function

What is the output of this TypeScript code?

Typescript
let count = 10;
function showCount() {
  console.log(count);
}
showCount();
A10
Bundefined
CReferenceError
Dnull
Attempts:
2 left
💡 Hint

Global variables are accessible inside functions unless shadowed.

Predict Output
intermediate
1:30remaining
Effect of redeclaring a global variable inside a function

What will this code print?

Typescript
let message = "Hello";
function greet() {
  let message = "Hi";
  console.log(message);
}
greet();
console.log(message);
A
Hi
Hi
B
Hello
Hello
C
Hi
Hello
DReferenceError
Attempts:
2 left
💡 Hint

Local variables with the same name shadow global ones inside functions.

🔧 Debug
advanced
2:00remaining
Why does this code cause an error?

What error does this TypeScript code produce?

Typescript
function update() {
  count = 5;
  let count = 10;
}
update();
ANo error, runs fine
BReferenceError: Cannot access 'count' before initialization
CTypeError: count is not a function
DSyntaxError: Unexpected token
Attempts:
2 left
💡 Hint

Variables declared with let are not hoisted like var.

Predict Output
advanced
1:30remaining
Global variable modification inside a function

What is the output of this code?

Typescript
let total = 0;
function add(value: number) {
  total += value;
}
add(5);
add(3);
console.log(total);
ANaN
B0
CReferenceError
D8
Attempts:
2 left
💡 Hint

Functions can change global variables if they don't redeclare them.

🧠 Conceptual
expert
3:00remaining
Understanding global variable declaration in TypeScript modules

In a TypeScript file treated as a module, which statement correctly declares a global variable accessible across multiple files?

ADeclare the variable with <code>declare global { var myVar: number; }</code> inside a <code>*.d.ts</code> file and assign it in one module.
BDeclare the variable inside a function with <code>globalThis.myVar = 10;</code> without any declaration.
CUse <code>var myVar = 10;</code> inside a function to make it global.
DUse <code>let myVar = 10;</code> at the top of any module file.
Attempts:
2 left
💡 Hint

Global variables shared across modules require declaration merging or global augmentation.