Concept Flow - Dynamic typing in JavaScript
Declare variable
Assign value of any type
Use variable
Change variable type by reassigning
↩Back to Use variable
JavaScript variables can hold any type and can change type anytime by assigning new values.
let x = 10; x = "hello"; x = true; console.log(x);
| Step | Code Line | Variable | Value | Type | Explanation |
|---|---|---|---|---|---|
| 1 | let x = 10; | x | 10 | number | Variable x declared and assigned number 10 |
| 2 | x = "hello"; | x | "hello" | string | x now holds a string value |
| 3 | x = true; | x | true | boolean | x now holds a boolean value |
| 4 | console.log(x); | Prints current value of x, which is true |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| x | undefined | 10 (number) | "hello" (string) | true (boolean) | true (boolean) |
Dynamic typing means variables can hold any type and change types anytime. Declare with let or var, assign any value. No errors when changing types. Use console.log to see current value and type. JavaScript figures out types at runtime.
let, var, or const without type annotations.let correctly. int x = 5; uses int which is not valid in JavaScript. var x: number = 5; uses TypeScript syntax. const x = 'hello'; is valid but declares a constant, not a variable that can change.let value = 10; value = 'hello'; console.log(typeof value);
value is a number 10, then reassigned to string 'hello'.typeof value returns the current type, which is "string" after reassignment.let data = 5; data = true; console.log(data.toFixed(2));
data starts as number 5, then changes to boolean true.toFixed is a method for numbers, not booleans, so calling it on a boolean causes a TypeError.function getType(input) {
// Your code here
}typeof returns the type of any JavaScript value as a string.Pass the test and this pattern moves unknown