Objects
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.
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.
Object creation
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
.
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.
Advanced creation
Properties can be specified directly when creating an object, through a list in curly braces like {..., key: value,
...} and create complex objects:
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
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
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
.
Accessing properties
The property is accessed by accessing it :
If the object has no such property, the result is undefined
. Check it in your browser console.
let obj = {}
obj.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
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
Object Methods
As with other languages , JavaScript objects have methods
.
For example, let's create a sport
object right away with the run
method:
Adding a method
Adding a method to an existing object is simple, assign the function⚙️ function (n) {...}
to the sport.run
property.
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
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 :
And secretly, to be honest, almost any variable is a mini-object in the JavaScript environment. So, don't be afraid to use them.
Problems?
Write to Discord chat.
Questions:
An empty object is created with the command:
let obj = {}
function obj()
let x = 10
The object stores matches:
- key: value
- name: surname
- variable = value
The syntax for assigning a value to a specific key (property):
color () = "green"
obj.color =" red "
function color () =>" yellow "
An object method in JavaScript is
- Just a function added to an associative array
- External function
- Variable described outside the object
Looping through object properties
for (let i = 0; i <= 100; i ++) {sum + = i}
for (let key in obj) {}
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.
Links
- MDN web doc. Developer.mozilla.org - Статья "Типы данных JavaScript и структуры данных"
- MDN web doc. Developer.mozilla.org - Статья "Инициализация объектов"
- Статья "Object Types"
- Статья "Объекты", сайт Learn.javascript.ru
- 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 🖋 🐛 🎨 |