Real-world data is often more complex than just single numbers or strings. For example, think about a shopping list, a user’s profile, or a set of settings for an app.
In JavaScript, we have three very useful tools to work with this kind of data: arrays, objects, and JSON.
🟢 Arrays: Lists of Items
An array is like an ordered list — it lets you store multiple values in one place.
let fruits = ["apple", "banana", "cherry"];
// Access items by their position (index starts at 0)
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
// Update an item
fruits[1] = "grape";
console.log(fruits); // ["apple", "grape", "cherry"]
- Arrays use square brackets [ ].
- Items inside are separated by commas.
- You can access items by their position (called the index, starting at 0).
Common Array Methods
fruits.push("mango"); // add item at the end
fruits.pop(); // remove last item
fruits.shift(); // remove first item
fruits.unshift("pear"); // add item at the start
👉 Arrays are perfect for storing lists like tasks, products, or messages.
🟡 Objects: Data with Properties
An object is a collection of key–value pairs. It lets you group related data under one “thing.”
let user = {
name: "Alice",
age: 25,
isAdmin: true
};
console.log(user.name); // "Alice"
console.log(user["age"]); // 25
- Objects use curly braces { }.
- Each property has a key (like
name) and a value (like"Alice"). - You can access values using either
.or[].
👉 Objects are great for representing things like users, products, or settings.
🔵 JSON: A Data Format for Sharing
JSON stands for JavaScript Object Notation. It’s a way of writing objects and arrays as text, so they can be saved or shared between systems (for example, between your app and a server).
Example JSON data
{
"name": "Alice",
"age": 25,
"hobbies": ["reading", "gaming", "cycling"]
}
In JavaScript
You often need to convert between JSON and JavaScript objects:
// JavaScript object
let user = { name: "Alice", age: 25 };
// Convert to JSON string
let jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Alice","age":25}'
// Convert back to JavaScript object
let userAgain = JSON.parse(jsonString);
console.log(userAgain.name); // "Alice"
👉 JSON is widely used for APIs (the way apps talk to each other).
✍️ Quick Practice
Try these exercises in your browser console:
- Create an array of 3 favorite colors. Add one more color using
.push(). - Create an object for a book with keys:
title,author, andyear. Print the author’s name. - Convert your book object into a JSON string using
JSON.stringify().
✨ Key Takeaways
- Arrays = ordered lists (good for tasks, items, messages).
- Objects = key–value pairs (good for users, products, settings).
- JSON = a text format based on JavaScript objects, useful for saving and sharing data.