Javascript Objects and Javascript arrays are two of the most important data structures in JavaScript. They are used to store and organize data in a variety of ways, and they are essential for building complex web applications.
Objects are used to represent real-world things, such as users, products, or posts. They are made up of properties, which are pairs of keys and values. For example, a user object might have properties for the user’s name, email address, and profile picture.
Arrays are used to store lists of data. Each item in an array has a numerical index, which is used to access the item. For example, an array of products might contain objects for each product, with each object containing information such as the product name, price, and description.
Here are some of the benefits of working with objects and arrays in JavaScript:
By the end of this post, you will have a good understanding of how to work with objects and arrays in JavaScript, and you will be able to use these data structures to build more powerful and efficient web applications.
There are two ways to access object properties in JavaScript: dot notation and bracket notation.
Dot notation is the simplest way to access object properties. It involves using a dot (.
) to separate the object name from the property name. For example, to access the name
property of the person
object, you would use the following syntax:
const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
const personName = person.name;
Bracket notation is more flexible than dot notation, but it is also more verbose. It involves using square brackets ([]
) to enclose the property name. This allows you to access properties that are not valid JavaScript identifiers, such as properties that contain spaces or special characters. For example, to access the occupation
property of the person
object using bracket notation, you would use the following syntax:
const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
const personOccupation = person["occupation"];
Here are some examples of how to use dot notation and bracket notation to access object properties:
// Dot notation
const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
const personName = person.name;
const personAge = person.age;
const personOccupation = person.occupation;
// Bracket notation
const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
const personName = person["name"];
const personAge = person["age"];
const personOccupation = person["occupation"];
There are two ways to create objects in JavaScript: object literal notation and constructor functions.
Object literal notation is the most common way to create objects in JavaScript. It involves using curly braces ({}
) to enclose a list of key-value pairs. The keys are the property names, and the values are the property values.
For example, to create an object for a person, you would use the following syntax:
const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
Constructor functions are another way to create objects in JavaScript. They are more verbose than object literal notation, but they offer more flexibility. To create a constructor function, you use the function
keyword to define a function with a constructor body. The constructor body is the code that will be executed when a new object is created using the constructor function.
For example, to create a constructor function for a person, you would use the following syntax:
function Person(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
To create a new object using a constructor function, you use the new
keyword followed by the name of the constructor function and the arguments that you want to pass to the constructor function.
For example, to create a new person object using the Person
constructor function, you would look like this:
const person = new Person("John Doe", 30, "Software Engineer");
Once you have created an object, you can use it in your code by accessing its properties and methods. To access a property, you use the dot notation or the bracket notation. To access a method, you use the dot notation followed by the name of the method.
Here is an example of how to create and use an object in JavaScript:
// Create a person object using object literal notation
const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
// Access the person's name
const personName = person.name;
// Access the person's occupation
const personOccupation = person.occupation;
// Create a person object using a constructor function
function Person(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
this.greet = function() {
console.log(`Hello, my name is ${this.name}.`);
};
}
const anotherPerson = new Person("Jane Doe", 25, "Web Developer");
// Access the person's name
const anotherPersonName = anotherPerson.name;
// Access the person's occupation
const anotherPersonOccupation = anotherPerson.occupation;
// Call the person's greet() method
anotherPerson.greet();
This code will create two person objects, one using object literal notation and the other using a constructor function. It will then access the properties and methods of the objects and call the greet()
method on both objects.
JavaScript arrays are like an organised lists of things, and each item in the list gets a special number, which we call an index. The first item starts with index 0, and the last one’s index is the total number of items minus 1.
To grab one of these items from the list, you use square brackets like this: ([]
). Inside those brackets, you put the number of the item you want. So, if you want the very first item, you’d do something like this:
const myArray = [1, 2, 3, 4, 5];
const firstElement = myArray[0]; // 1
To access the last element in an array, you’d do something like this:
const myArray = [1, 2, 3, 4, 5];
const lastElement = myArray[myArray.length - 1]; // 5
You can also use square brackets to get information about arrays. For instance, the “length” property of an array tells you how many things are in it. To find the length of an array, you’d do something like this:
const myArray = [1, 2, 3, 4, 5];
const arrayLength = myArray.length; // 5
In JavaScript, there’s a handy tool called the forEach()
method. It’s like a built-in helper that lets you go through an array and look at each item. To make it work, you need to give it a special function to do something with each item. This function is called a callback, and it gets the item’s position in the array as a parameter.
Here’s how you’d use the forEach()
method to loop through an array and check out its items:
myArray.forEach((element, index) => {
// Do something with the element
});
For instance, in the following code, we’ve employed the forEach()
method to stroll through the myArray
and display each item within it on the console:
const myArray = [1, 2, 3, 4, 5];
myArray.forEach((element, index) => {
console.log(element);
});
// 1
// 2
// 3
// 4
// 5
The forEach()
method is like a Swiss Army knife for dealing with arrays. It’s your go-to for doing all sorts of things with the stuff inside an array, like picking out specific items, putting them in order, or changing them in some way.
The filter()
method is like a virtual sieve for your arrays. It’s a built-in tool in JavaScript that lets you make a new array with only the items that meet certain requirements. You provide a special function as a filter, and it gets called for each item in the array. If the function gives a thumbs-up (a truthy value), the item makes it into the new array.
If you want to level up, check out this post.
Here’s how you’d work this magic with the filter()
method:
const newArray = myArray.filter((element, index) => {
// Return a truthy value to include the element in the new array
});
The filter()
method is a versatile tool that allows you to craft new arrays in numerous ways. You can use it to gather items that meet specific conditions, like those greater or smaller than a certain value, items containing a particular string, or any other criteria you set up in your callback function.
Here are some examples of how to use the filter()
method to filter arrays based on various conditions:
// Filter an array to only include items that are greater than 10
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const filteredArray = myArray.filter((element) => element > 10);
// Filter an array to only include items that are less than 5
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const filteredArray = myArray.filter((element) => element < 5);
// Filter an array to only include items that contain the string "foo"
const myArray = ["foo", "bar", "baz", "qux"];
const filteredArray = myArray.filter((element) => element.includes("foo"));
// Filter an array to only include items that have a property "name" equal to "John Doe"
const myArray = [{ name: "John Doe" }, { name: "Jane Doe" }, { name: "Peter Parker" }];
const filteredArray = myArray.filter((element) => element.name === "John Doe");
The filter()
method is a powerful tool for filtering arrays and creating new arrays based on specific criteria. It can be used to perform a variety of tasks, such as cleaning data, preparing data for analysis, and creating dynamic user interfaces.
The filter()
method returns a new array, without modifying the original array. This is known as immutability.
Immutability in JavaScript is like a rule that says once you create something, you can’t directly change it. Instead, if you want to make a change, you create a new version with the modifications. It’s similar to having an old book that you don’t want to write in. So, if you need to add a note or make a change, you copy the page, make the edits in the copy, and leave the original book untouched. This approach helps keep your original data safe and predictable. We use immutability when we want to be extra careful with our data.
Example
The following example shows how to use the filter()
method to filter an array and create a new array without modifying the original array:
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter the array to only include items that are greater than 10
const filteredArray = myArray.filter((element) => element > 10);
// The original array is still intact
console.log(myArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// The filtered array contains only items that are greater than 10
console.log(filteredArray); // [11, 12]
Immutability has a number of benefits, including:
How to filter arrays based on their index
To filter arrays based on their index, you can use the filter()
method with a callback function that checks the index of the element.
The callback function for the filter()
method takes two arguments: the element and the index. The index argument is the index of the element in the array.
To filter the array based on the index, you can simply return true
from the callback function if the index matches the criteria that you are looking for.
Examples of filtering arrays by index using filter
The following example shows how to filter an array to only include items that have an even index:
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter the array to only include items that have an even index
const filteredArray = myArray.filter((element, index) => index % 2 === 0);
// The filtered array contains only items that have an even index
console.log(filteredArray); // [2, 4, 6, 8, 10]
The following example shows how to filter an array to only include items that have an index that is greater than or equal to 5:
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter the array to only include items that have an index that is greater than or equal to 5
const filteredArray = myArray.filter((element, index) => index >= 5);
// The filtered array contains only items that have an index that is greater than or equal to 5
console.log(filteredArray); // [6, 7, 8, 9, 10]
Object properties and array filtering are essential for working with data in JavaScript. By mastering these concepts, you can write more efficient, effective, and maintainable code.
Why is it important?
I encourage you to continue learning about object properties and array filtering.
Leave a Reply