minte9
LearnRemember



Create

An object can be created with figure brackets {...} with an optional list of properties.
 
/**
 * Create object
 * 
 * Object are created using figure brakets {}
 * A property is a (key:value) pair
 */

let A = {};
let B = {
    name: "John",
    age: 30,  // trailing comma accepted
};
let x = "mykey";
let C = {
    "some key": 1,
    [x]: 3, // computed properties
}

console.log(A.something);   // undefined
console.log(B.name);        // John
console.log(C['mykey'])     // 3

Shorthand

It is very common to make a property from a variable.
 
/**
 * Property value shorthand
 * 
 * The use-case of making a property from a variable is so common, 
 * that is a special property value shorthand to make it shorter
 * 
 */

function makeUser(name, age) {
    return {
        name, // same as, name: name
        age,
        tasks: 10,
    };
}

let user = makeUser("Marry", 18);

console.log(user.age);      // 18  
console.log(user.tasks);    // 10

For ... in

In Javascript you can access any properties, even if doesn't exists.
 
/**
 * Object's keys
 * 
 * Walk over all keys of an object, with for/in loop
 * Test if a property exists with 'in' operator
 */

let A = {
    'name': 'John',
    'age': 30,
};


for (key in A) {
    console.log(C[key]); // John 30
}
console.log('xyz' in A); // false



  Last update: 210 days ago