Skip to content

Instantly share code, notes, and snippets.

@kaustavha
Created November 5, 2019 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaustavha/6d31ad851a566af3c932395c7caccdc4 to your computer and use it in GitHub Desktop.
Save kaustavha/6d31ad851a566af3c932395c7caccdc4 to your computer and use it in GitHub Desktop.
javascript hijinks to remembers

Javascript language hijinks and quirks to watch out for

  • 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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment