Mastering Core JavaScript
Advanced Data Types
Beyond the Basics: Objects
So far, you've worked with simple data types like strings and numbers. But what happens when you need to group related information together? Imagine you're building a profile for a user. You'd have a name, an age, and maybe a city. Storing these in separate variables works, but it's messy.
This is where objects come in. An object is a collection of key-value pairs. Think of it like a filing cabinet where each drawer (the key) has a specific piece of information (the value) inside.
const userProfile = {
firstName: "Alex",
age: 32,
city: "New York",
isOnline: true
};
In this example, firstName, age, city, and isOnline are the keys (also called properties), and their corresponding values are on the right side of the colons. Notice that the values can be any data type, including strings, numbers, and booleans.
To access a value, you can use dot notation or bracket notation. Dot notation is cleaner and more common, but bracket notation is useful when the property name is stored in a variable or contains special characters.
// Dot notation
console.log(userProfile.firstName); // Outputs: Alex
// Bracket notation
console.log(userProfile['city']); // Outputs: New York
Objects can also hold functions, which we call methods. Methods are actions that an object can perform. Let's add a method to our userProfile object that introduces the user.
const userProfile = {
firstName: "Alex",
age: 32,
greet: function() {
console.log(`Hello, my name is ${this.firstName}.`);
}
};
userProfile.greet(); // Outputs: Hello, my name is Alex.
The this keyword refers to the object the method is part of. In this case, this.firstName is the same as userProfile.firstName.
Organizing Data with Arrays
While objects are great for grouping related properties, arrays are perfect for ordered lists of items. If you wanted to store a list of tasks, a collection of user scores, or the days of the week, you'd use an array.
const weeklyTasks = ["Pay bills", "Go grocery shopping", "Call mom"];
const scores = [98, 85, 91, 78, 88];
You access elements in an array using their index, which is their position in the list. A crucial thing to remember is that JavaScript arrays are zero-indexed, meaning the first element is at index 0, the second is at index 1, and so on.
console.log(weeklyTasks[0]); // Outputs: Pay bills
console.log(scores[2]); // Outputs: 91
Arrays are dynamic. You can easily add or remove items. The most common methods for this are push (add to the end), pop (remove from the end), unshift (add to the beginning), and shift (remove from the beginning).
| Method | Action | Example |
|---|---|---|
push() | Adds one or more elements to the end of an array. | scores.push(100); |
pop() | Removes the last element from an array. | scores.pop(); |
unshift() | Adds one or more elements to the beginning of an array. | scores.unshift(75); |
shift() | Removes the first element from an array. | scores.shift(); |
Powerful Array Methods
Looping through arrays to perform an operation on each element is a very common task. While you can use a standard for loop, JavaScript provides more elegant and readable methods that are built right into arrays. These are often called higher-order functions because they take another function as an argument.
Let's look at three of the most useful ones: map, filter, and reduce.
map(): Transforms each element in an array and returns a new array of the same length.
Imagine you have an array of numbers and you want to create a new array where each number is doubled. Instead of writing a loop, you can use map.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(num) {
return num * 2;
});
// doubledNumbers is now [2, 4, 6, 8, 10]
// The original 'numbers' array is unchanged.
filter(): Creates a new array containing only the elements that pass a test you provide.
Suppose you want to find all the scores above 90 from our earlier scores array. The filter method is perfect for this.
const scores = [98, 85, 91, 78, 88];
const highScores = scores.filter(function(score) {
return score > 90;
});
// highScores is now [98, 91]
reduce(): Executes a function on each element of the array, resulting in a single output value.
The reduce method is a bit different. It's used to boil an array down to a single value. A classic example is summing all the numbers in an array. The function you pass to reduce takes two main arguments: an accumulator (the value being built up) and the currentValue from the array.
const numbers = [1, 2, 3, 4, 5];
// The '0' is the initial value for the accumulator.
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
// sum is now 15
These methods—map, filter, and reduce—are fundamental tools for working with data in JavaScript. They allow you to write code that is more concise, easier to read, and less prone to errors than traditional loops.
What is the primary purpose of a JavaScript object?
Given the object const user = { name: 'Alex', city: 'Berlin' };, how would you access the value 'Berlin' using bracket notation?
Mastering objects and arrays is a huge step in your JavaScript journey. They are the primary ways you will structure and manage data in any application you build.