My Docs
Search…
Mutability

Mutability && Primitive && Reference Examples

Objects are passed by reference, are mutable, and can be modified by our functions:
1
function rotateLeft(arr, num) {
2
for (let i = 0 ; i < num; i++) {
3
let el = arr.pop();
4
arr.unshift(el);
5
}
6
}
7
let myArr = [1, 2, 3, 4, 5,];
8
rotateLeft(myArr, 2);
9
console.log(myArr);
Copied!
Strings are passed by value, are immutable, and a new array is constructedd and returned, because it cannot be changed in place.
1
function rotateString(str, num) {
2
return str.slice(num) + str.slice(0, num);
3
}
4
​
5
let str = "foobar";
6
let ret = rotateString(str, 3);
7
console.log(str);
8
console.log(ret);
Copied!

Dereferencing

Arrays

To dereference an array, use let [var1, var2] syntax.
1
let arr = ['one', 'two', 'three'];
2
​
3
let [first] = arr;
4
console.log(first);
Copied!

Objects

To dereference attributes from an object, use let {} syntax.
1
let me = {
2
name: "Ian",
3
instruments: ['bass', 'synth', 'guitar'],
4
siblings: {
5
brothers: ['Alistair'],
6
sisters: ['Meghan']
7
}
8
}
9
​
10
let { name, instruments: musical_instruments, siblings: {sisters}} = me;
11
​
12
console.log(sisters);
Copied!
1
function printInstruments({ instruments } ) {
2
console.log(instruments);
3
}
4
printInstruments(me);
5
​
6
function printSiblings({ siblings: {sisters, brothers}}) {
7
console.log("Sisters", sisters);
8
console.log("Brothers", brothers);
9
}
10
​
11
printSiblings(me);
12
​
13
​
14
​
15
//rest parameters
16
// combines parameters into array
17
​
18
...parameterName
19
​
20
splice is an example of where we've seen this before
21
​
22
let arr = 'my dog has fleas'.split(' ');
23
arr.splice(3, 1, 'trees')
24
​
25
​
26
//spread operator
27
// take an arrray and spread them into arguments
28
​
29
...argContainer
30
​
31
OR
32
​
33
// take an object or array and spread their elements/attributes into another object or array
34
​
35
​
36
​
37
function multiply(multiplier, ...theArgs) {
38
return theArgs.map(function(element) {
39
return multiplier * element
40
})
41
}
42
​
43
let arr = multiply(2, 1, 2, 3)
44
console.log(arr)
45
​
46
​
47
​
48
​
49
let me = {
50
name: "Ian",
51
instruments: ['bass', 'synth', 'guitar'],
52
siblings: {
53
brothers: ['Alistair'],
54
sisters: ['Meghan']
55
}
56
}
57
​
58
let countryArr = ['USA', 'Canada', 'UK'];
59
//me[countries] = countryArr;
60
​
61
let myCountries = {
62
'countries': countryArr
63
};
64
​
65
let newMe = {...me, ...countries}
Copied!
Last modified 2mo ago