Skip to main content

Objects

@serverSerrverlesskiy

Objects are like a closet for storing and transporting other types of data. JavaScript is designed around a simple paradigm. The concept is based on simple objects. An object is a collection of properties, and each property consists of a name (key) and a value associated with that name. The property value can be a function⚙️, which can be called a method of an object, or any other type.

Object

In this article, we'll cover the most basic properties of JavaScript objects, creating and modifying, and enumerating properties.

An object in JavaScript is a simple associative array or, in other words, a "hash". It stores any key: value matches and has several standard methods.

Objects in JavaScript, like objects in real life (a person, a bus, a building, etc.) have several named (key🗝️) parameters (age, name, hair color, status) with specific values (15, John, black, 'true') :

let obj = {
age: 15,
name: 'John',
color: 'black',
student: true
}

An object method in JavaScript is simply a function️ that is added to an associative array.

Live Editor
Result
Loading...

Object creation

Object

In a computer ️ we can represent an object as a cabinet with names-properties (access keys) signed on it. Inside the cabinet drawers - data (specific information) and even smaller objects, by analogy with things. It is easy to find, delete or add (write) a new value to it by the key.

obj01

These are two 2️⃣ options for creating an empty object:

// equivalent records
let obj = {}
let person = new Object()

The second option is very rarely used in practice.

obj00

Advanced creation

Extended

Properties can be specified directly when creating an object, through a list in curly braces like {..., key: value, ...} and create complex objects:

Live Editor
Result
Loading...

The created object contains five properties with specific values, one of which is passport data, which is a built-in object. Notice how the call to distant properties or methods of the object goes. Try to return your passport number.

Adding properties

Adding

There are two 2️⃣ syntax for adding properties to an object. 1️⃣ The first is a period, the second is square brackets:

// equivalent records
obj.age = 15
obj['age'] = 15
Live Editor
Result
Loading...

Square brackets are mainly used when the properties' name is in a variable` :

let nameProp = 'age'
obj[nameProp] = 15

Here, through the variable nameProp, we set the name of the property"age", which is the key in the associative array that contains value 15.

Live Editor
Result
Loading...

Accessing properties

Door

The property is accessed by accessing it :

Live Editor
Result
Loading...

If the object has no such property, the result is undefined. Check it in your browser console.

let obj = {}
obj.nokey

nokey

There will be no error when accessing a property that does not exist, the special value undefined will simply return. If there is no return keyword inside the function, then the undefined value will also return - the absence of something.

Removing properties

Delete

Deletes ➖ property operator delete. Try to remove the passport number from the previous example:

Create the object from the previous example in the console.

const obj = {
age: 15,
name: 'John',
color: 'black',
passport: {
serial: 5721,
number: 258963,
date: '27.10.2015'
},
student: true
}

Now remove the nested passport object

delete obj.passport

Now if you refer to it, then the result will be undefined

obj.passport

delete obj

Object Methods

Description

As with other languages , JavaScript objects have methods.

For example, let's create a sport object right away with the run method:

Live Editor
Result
Loading...

Adding a method

Add

Adding a method to an existing object is simple, assign the function⚙️ function (n) {...} to the sport.run property.

Live Editor
Result
Loading...

This is not about classes, instantiation, and the like. Simple - you can add a new method or delete an existing one to any object at any time.

Looping through object properties

enumeration

To iterate over all the properties of an object, a special type of for .. in construction is used:

for(let key in obj) {
// key - property name
// obj [key] - property value
...
}

For example :

Live Editor
Result
Loading...

And secretly, to be honest, almost any variable is a mini-object in the JavaScript environment. So, don't be afraid to use them.

EnglishMoji!

Problems?

Problem

Write to Discord chat.

Questions:

Question

An empty object is created with the command:

  1. let obj = {}
  2. function obj()
  3. let x = 10

The object stores matches:

  1. key: value
  2. name: surname
  3. variable = value

The syntax for assigning a value to a specific key (property):

  1. color () = "green"
  2. obj.color =" red "
  3. function color () =>" yellow "

An object method in JavaScript is

  1. Just a function added to an associative array
  2. External function
  3. Variable described outside the object

Looping through object properties

  1. for (let i = 0; i <= 100; i ++) {sum + = i}
  2. for (let key in obj) {}
  3. while (condition) {}

In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.

EnglishMoji!

  1. MDN web doc. Developer.mozilla.org - Статья "Типы данных JavaScript и структуры данных"
  2. MDN web doc. Developer.mozilla.org - Статья "Инициализация объектов"
  3. Статья "Object Types"
  4. Статья "Объекты", сайт Learn.javascript.ru
  5. Code for Teens: The Perfect Beginner's Guide to Programming, Volume 1: Javascript - Jeremy Moritz

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Dmitriy K.


Dmitriy Vasilev

💵

Resoner2005

🐛 🎨 🖋

Navernoss

🖋 🐛 🎨