Variables and Data Types
Understanding variables and data types is fundamental to programming. Variables are containers for storing data values, and data types define the kind of value a variable can hold and the operations that can be performed on it.
Variables
In programming, a variable is a symbolic name given to a memory location where a value can be stored. You can think of it like a labeled box where you can put information.
Declaring and Initializing Variables
Before you can use a variable, you typically need to declare it. Initialization is the process of assigning an initial value to a variable.
// Declaring a variable named 'userName'
let userName;
// Initializing the variable with a value
userName = "Alice";
// Declaring and initializing in one step
const userAge = 30;
var score = 100; // Older way of declaring variables, generally prefer let/const
Variable Naming Rules
- Variable names must start with a letter, an underscore (_), or a dollar sign ($).
- Variable names cannot start with a number.
- Variable names can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
- Variable names are case-sensitive (
userName
andusername
are different variables). - Reserved words (like
if
,for
,function
) cannot be used as variable names.
Data Types
Data types specify the type of data that a variable can hold. Different programming languages have different sets of data types, but most common ones include:
Primitive Data Types
These are the most basic data types:
1. String
Represents a sequence of characters, typically enclosed in quotes.
let greeting = "Hello, world!";
let message = 'This is a message.';
2. Number
Represents numeric values. This includes integers (whole numbers) and floating-point numbers (numbers with decimal points).
let count = 42;
let price = 19.99;
let temperature = -5;
3. Boolean
Represents a logical value, which can be either true
or false
.
let isActive = true;
let isComplete = false;
4. Undefined
A variable that has been declared but not yet assigned a value has the type undefined
.
let notAssigned; // notAssigned is undefined
5. Null
Represents the intentional absence of any object value. It is an assigned value, unlike undefined
.
let emptyValue = null;
6. Symbol (ES6+)
A unique and immutable primitive value, often used as identifiers for object properties.
const id = Symbol('uniqueId');
7. BigInt (ES11+)
For representing integers of arbitrary precision, larger than the maximum safe integer representable by the Number
type.
const bigNumber = 1234567890123456789012345678901234567890n;
Composite (or Reference) Data Types
These are more complex types that can hold collections of data:
1. Object
A collection of key-value pairs. Keys are typically strings, and values can be any data type, including other objects.
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
2. Array
An ordered list of values. Elements are accessed by their index (starting from 0).
let colors = ["red", "green", "blue"];
let numbers = [1, 2, 3, 4, 5];
Type Coercion
Type coercion is the process of automatically converting one data type to another. This can happen implicitly during operations.
Be mindful of type coercion, as it can sometimes lead to unexpected results. Explicitly converting types (e.g., using String()
, Number()
) can make your code more predictable.
For example:
let num = 5;
let str = "10";
let result = num + str; // Coerced to string: "510"
let anotherResult = num * str; // Coerced to number: 50
Checking Data Types
You can use the typeof
operator to determine the data type of a variable.
let myVar = "Hello";
console.log(typeof myVar); // Output: "string"
let myNum = 123;
console.log(typeof myNum); // Output: "number"
let myBool = false;
console.log(typeof myBool); // Output: "boolean"
let myObj = { a: 1 };
console.log(typeof myObj); // Output: "object"
let myArray = [1, 2];
console.log(typeof myArray); // Output: "object" (Note: typeof Array is 'object')
console.log(typeof null); // Output: "object" (A known quirk in JavaScript)
To specifically check if something is an array, you can use Array.isArray()
.
console.log(Array.isArray(myArray)); // Output: true
Understanding the distinction between primitive and reference types is crucial for managing data effectively and avoiding common bugs.