JavaScript Variables & Data Types
Variables store data values. JavaScript has multiple ways to declare variables and many data types.
Declaring Variables
var — Old Way (Avoid)
var name = "John";
var age = 25;
Function-scoped, can be redeclared, and hoisted. Use let or const instead.
let — When Reassigning
let name = "John";
name = "Jane"; // OK
Block-scoped and can be reassigned.
const — Default Choice
const PI = 3.14159;
// PI = 3; // Error!
Block-scoped, cannot be reassigned. Must initialize immediately.
Rule: Use const by default. Use let only when reassignment is needed.
Naming Rules
let userName = "John"; // camelCase
let _private = true; // underscore OK
let $element = "div"; // dollar sign OK
// let 123abc = "bad"; // Error: can't start with number
// let my-name = "bad"; // Error: no hyphens
Convention: Use camelCase for variables and functions.
Primitive Data Types
let name = "John"; // String
let age = 25; // Number
let isActive = true; // Boolean
let x; // undefined
let data = null; // null
let id = Symbol('id'); // Symbol
let big = 9007199254740991n; // BigInt
Remember: null is intentional emptiness. undefined means no value assigned.
Checking Types
typeof "John" // "string"
typeof 25 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (known JS bug)
typeof {} // "object"
typeof [] // "object"
Type Conversion
// String → Number
Number("123") // 123
parseInt("123abc") // 123
+"123" // 123
// Number → String
String(123) // "123"
(123).toString() // "123"
`${123}` // "123"
// To Boolean
Boolean(0) // false
Boolean("") // false
Boolean(null) // false
Boolean("hello") // true
Boolean({}) // true
Boolean([]) // true
Best Practices
- Use
constby default —letonly when needed - Use descriptive names —
userNamenotx - Use camelCase —
myVariablenotmy_variable - Initialize variables — Avoid
undefined - Use template literals — Instead of string concatenation
Common Mistakes
- Using
var— Uselet/constinstead - Redeclaring with
let— Not allowed - Confusing
nullandundefined— Different meanings - Using
typeof null— Returns"object"(bug in JS) - Confusing
=and===— Assignment vs comparison