- Copy by reference vs copy by value Strings and numbers are passed by value. Arrays and objects are passed by reference. -- Example
// Nums
> a = 0
0
> b = a
0
> a = 1
1
> b
0
// Objects
> a = {}
{}
> b = a
{}
> a[1] = 'hi'
'hi'
> a
{ '1': 'hi' }
> b
{ '1': 'hi' }
-- Solutions:
// Use Object.assign(<empty object>, objToCopy)
> a = {}
{}
> a[1] = 'hi'
'hi'
> b = Object.assign({}, a)
{ '1': 'hi' }
> a[1] = 'bye'
'bye'
> b
{ '1': 'hi' }
> a
{ '1': 'bye' }
// Use [].concat(arrToCopy) for arrays
> a = []
[]
> a.push(1)
1
> b = a
[ 1 ]
> b = new Array().concat(a)
[ 1 ]
> a.push(2)
2
> b
[ 1 ]
> a
[ 1, 2 ]
-
Array quirks with -ve indices If we push -ve indices into an array it will behave like a keyed object and arr functions like
.forEach
will ignore the -ve indexed values. If we call Object.keys() on this array we will get the indices back in a strange order i.e. 0,1,2,3,-1,-2,-3 -
Math -- Faulty rounding Divisions with large remainders are faulty is js and anywhere from 9-20th precision pt after decimal place may be rounded incorrectly. -- Solution : Use long division by hand algorithm when dealing with large remainders
-- Incorrect adds Watch out for adding strings and nums, e.g.
> 1 + '0'
'10'