Understanding Objects
Explore how JavaScript objects store data with key-value pairs, access and modify properties using dot and bracket notation, and utilize built-in methods like Object.keys and Object.freeze. Understand techniques to manipulate objects efficiently and practice best coding practices to handle data in your web projects.
We'll cover the following...
Objects in JavaScript are versatile data structures that allow us to store and organize data as key-value pairs. A key is a unique identifier (usually a string or symbol), and its associated value can be any JavaScript data type, including numbers, strings, arrays, other objects, or functions.
Creating an object
The syntax for defining objects in JavaScript is given below.
const objectName = {key1: value1,key2: value2,key3: value3};
Let’s create a car object to illustrate how objects work:
const car = {brand: "Toyota",model: "Corolla",year: 2022,start: function() {console.log("Car started!");}};
In the above code:
Properties: The
brand,model, andyearare key-value pairs.Method: The
startis a function that belongs to thecarobject.
We can access the data stored in these objects in the following ways.
Dot notation:
car.brandreturns ...