JavaScript Arrays and Objects cheatsheet
for people like me who cannot remember the basics
Arrays
Basics
- Create an array name myArray:
let myArray = [‘one’, 2, true]
- Access array and store in variable:
let firstValue = myArray[0]
.firstValue
has now the value‘one’
- Create a nested array (arrays within an array):
let myNestedArray = [[“first array”, 1], [“second array”, 2]]
- Access nested arrays:
let secondFirst= myNestedArray[1][0]
.secondFirst
has now the value2
. - Modify specific array index:
myArray[0] = 1;
Manipulate Arrays
Add .push()
to the end.unshift()
to the beginning
Remove.pop()
the end.shift()
beginning.splice(startIndex, how many elements, other values to insert)
middle → modifies original array
Copy.slice(startIndex, stopIndex)
up to, not includinglet newArr = [… oldArr]
(spread operator) → copies entire array, can insert array into another array:
let oldArr = ['hello', 'world'];
let newArr = [1, 2, ...oldArr, 3];console.log(newArr)
→[ 1, 2, 'hello', 'world', 3 ]
Check.indexOf(‘name’)
returns index or -1 if not found
Objects
Basics
- Objects are key-value pairs.
- Create an object :
let person = {
name: “Nicole”,
age: 19
}
- Access object value with key:
person.name
- Change object value:
person.age = 20;
- Add new key-value pair:
person.birthYear = 2002;
- Multiple levels:
let person = {
name: “Nicole”,
age: 19,
"favourite colours": {
first: "blue",
second: "pink",
third: "green"
}}
Dot notationmyObject.key = ‘value’;
Multiple levels works the samemyObject.key.key = ‘value’;
Bracket notationmyObject[‘name of key with space’] = ‘light blue’;
Name of key always in quotes
Must be used when key has a space (e.g. ‘favourite colours’
)
Method property of an object
An object can also have a method stored inside of it:
let person = {
name: “Nicole”,
age: 19,
introduceSelf: function() { return “Hello, my name is ” +
this.name; }
}console.log(person.introduceSelf());
→ Hello, my name is Nicole
Remove keydelete object.keyToDelete;
with example object from above: delete person.age;
Check if object has certain property
hasOwnProperty()
object.hasOwnProperty(‘property name’);
with example object from above: person.hasOwnProperty(‘name’);
→ true
in‘Property name’ in object;
with example object from above: ‘name’ in person;
→ true
for…in — iterate through object by key
for(let xyz in object){
// do something with each key
}
with (as expected) example from above:
for(let x in person){
console.log(person[x]);
}→ Nicole
19
Array of all keyslet array = Object.keys(myObject);
with example from above: let array =Object.keys(person);