Type inference
- Node.js course
- Beginner
- Lesson 9/116
- 4 min
Learn JavaScript's dynamic type inference.
Type inference
JavaScript is a dynamically typed language: you do not declare a variable's type explicitly; the engine infers it from the value.
For example, when you write let count = 42, count becomes a number. When you write let name = 'Alex', name becomes a string. You can later reassign the same variable with a value of a different type.
To check the type, you use the typeof operator; we will see it in detail in the next group.
Type checking with typeof
The typeof operator returns the type of a value as a string. For example, typeof 42 returns 'number'; typeof 'hello' returns 'string'.
This is useful when you want to behave differently based on a variable's type. For example, you can check whether an argument passed to a function is a number or a string.
Interestingly, typeof null returns 'object'; this is an old design decision in JavaScript.
Practice Print types with typeof
Declare let count = 42 and let name = 'Alex'. Then call console.log(typeof count) and console.log(typeof name) to print their types.
Starter code
// Declare count and name variables
// Print their types with typeofSample solution
let count = 42;
let name = "Alex";
console.log(typeof count);
console.log(typeof name);Expected output
number string
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Dynamic type
let x = 5; x = ____ // x is now a string
let x = 5; x = 'text'; // x is now a string
Explanation: JavaScript is dynamically typed, so the type can change.
2 Match the type concepts
| Term | Meaning |
|---|---|
typeof 42 |
number |
typeof 'text' |
string |
typeof true |
boolean |
typeof undefined |
undefined |
3 How does type inference work in JavaScript?
- The type must be declared explicitly
- The variable's type is determined at compile time
- The variable's type is determined at runtime Correct answer
- The type can never change
Explanation: JavaScript is dynamically typed, so the type is determined at runtime.