> For the complete documentation index, see [llms.txt](https://strctr.gitbook.io/programming/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://strctr.gitbook.io/programming/01-languages/javascript/01-language/b-structured/b2-objects/01-object-creation.md).

# 01. Object Creation

Объекты можно создавать:

* Через литерал объектов `{}`,
* При помощи функции `Object.create(prototype)`.
* При помощи функции-конструктора `new Object()`,

Три способа создать пустой объект в JS:

```javascript
const o1 = {};
const o2 = Object.create(null);
const o2 = new Object();
```

## Object Literal Syntax

* В фигурных скобках перечисляется объект и его синтаксис.
* Можно дублировать свойства имен, при этом свойство с новым именем перезапишет свойство со старым именем.

### Notation in ES5

```javascript
var o1 = {};
var o2 = {
  a: "foo", // value is string
  b: 42, // value is number
  c: {} // value is other object
};

var a = "foo",
  b = 42,
  c = {};
var o3 = { a: a, b: b, c: c };

var o4 = {
  property: function([parameters]) {},
  get property() {},
  set property(value) {},
  generatorMethod: function*() {}
};
```

### Notation in ES6+

When evaluating the property name from an expression, place the code into square brackets `{[expression]: value}`. The expression evaluation result becomes the property name.

```javascript
// Shorthand property names (ES6)
const a = "foo", b = 42, c = {};
const o = { a, b, c };

// Shorthand method names (ES6)
const o = {
  property([parameters]) {},
  get property() {},
  set property(value) {},
  * generator() {}
  ...O
};

// Computed property names (ES6)
const prop = "foo";
const o = {
};
```

We can evaluate function name:

```javascript
const methodName = "getFirstName";
const user = {
  // в квадратных скобках может быть любое выражение,
  // которое должно вернуть название метода
  [methodName]() {
    // вместо [methodName]: function() {
    return "Anton";
  }
};

user.getFirstName(); // Anton
```

Expression can be used to evaluate property names:

```javascript
const prefix = (prefStr, name) => prefStr + "_" + name;

const object = {};
object[prefix("number", "pi")] = 3.14;
object[prefix("bool", "false")] = false;

object; // => { number_pi: 3.14, bool_false: false }
```

## `Object.create()`

Метод `Object.create(proto, ?propertiesObject)` создаёт новый объект с указанными объектом прототипа и свойствами.

```javascript
const o1 = {};
// эквивалентно этому:
const o2 = Object.create(Object.prototype);
```

## `Object.fromEntries()`

Создает новый объект из массива entries. Противоположность `Object.entries`.&#x20;

```javascript
Object.fromEntries([['foo',1], ['bar',2]]);
//  {
//    foo: 1,
//    bar: 2,
//  }
```

`Object.fromEntries()` is flexible: It accepts iterables (which includes Arrays and is consistent with `new Map()` etc.). Its \[key,value] pairs are only required to be objects that have properties with the keys `'0'` and `'1'` (which includes 2-element Arrays).

## `Object()` constructor

Конструктор `Object` создаёт объект-обёртку для переданного значения. Если значением является `null` или `undefined`, создаёт и возвращает пустой объект, в противном случае возвращает объект такого типа, который соответствует переданному значению. Если значение уже является объектом, конструктор вернёт это значение. При вызове как не конструктор, `Object` ведёт себя идентично коду `new Object()`.

Преобразование в объект выполняется функцией `Object()`:

* `Object()` без параметров возвращает `{}`
* `Object(undefined)` или `Object(null)` возвращает `{}`
* `Object(bool) => new Boolean(bool)`
* `Object(num) => new Number(num)`
* `Object(str) => new Boolean(String)`
* `Object(obj) => obj`

```javascript
new Object(3); // => new Number(3)
new Object(); // => {}
```
