Variables and Data Types in JavaScript
In JavaScript, variables are used to store data values. JavaScript is dynamically typed, meaning you don't need to declare the type of a variable explicitly. Variables can hold different types of data, such as numbers, strings, booleans, objects, and more.
Declaring Variables
Variables in JavaScript can be declared using let
, const
, or var
.
let age = 25; // Mutable variable
const name = "Alice"; // Immutable variable
var isStudent = true; // Older way (avoid in modern code)
Common Data Types
- Number: Represents numeric values (e.g.,
10
,3.14
). - String: Represents text data (e.g.,
"Hello"
,'JavaScript'
). - Boolean: Represents true or false values.
- Object: Represents key-value pairs (e.g.,
{ name: "Alice", age: 25 }
). - Array: Represents an ordered collection of elements (e.g.,
[1, 2, 3]
). - Undefined: Represents a variable that has not been assigned a value.
- Null: Represents an intentional absence of value.
Example:
let age = 25;
const name = "Alice";
let isStudent = true;
let scores = [90, 85, 95];
let person = { name: "Alice", age: 25 };
console.log("Name:", name);
console.log("Age:", age);
console.log("Is Student:", isStudent);
Typeof Operator
The typeof
operator is used to determine the type of a variable.
console.log(typeof age); // Output: number
console.log(typeof name); // Output: string
console.log(typeof isStudent); // Output: boolean
console.log(typeof scores); // Output: object
console.log(typeof person); // Output: object
console.log(typeof undefinedVar); // Output: undefined
Type Conversion
JavaScript automatically converts types in certain situations, but you can also explicitly convert types.
// Implicit Type Conversion
let num = "10";
let result = num + 5; // Output: "105" (string concatenation)
// Explicit Type Conversion
let numAsNumber = Number(num); // Convert string to number
let resultAsNumber = numAsNumber + 5; // Output: 15
Template Literals
Template literals allow you to embed expressions inside strings using backticks (`
).
let greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting); // Output: Hello, my name is Alice and I am 25 years old.
Constants and Immutability
Variables declared with const
cannot be reassigned, but their properties can be modified if they are objects or arrays.
const person = { name: "Alice", age: 25 };
person.age = 26; // Allowed
// person = { name: "Bob", age: 30 }; // Error: Assignment to constant variable
Next: Control Structures