var
, let
, const
In JavaScript, variables are containers for storing data values. You can declare variables using three keywords: var
, let
, and const
. Understanding their differences is important for writing clean, bug-free code.
var
var
is the oldest way to declare variables and has some quirks:
var
are scoped to the nearest function, not blocks like if
or loops.var
declarations are hoisted to the top of their scope, meaning you can use the variable before it’s declared (though its value will be undefined
until assignment).Example:
console.log(x); // undefined (due to hoisting)
var x = 5;
console.log(x); // 5
if (true) {
var y = 10;
}
console.log(y); // 10 (y is accessible outside the if-block)
let
let
was introduced in ES6 to fix var
’s scoping problems:
let
exist only inside the nearest {}
block.let
variable before it’s declared.Example:
if (true) {
let a = 20;
console.log(a); // 20
}
// console.log(a); // Error: a is not defined
let
variables can be reassigned:
let count = 1;
count = 2; // valid
const
const
declares constants—variables that cannot be reassigned after initialization:
let
.const
can have their properties modified.Example:
const PI = 3.14;
// PI = 3.15; // Error: Assignment to constant variable
const obj = { name: "Alice" };
obj.name = "Bob"; // Allowed: modifying property, not reassigning obj
Best Practices
const
by default for values that don’t change.let
when you expect to reassign the variable.var
to reduce bugs related to hoisting and scope confusion.Using let
and const
leads to more predictable and readable code, which is especially helpful for beginners.
JavaScript has seven primitive data types. Primitives are the most basic kinds of data and are immutable, meaning their values cannot be changed once created. Understanding these types is fundamental to writing effective JavaScript.
1. Number
The Number
type represents all numeric values, including integers and floating-point numbers.
let age = 25;
let price = 19.99;
Note: JavaScript uses double-precision floating-point format, which can cause small rounding errors:
console.log(0.1 + 0.2); // 0.30000000000000004
This can confuse beginners, so be cautious with floating-point math.
2. String
Strings represent text and are enclosed in single quotes 'string'
, double quotes "string"
, or backticks ` (for template literals).
let name = "Alice";
let greeting = 'Hello';
let message = `Welcome, ${name}!`;
Strings are immutable — you cannot change a character directly but can create new strings from existing ones.
3. Boolean
Boolean values are either true
or false
, often used in conditions:
let isLoggedIn = true;
let hasAccess = false;
4. Undefined
A variable that has been declared but not assigned a value is undefined
:
let x;
console.log(x); // undefined
This means “no value has been assigned yet.”
5. Null
null
is a special value that represents “no value” or “empty.” It is explicitly assigned to indicate the absence of any object value.
let user = null;
Common pitfall: null
and undefined
are different but often confused. undefined
means a variable hasn’t been assigned, while null
means it has been intentionally cleared.
6. Symbol
Symbols are unique and immutable identifiers, often used to create unique object keys:
let id = Symbol("id");
Every symbol is unique, even if they have the same description.
7. BigInt
BigInt
allows representation of integers larger than the safe limit for Number
(2^53 - 1
):
let bigNumber = 9007199254740991n;
BigInts are created by appending n
to the end of an integer.
Summary
Primitive types are the building blocks of JavaScript data. Be mindful of differences like null
vs. undefined
and floating-point quirks with numbers. Knowing these types well will help you avoid common mistakes and write better code.
typeof
In JavaScript, the typeof
operator is used to determine the type of a variable or value. It’s a simple yet powerful tool to help you understand what kind of data you’re working with.
The syntax is straightforward:
typeof value
Here are examples using all the primitive types:
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof 9007199254740991n); // "bigint"
console.log(typeof null); // "object"
Most of these are intuitive, but note the special case with null
. Even though null
represents the absence of a value, typeof null
returns "object"
. This is a long-standing quirk in JavaScript, originating from its early implementation, and has been kept for backward compatibility. So, always remember that null
is a primitive type, but typeof
incorrectly labels it as an object.
Using typeof
with Variables
let name = "Alice";
console.log(typeof name); // "string"
let count;
console.log(typeof count); // "undefined"
let isActive = false;
console.log(typeof isActive); // "boolean"
Why Use typeof
?
typeof
is useful when writing conditional code that depends on data types, such as validating inputs or debugging your programs. While it doesn’t distinguish between objects like arrays or dates, it is reliable for checking primitive types.
Understanding how typeof
works helps you write clearer, more robust JavaScript programs.