Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5K views

Learn JavaScript - Objects Cheatsheet - Codecademy

The document provides examples and explanations of JavaScript object concepts including destructuring assignment, shorthand property syntax, the this keyword, arrow functions, getters and setters, and factory functions. Destructuring allows extracting values from objects into variables. Shorthand syntax omits explicitly specifying property names when creating objects. The this keyword refers to the calling object. Arrow functions use the this from the enclosing context rather than having their own. Getters and setters intercept property access. Factory functions return customized objects.

Uploaded by

bilal.a6t9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5K views

Learn JavaScript - Objects Cheatsheet - Codecademy

The document provides examples and explanations of JavaScript object concepts including destructuring assignment, shorthand property syntax, the this keyword, arrow functions, getters and setters, and factory functions. Destructuring allows extracting values from objects into variables. Shorthand syntax omits explicitly specifying property names when creating objects. The this keyword refers to the calling object. Arrow functions use the this from the enclosing context rather than having their own. Getters and setters intercept property access. Factory functions return customized objects.

Uploaded by

bilal.a6t9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

Cheatsheets / Learn JavaScript

Objects

JavaScript destructuring assignment shorthand syntax

The JavaScript destructuring assignment is a shorthand const rubiksCubeFacts = {


syntax that allows object properties to be extracted into
possiblePermutations:
specific variable values.
It uses a pair of curly braces ( {} ) with property names '43,252,003,274,489,856,000',
on the left-hand side of an assignment to extract values invented: '1974',
from objects. The number of variables can be less than
largestCube: '17x17x17'
the total properties of an object.
};
const {possiblePermutations, invented,
largestCube} = rubiksCubeFacts;
console.log(possiblePermutations); //
'43,252,003,274,489,856,000'
console.log(invented); // '1974'
console.log(largestCube); // '17x17x17'

shorthand property name syntax for object creation

The shorthand property name syntax in JavaScript allows const activity = 'Surfing';
creating objects without explicitly specifying the property
const beach = { activity };
names (ie. explicitly declaring the value after the key). In
this process, an object is created where the property console.log(beach); // { activity:
names of that object match variables which already exist 'Surfing' }
in that context. Shorthand property names populate an
object with a key matching the identifier and a value
matching the identifier’s value.

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 1/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

this Keyword

The reserved keyword this refers to a method’s calling const cat = {


object, and it can be used to access properties belonging
name: 'Pipey',
to that object.
Here, using the this keyword inside the object function age: 8,
to refer to the cat object and access its name whatName() {
property.
return this.name
}
};

console.log(cat.whatName());
// Output: Pipey

javascript function this

Every JavaScript function or method has a this context. const restaurant = {


For a function defined inside of an object, this will refer
numCustomers: 45,
to that object itself. For a function defined outside of an
object, this will refer to the global object ( window in a seatCapacity: 100,
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;
}
}

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 2/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

JavaScript Arrow Function this Scope

JavaScript arrow functions do not have their own this const myObj = {
context, but use the this of the surrounding lexical
data: 'abc',
context. Thus, they are generally a poor choice for writing
object methods. loggerA: () => {
Consider the example code: console.log(this.data); },
loggerA is a property that uses arrow notation to
loggerB() { console.log(this.data); },
define the function. Since data does not exist in the
};
global context, accessing this.data returns undefined .
loggerB uses method syntax. Since this refers to the
enclosing object, the value of the data property is myObj.loggerA(); // undefined
accessed as expected, returning "abc" .
myObj.loggerB(); // 'abc'

getters and setters intercept property access

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");
}
}
}

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 3/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

javascript factory functions

A JavaScript function that returns an object is known as a // A factory function that accepts 'name',
factory function. Factory functions often accept
// 'age', and 'breed' parameters to return
parameters in order to customize the returned object.
// a customized dog object.
const dogFactory = (name, age, breed) => {
return {
name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');
}
};
};

javascript getters and setters restricted

JavaScript object properties are not private or protected. const myCat = {


Since JavaScript objects are passed by reference, there is
_name: 'Dottie',
no way to fully prevent incorrect interactions with object
properties. get name() {
One way to implement more restricted interactions with return this._name;
object properties is to use getter and setter methods.
},
Typically, the internal value is stored as a property with an
identifier that matches the getter and setter method set name(newName) {
names, but begins with an underscore ( _ ). this._name = newName;
}
};

// Reference invokes the getter


console.log(myCat.name);

// Assignment invokes the setter


myCat.name = 'Yankee';

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 4/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

Restrictions in Naming Properties

JavaScript object key names must adhere to some // Example of invalid key names
restrictions to be valid. Key names must either be strings
const trainSchedule = {
or valid identifier or variable names (i.e. special
characters such as - are not allowed in key names that platform num: 10, // Invalid because of
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.
}

Dot Notation for Accessing Object Properties

Properties of a JavaScript object can be accessed using const apple = {


the dot notation in this manner: object.propertyName .
color: 'Green',
Nested properties of an object can be accessed by
chaining key names in the correct order. price: {
bulk: '$3/kg',
smallQty: '$4/kg'
}
};
console.log(apple.color); // 'Green'
console.log(apple.price.bulk); // '$3/kg'

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.

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 5/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

Accessing non-existent JavaScript properties

When trying to access a JavaScript object property that const classElection = {


has not been defined yet, the value of undefined will be
date: 'January 12'
returned by default.
};

console.log(classElection.place); //
undefined

JavaScript Objects are Mutable

JavaScript objects are mutable, meaning their contents const student = {


can be changed, even when they are declared as const .
name: 'Sheldon',
New properties can be added, and existing 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.

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 6/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

JavaScript for...in loop

The JavaScript for...in loop can be used to iterate over let mobile = {
the keys of an object. In each iteration, one of the
brand: 'Samsung',
properties from the object is assigned to the variable of
that loop. model: 'Galaxy Note 9'
};

for (let key in mobile) {


console.log(`${key}: ${mobile[key]}`);
}

Properties and values of a JavaScript object

A JavaScript object literal is enclosed with curly braces const classOf2018 = {


{} . Values are mapped to keys in the object with a colon
students: 38,
( : ), and the key-value pairs are separated by commas. All
the keys are unique, but values are not. year: 2018
Key-value pairs of an object are also referred to as }
properties.

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 7/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

Delete operator

Once an object is created in JavaScript, it is possible to const person = {


remove properties from the object using the delete
firstName: "Matilda",
operator. The delete keyword deletes both the value of
the property and the property itself from the object. The age: 27,
delete operator only works on properties, not on hobby: "knitting",
variables or functions.
goal: "learning JavaScript"
};

delete person.hobby; // or delete


person[hobby];

console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 8/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

javascript passing objects as arguments

When JavaScript objects are passed as arguments to const origNum = 8;


functions or methods, they are passed by reference, not
const origObj = {color: 'blue'};
by value. This means that the object itself (not a copy) is
accessible and mutable (can be changed) inside that
function. const changeItUp = (num, obj) => {
num = 7;
obj.color = 'red';
};

changeItUp(origNum, origObj);

// Will output 8 since integers are passed


by value.
console.log(origNum);

// Will output 'red' since objects are


passed
// by reference and are therefore mutable.
console.log(origObj.color);

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 9/10
1/18/24, 10:43 AM Learn JavaScript: Objects Cheatsheet | Codecademy

JavaScript Object Methods

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

https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-objects/cheatsheet 10/10

You might also like