JavaScript Objects

Objects are ways of storing data in JavaScript and are a key part of Object Oriented Programming. Learn the syntax and more about them in this article…

Oktober 14, 2024 - 20:17
 0  8

Objects are ways of storing data in JavaScript and are a key part of Object Oriented Programming. Learn the syntax and more about them in this article…

While it’s not completely necessary, a basic understanding of JavaScript arrays may help you understand objects.

What is an object?

An object in JavaScript is quite similar to an array — it is a data type which stores lots of values. These values can be any data type — numbers, strings, booleans, functions, and even arrays and objects!

The difference between an array and an object is how the values are referenced. In an array, you reference a value with a number (its position in the array) — for example:

myArray[3]

When referencing a value in an object, you do so using a name instead of a number. For example:

myObject['superFlashyName']

That’s it! Name instead of number.

How to declare an object

The syntax for declaring an object is different to the syntax for an array. Here’s what it looks like:

var myFriend = {firstName: 'John', lastName: 'Smith', age: 27, nationality: 'British'};

As you can see, it’s kind of similar to the array syntax, but it has curly brackets instead of square brackets. The items are still comma-separated. However, the items now have a ‘name’ as well as a value. For example:

age: 27

Here, age is the name (aka ‘key’) of the item and 27 is the item’s value. They are separated by a colon.

We call this a key-value pair. It has a key and a value… (really?

Apa Reaksimu?

like

dislike

love

funny

angry

sad

wow

ahmadsofyan Saya hanya manusia biasa, kesempurnaan hanya milik allah swt.