You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Variables store values that your program can read and modify. JavaScript has three ways to declare variables: var, let, and const. Modern JavaScript uses let and const almost exclusively.
let name = "Alice"; // can be reassigned
const age = 30; // cannot be reassigned
var score = 100; // old-style, avoid in modern code
Use const by default. Switch to let only when you need to reassign the variable. Avoid var — it has quirky scoping behaviour that can cause bugs.
JavaScript has seven primitive types:
// Number — integers and decimals share one type
let count = 42;
let price = 9.99;
// String — text in single, double, or backtick quotes
let greeting = "Hello";
let message = 'World';
let template = `Count is ${count}`; // template literal
// Boolean
let isLoggedIn = true;
let hasPaid = false;
// undefined — variable declared but not assigned
let result;
console.log(result); // undefined
// null — intentional absence of value
let user = null;
// Symbol — unique identifiers (advanced use)
const id = Symbol("id");
// BigInt — integers larger than Number.MAX_SAFE_INTEGER
const big = 9007199254740993n;
Use typeof to inspect a value's type at runtime:
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (historical quirk!)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
Note: typeof null returns "object" — this is a well-known bug in JavaScript that was never fixed for compatibility reasons.
JavaScript automatically converts types in certain contexts. This can be surprising:
console.log("5" + 3); // "53" (number converted to string)
console.log("5" - 3); // 2 (string converted to number)
console.log(true + 1); // 2 (true becomes 1)
console.log(false + 1); // 1 (false becomes 0)
To convert explicitly:
Number("42"); // 42
String(100); // "100"
Boolean(0); // false
Boolean("hello"); // true
parseInt("3.7"); // 3
parseFloat("3.7"); // 3.7
JavaScript uses camelCase by convention:
let firstName = "Alice";
let totalPrice = 49.99;
const MAX_RETRIES = 3; // constants often use UPPER_SNAKE_CASE
Variable names must start with a letter, underscore, or dollar sign. They are case-sensitive — myVar and myvar are different.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.