Variables & Types
Declaring variables
Section titled “Declaring variables”In JavaScript, you can declare a variable with var
, let
, or const
.
Keyword | Description |
---|---|
var | Old way of declaring variables (still works but should be avoided because of confusing scope). |
let | A modifiable variable, limited to the block { } where it is declared. |
const | A constant variable, cannot be reassigned (but its content can still change if it’s an object or an array). |
let name = "Baptiste";const age = 26;
⚠️ With const, if the value is an object or an array, you can still modify its contents:
const fruits = ["apple", "banana"];fruits.push("pear");console.log(fruits); // ["apple", "banana", "pear"]
Data types in JavaScript
Section titled “Data types in JavaScript”In JavaScript, there are two main categories:
Primitive types
Section titled “Primitive types”Primitives are immutable (their value cannot change once created) and are stored directly in memory.
- String: text
- Number: number
- Boolean: true/false
- Null: empty value
- Undefined: undefined value
- Symbol: unique identifier (rare, advanced)
- BigInt: very large integers
let text = "Hello"; // stringlet number = 42; // numberlet active = true; // booleanlet empty = null; // nulllet unknown; // undefinedlet bigNumber = 123456789012345678901234567890n; // BigInt
Reference types
Section titled “Reference types”References point to objects in memory.
- Object: key/value pairs
- Array: ordered list
- Function: also an object in JavaScript
let person = { name: "Alice", age: 30 }; // objectlet fruits = ["apple", "banana"]; // arrayfunction greet() { return "Hello"; } // function
Checking a variable’s type
Section titled “Checking a variable’s type”Using typeof:
console.log(typeof "Hello"); // stringconsole.log(typeof 42); // numberconsole.log(typeof true); // booleanconsole.log(typeof null); // object (⚠️ historical bug in the language)console.log(typeof []); // objectconsole.log(typeof function(){}); // function
Practical example
Section titled “Practical example”let x = 10;let y = 5;let sum = x + y;console.log("The sum is:", sum); // The sum is: 15
Modern best practices
Section titled “Modern best practices”- Use const by default.
- Use let only when the value needs to change.
- Avoid var, except when reading old code.
- Use
typeof
to check the type when necessary.