Aller au contenu

Variables & Data Types

Ce contenu n’est pas encore disponible dans votre langue.

Prerequisites:

Variables are containers for storing data values. JavaScript has three ways to declare variables.

let message = "Hello";
message = "World"; // OK - can be reassigned
const PI = 3.14159;
// PI = 3; // Error! Cannot reassign const
var oldStyle = "Avoid using var";
// String
const name = "JavaScript";
// Number
const age = 25;
const price = 99.99;
// Boolean
const isActive = true;
// Undefined
let notAssigned;
// Null
const empty = null;
// Symbol (ES6)
const id = Symbol("id");
// BigInt (ES2020)
const bigNumber = 9007199254740991n;
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (historical bug)
typeof Symbol() // "symbol"
typeof {} // "object"
typeof [] // "object"

JavaScript automatically converts types in certain situations:

// String concatenation
"5" + 3 // "53" (number becomes string)
// Numeric operations
"5" - 3 // 2 (string becomes number)
"5" * "2" // 10
// Boolean context
Boolean("") // false
Boolean("hi") // true
Boolean(0) // false
Boolean(1) // true
// Global scope
const global = "I'm everywhere";
function example() {
// Function scope
const local = "I'm local";
if (true) {
// Block scope
let blockScoped = "Only here";
const alsoBlock = "Also only here";
}
// blockScoped is not accessible here
}

With variables mastered, learn about Functions to write reusable code.