Objects
Let user = { // an object
name: "John", // by key "name" store value "John"
age: 30 // by key "age" store value 30
};
Let fruit = prompt("Which fruit to buy?", "apple");
let bag = {
*!*
[fruit]: 5, // the name of the property is taken from the variable fruit
*/!*
};
alert( bag.apple ); // 5 if fruit="apple"
- Are used to store keyed collections of various data and more complex entities.
- We can immediately put some properties into {...} as "key: value" pairs.
- We can use square brackets in an object literal. That's called computed properties.
- A notable feature is that it's possible to access any property. There will be no error if the property doesn't exist! Accessing a non-existing property just returns undefined.
- One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference".
- Is capable of storing multiple values as properties.
- For more complex data structures.
Syntax
Let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax
Can be created with figure brackets {…} with an optional list of properties. A property is a "key: value" pair, where key is a string (also called a "property name"), and value can be anything.
Related concepts
→
Objects
→
- NULL
- Symbol
- Garbage collector
- Object methods "this"
- Object methods "this": Method examples
- Object methods "this": Method shorthand
- ToPrimitive
- arr.find
- Map
- ToJSON
- Prototypal inheritance
- Class
- Functional pattern
- Prototype-based pattern
- Instanceof
- Try..catch
- Document Object Model (DOM)
- Browser Object Model (BOM)
- Functions
- Array
- Date and time
- Accessor properties