Javascript
/
Objects
- 1 Fundamentals 11
-
Hello World
-
Code structure
-
Use strict
-
Variables
-
Data types
-
Type conversions
-
Maths
-
Comparitions
-
Conditional
-
Loops
-
Functions
- 2 Testing 2
-
Mocha
-
Nested describe
- 3 Objects 4
-
Basics
-
Reference
-
Methods
-
Constructor
- 4 Types 5
-
Primitives
-
Numbers
-
Strings
-
Arrays
-
Json
- 5 Classes 3
-
Constructor
-
Binding
-
Inheritance
/
Basics
➟
➟
Last update: 25-01-2022
Create
! An object can be created with figure brackets {...} with an optional list of properties.
/**
* Object are created using figure brakets {}
* A property is a (key:value) pair
*/
let A = {};
console.log(A.something); // undefined
let B = {
name: "John",
age: 30, // trailing comma accepted
};
console.log(B.name); // John
console.log(B.age); // 30
delete B.age; // remove a property
console.log(B.age); // undefined
/**
* Computed properties, use square brakets
*/
let myvar = "my key";
let C = {
"some key": 1,
[myvar]: 3,
}
console.log(C[myvar]); // 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.
*
* We can use both normal properties and shorthands ...
* in the same object.
*
*/
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.
/**
* In Javascript you can access non-existing keys.
* The returned value is undefined.
*
* We can test if a property exists using 'in' operator.
*
* There is a special form of loop: for ... in,
* to walk over all keys of an object.
*/
let A = {};
console.log(A.name);
// undefined
let B = {};
console.log('name' in B);
// false
let C = {
'name': 'John',
'age': 30,
};
for (key in C) {
console.log(key + ": " + C[key]);
}
// name: John
// age: 30
➥ Questions github Objects