Learn JavaScript - Objects Cheatsheet - Codecademy
Learn JavaScript - Objects Cheatsheet - Codecademy
Learn JavaScript - Objects Cheatsheet - Codecademy
Objects
Restrictions in Naming Properties
JavaScript object key names must adhere to some
restrictions to be valid. Key names must either be // Example of invalid key names
strings or valid identifier or variable names (i.e. special const trainSchedule = {
characters such as - are not allowed in key names platform num: 10, // Invalid because of
that are not strings).
the space between words.
40 - 10 + 2: 30, // Expressions cannot
be keys.
+compartment: 'C' // The use of a +
sign is invalid unless it is enclosed in
quotations.
}
Objects
An object is a built-in data type for storing key-value
pairs. Data inside objects are unordered, and the values
can be of any type.
console.log(classElection.place); //
undefined
JavaScript Objects are Mutable
JavaScript objects are mutable, meaning their contents
can be changed, even when they are declared as const student = {
const . New properties can be added, and existing name: 'Sheldon',
property values can be changed or deleted. score: 100,
It is the reference to the object, bound to the variable, grade: 'A',
that cannot be changed.
}
console.log(student)
// { name: 'Sheldon', score: 100, grade:
'A' }
delete student.score
student.grade = 'F'
console.log(student)
// { name: 'Sheldon', grade: 'F' }
student = {}
// TypeError: Assignment to constant
variable.
console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
changeItUp(origNum, origObj);
engine.start('noisily');
engine.sputter();
/* Console output:
The engine starts up noisily...
The engine sputters...
*/
this Keyword
The reserved keyword this refers to a method’s
calling object, and it can be used to access properties const cat = {
belonging to that object. name: 'Pipey',
Here, using the this keyword inside the object age: 8,
function to refer to the cat object and access its whatName() {
name property.
return this.name
}
};
console.log(cat.whatName());
// Output: Pipey
javascript function this
Every JavaScript function or method has a this
context. For a function defined inside of an object, const restaurant = {
this will refer to that object itself. For a function numCustomers: 45,
defined outside of an object, this will refer to the seatCapacity: 100,
global object ( window in a browser, global in Node.js). availableSeats() {
// this refers to the restaurant
object
// and it's used to access its
properties
return this.seatCapacity
- this.numCustomers;
}
}