9.Learn JavaScript_ Objects Cheatsheet _ Codecademy
9.Learn JavaScript_ Objects Cheatsheet _ Codecademy
Objects
console.log(cat.whatName());
// Output: Pipey
JavaScript getter and setter methods are helpful in part const myCat = {
because they offer a way to intercept property access
_name: 'Snickers',
and assignment, and allow for additional actions to be
performed before these changes go into effect. get name(){
return this._name
},
set name(newName){
//Verify that newName is a non-empty
string before setting as name property
if (typeof newName === 'string' &&
newName.length > 0){
this._name = newName;
} else {
console.log("ERROR: name must be a
non-empty string");
}
}
}
javascript factory functions
A JavaScript function that returns an object is known as // A factory function that accepts
a factory function. Factory functions often accept
'name',
parameters in order to customize the returned object.
// 'age', and 'breed' parameters to
return
// a customized dog object.
const dogFactory = (name, age, breed) =>
{
return {
name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');
}
};
};
JavaScript object key names must adhere to some // Example of invalid key names
restrictions to be valid. Key names must either be
const trainSchedule = {
strings or valid identifier or variable names (i.e. special
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
console.log(classElection.place); //
undefined
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.
JavaScript for...in loop
console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
javascript passing objects as arguments
changeItUp(origNum, origObj);
JavaScript objects may have property values that are const engine = {
functions. These are referred to as object methods.
// method shorthand, with one argument
Methods may be defined using anonymous arrow
function expressions, or with shorthand method syntax. start(adverb) {
Object methods are invoked with the syntax: console.log(`The engine starts up
objectName.methodName(arguments) .
${adverb}...`);
},
// anonymous arrow function expression
with no arguments
sputter: () => {
console.log('The engine
sputters...');
},
};
engine.start('noisily');
engine.sputter();
/* Console output:
The engine starts up noisily...
The engine sputters...
*/
Print Share