Objects can be created two ways: Object constructor Object literal
let user = new Object(); //object constructor let user = {}; //object literal
let user = { //an object name: "Raymond" //key is the name and value is John age: 20
};
//Its important to note that objects can be removed, added, and read:
As we noted above USER is the object which has keys and values.
The way to access properties and values is by using the dot notation for instance:
console.log(user.name); //Raymond console.log(user.age); //20
delete user.age;
Another important note properties names can be multi-word using a quote
let user = { name: "Raymond" age: 20, "likes dogs": true //As you see multi-word quoted };
function newUser(name, age){ return{ name: name, age: age,
};
}
let user = newUser("Raymond", 20); console.log(user.name);
function newUser(name, age) { return { name, age, }; }
///
let user = {name: "Raymond", age: 20};
console.log("age" in user); console.log("name" in user);
This kind of loop is different than the other loops
for (key in object) { //executes the body for each key among object properties }
let user = { name: "John", age: 30, isAdmin: true };
for (let key in user) { // keys console.log( key ); // name, age, isAdmin // values for the keys console.log( user[key] ); // John, 30, true }
In this example it whenever a property has quotation mark even though its a number it takes it in order
let codes = { "49": "Germany", "41": "Switzerland", "44": "Great Britain", // .., "1": "USA" };
for (let code in codes) { alert(code); // 1, 41, 44, 49 }
let codes = { "+49": "Germany", "+41": "Switzerland", "+44": "Great Britain", // .., "+1": "USA" };
for (let code in codes) { alert( +code ); // 49, 41, 44, 1 }