javascript
General Concepts
Reference vs. Value
(The following is basically a short version of this article)
Primitives are accessed directly. Primitives are:
String
Number
Boolean
null
undefined
Other data types are passed by reference (and handled as Objects in JavaScript):
Array
Function
Object
When a primitive is assigned to a variable, its value is copied. For example:
Changes made to x
after assigning x
to a
are not reflected in a
, because its value copied and the variables have no connection whatsoever to on another.
In contrast, Objects are references to an address. If an Object is assigned to a variable, that variable contains a reference to the address of the Object. Therefore, changes made to the object are reflected in all variables referencing that address.
A pure function in JavaScript is a function with no side effects, everytime you call it with the same arguments it returns the exact same result. Common disqualifiers for a pure function are Methods like Math.random()
and Date.now()
being called. I the function has to manupilate an object, it has to manipulate a copy of it to not manipulate the external state.
Useful things
Useful to print out complexer data structures. (Non Standard)
String literals that allow embedded expressiosn:
Sum of an array
There is no native sum()
function on JavaScript arrays, so the sum has to be calculated by hand somehow. There is the method reduce()
on array, though.
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
So, to sum the values of an array, we can simply use reduce()
in a way like this (ES6 Syntax):
Create a unique array
Given the array
using Set
we can create an array with only unique values in it
Last updated