Javascript
/
Objects
- 1 Fundamentals 11
-
Hello World S
-
Code structure S
-
Use strict S
-
Variables S
-
Data types S
-
Type conversions S
-
Maths S
-
Comparitions S
-
Conditional S
-
Loops S
-
Functions S
- 2 Testing 2
-
Mocha S
-
Nested describe S
- 3 Objects 4
-
Basics S
-
Reference S
-
Methods S
-
Constructor S
- 4 Types 5
-
Primitives S
-
Numbers S
-
Strings S
-
Arrays S
-
Json S
- 5 Classes 3
-
Constructor S
-
Binding S
-
Inheritance S
S
R
Q
Javascript Objects Basics
Object are created using figure brakets {} A property is a (key:value) pair Computed properties, use square brakets let A = { age: 30, [myvar]: 3, } for (key in A) // A[key]Objects
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
➥ Questions