Ternary Conditionals
var x = true ? true : false;
Nested Ternaries
isArthur && isKing ? (weapon = ‘a, helment = ‘a) : isArcher ? (weapon = ‘b’, helmet = ‘b’) : (weapon = ‘c’, helmet = ‘c’);
Logical Assignments
Var result = 42 || undefined; // 42 Var result2 = [‘sweet’] || 0 //[‘sweet’,..] Var result3 = ‘’ || {object} //{object}
If all elements are truthy, then takes the first one:
Var result = ‘king’ || ‘arthur’ // ‘king’
If all elements are falsy, then takes the last one:
Var result = undefined || ‘’ // ‘’ Var result2= ‘’ || undefined // undefined
For && assignments, takes the last truthy value:
Var result = ‘a’ && ‘b’ && ‘c’ // ‘c’
For && if any element is false, short circuits immediately to false:
Var result = false && ‘b’ && ‘c’ // false
Switch Statements
Without the break, switch statement has program flow go through each case statement after the first truthy one:
Switch (test) { Case false: Str = 1 Case true: Str = 2 Case true: Str = 3 } // str = 3
Loop Optimization
Variables defined inside a loop causes CPU processing on each iteration to set the variable, so these should be done outside the loop (if it is legiable)
Var someElement = ‘’; for (…) { someElement = … }
Also, the variable for length is some expensive so these can also be defined before the second definition of the for loop:
for (var i = 0, total = someArray.length; i < total; i++) { … }
Map, Reduce and Filter
These are 3 very powerful built-in javascript functions that let us manipulate data sets quickly and efficiently. Traditionally when we have to manipulate any data set we would create a loop that traverses the set. We may define a result set variable beforehand to push the desired values into that result during the loop traversal. For example:
var results = []; dataset.forEach(function (record) { if (record.id > 5) { results.push(record); } });
The problem with the above code sample is that we must have another variable set in memory to capture the results and we must write up the loop to do the full traversal. To avoid this, JavaScript provides the map(), reduce() and filter() functions which make it a lot easier to code this.
map()
The map() function takes 2 arguments, a callback and an optional context. The callback runs for every value in the dataset and returns a new value into the final resulting set. In the example below, we have a dataset of objects with multiple properties. We can use map() to get specific properties of that set.
var people = [ { name: 'jack', age: 5 }, { name: 'john', age: 6 }, { name: 'joey', age: 1 }, { name: 'jane', age: 3 } ]; var names = people.map(function (person) { return person.name; });
reduce()
The reduce() method is used to reduce the dataset into a single value or element. Similar to map() function, the reduce() function also takes a callback function and an optional accumulator initial value. The callback function can take up to 4 parameters, which are shown in the table below.
function(total,currentValue,currentIndex,arr);
Argument | Description |
---|---|
total | Required. The initialValue, or the previously returned value of the function |
currentValue | Required. The value of the current element |
currentIndex | Optional. The array index of the current element |
arr | Optional. The array object the current element belongs to |
For example, if we have an array of numbers, we can use reduce() to get the sum of the dataset.
var numbers = [65, 42, 12, 3]; var sum = numbers.reduce(function(total, num) { return total + num; });
Note that in the example above, the total variable is what we are tracking to get the final result we are expecting from the reduce() function. Another example below shows how we can use reduce to get a specific object – the person with the oldest age.
var people = [ { name: 'jack', age: 5 }, { name: 'john', age: 6 }, { name: 'joey', age: 1 }, { name: 'jane', age: 3 } ]; var oldest = people.reduce(function(personOlder, person) { return (personOlder.age || 0) > person.age ? personOlder : person; }, {});
Note that in the example above, the initial starting value is a null object and so the first element of the dataset is the first ‘person’ parameter passed into the callback method.
filter()
Filter is another powerful method of getting specific elements of a dataset. As the name implies, it does a filter on the dataset. The example below shows how we can get elements where the character length is greater than 5.
var names = ['jack','jonathan','joseph','jane']; var longnames = names.filter(function(word) { return word.length >= 5; });
end