Variables & Data Types in JavaScript
What is a Variable?
Know more in Detail
A variable is like a container that stores data values. In JavaScript, we use keywords like var, let, and const to declare variables.
Variable Declaration Keywords
- var - old way of declaring variables (function-scoped, can be re-declared and updated).
- let - modern way (block-scoped, can be updated but not re-declared in same scope).
- const - block-scoped, cannot be updated or re-declared (used for constants).
// Example
var name = "John"; // old
let age = 25; // modern
const country = "India"; // constant
Data Types in JavaScript
Know more in Detail
JavaScript has different types of data that variables can hold. These are divided into two main categories:
1. Primitive Data Types
Primitive means simple data types that store a single value like a name or number. They are stored directly in memory.
- String: A sequence of characters, like text.
- Number: Any numeric value (integer or floating-point).
- Boolean: True or false.
- Undefined: A variable that has been declared but not assigned a value.
- Null: Intentionally set to have no value.
- BigInt: Used for very large integers.
- Symbol: Unique and immutable value often used as object keys.
Primitive & Non-primitive in Detail
let name = "Alice"; // String
let age = 30; // Number
let isStudent = true; // Boolean
let score; // Undefined
let empty = null; // Null
let bigNumber = 1234567890123456789012345678901234567890n; // BigInt
let uniqueId = Symbol("id"); // Symbol
2. Non-Primitive (Reference) Data Types
Non-Primitive means complex data types like arrays, objects, and functions. They are stored by reference, which means they point to a memory address.
- Object: A collection of key-value pairs.
- Array: A list-like object.
- Function: A block of code that can be called.
let person = { name: "Bob", age: 40 }; // Object
let fruits = ["Apple", "Banana"]; // Array
function greet() { // Function
console.log("Hello!");
}
Type Checking
You can use typeof to check the data type of a variable:
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
Summary
- Use
let for values that may change.
- Use
const for constants.
- Understand the difference between primitive and reference types.
- Use
typeof to inspect types.