Friday, May 15, 2015

Javascript - tricks - summary


http://javascript-puzzlers.herokuapp.com/

1. map()

The map() method creates a new array with the results of calling a provided function on every element in this array.

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values.

arr.map(callback[, thisArg])

['1', '2', '3'].map(parseInt);
// While one could expect [1, 2, 3]
// The actual result is [1, NaN, NaN]

Explain:

parseInt expects 2 arguments. The first is the string to be parsed and the second specifies the radix of the number to be parse
The map function is called with three arguments. the value of the element, the index of the element, and the object that is being traversed.

So, it actually has three calls like:
parseInt("1", 0, theArray)
parseInt("2", 1, theArray)
parseInt("3", 2, theArray)

However, if the radix is non-zero and less than 2 the function returns NaN.

parseInt(3, 0) -> parseInt will treat 0 as 10

2. null

typeof null -> "object"
null instanceof Object -> false

Explain:
null can't be considered an object because it cannot have properties.

3.reduce()

the reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

arr.reduce(callback[, initialValue])

the callback function executes each value in the array, taking 4 parameters.
previousValue -> the value previously returned in the last invocation
currentValue -> the current element being processed in the array.
index -> the index of current element
array -> the array reduce() was called upon
initialValue(optional) ->Object to use as the first argument to the first call of the callback.

If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

If the array is empty and no initialValue was provided, TypeError would be thrown. If the array has only one element (regardless of position) and no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callback.

4. Hoisting

var name = 'World!';
(function () {
    if (typeof name === 'undefined') {
        var name = 'Jack';
        console.log('Goodbye ' + name);
    } else {
        console.log('Hello ' + name);
    }
})();

//will output 'Goodbye Jack'.

Explain:
Within the current scope, regardless of where a variable is declared, it will be, behind the scenes, hoisted to the top. However, only the declaration will be hoisted. If the variable is also initialized, the current value, at the top of the scope, will initially be set to "undefined".

Unlike other languages (like c, has block-level scope), js has function-level scope. e.g. if/else don't create a new scope. Only functions create new scope.

5. The highest number in js

var END = Math.pow(2, 53);
var START = END - 100;
var count = 0;
for (var i = START; i <= END; i++) {
    count++;
}
console.log(count); // this will result into an infinite loop, a^52 is the highest possible number in js, 2^53+1 gives 2^53


6. filter()



The filter() method creates a new array with all elements that pass the test implemented by the provided function.

arr.filter(callback[, thisArg])

Function to test each element of the array. Invoked with arguments (element, index, array). Return true to keep the element, false otherwise.

var ary = [0,1,2];
ary[10] = 10;
ary.filter(function(x) { return x === undefined;}); //result -> []

Explain:
Array.prototype.filter is not invoked for the missing elements.

7. Switch

function showCase(value) {
    switch(value) {
    case 'A':
        console.log('Case A');
        break;
    case 'B':
        console.log('Case B');
        break;
    case undefined:
        console.log('undefined');
        break;
    default:
        console.log('Do not know!');
    }
}
showCase(new String('A')); //Do not know

Explain:
switch uses === internally and new String(x) !== x

8. arguments

The arguments object is an Array-like object corresponding to the arguments passed to a function.
The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length.

Can refer to the argument as follows:
arguments[0]
arguments[1]
arguments[2]

In javascript variables are tied to the arguments object so changing the variables changes arguments and changing arguments changes the local variables even when they are not in the same scope. 

9. reverse()

The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.

var x = [].reverse;
x(); //return window

Explain:
[].reverse will return this and when invoked without an explicit receiver object it will default to the default this AKA window

10. Number

Number.MIN_VALUE is the smallest value bigger than zero, -Number.MAX_VALUE gets you a reference to something like the most negative number.

11. Arrays

var a = [1, 2, 3],
      b = [1, 2, 3],
      c = [1, 2, 4];

a ==  b  // false
a === b //false
a > c  //false
a < c //true

Arrays are compared lexicographically with > and <, but not with == and ===


12. Function & Object

Functions have a prototype property but other objects don't.
The Object.getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.

var a = {}, b = Object.prototype;

a.prototype === b;  //a.prototype is undefined, return false

Object.getPrototypeOf(a) === b; // return true

----------------------------
function f() {}
var a = f.prototype, b = Object.getPrototypeOf(f);
a === b; //false

//f.prototype is the object that will become the parent of any objects created with new f 
  while Object.getPrototypeOf returns the parent in the inheritance hierarchy.

13. replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

14. name

Function.name returns the name of the function. This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.

15. Math.min() vs Math.max()

The Math.max() function returns the largest of zero or more numbers. 
If no arguments are given, the result is -Infinity.
If at least one of arguments cannot be converted to a number, the result is NaN.

The Math.min() function returns the smallest of zero or more numbers.
If no arguments are given, the result is Infinity.
If at least one of arguments cannot be converted to a number, the result is NaN.

16. join()

The join() method joins all elements of an array into a string.

str = arr.join([separator = ',']);

The separator is Optional. Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma. If separator is an empty string all ellements are joined without any characters in between them.

17. Trailing comma

[ , , , ].join(", ") // ", , , " 
JavaScript allows a trailing comma when defining arrays, so that turns out to be an array of three undefined.  

18. test()

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.

var lowerCaseOnly =  /^[a-z]+$/;
[lowerCaseOnly.test(null), lowerCaseOnly.test()]

Explain:
the argument is converted to a string with the abstract ToString operation, so it is "null" and "undefined". 

19. Date()

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);


var a = Date(0);
var b = new Date(0);
var c = new Date();

a === b; //false
b === c; //false
a === c; //false

When Date is invoked as a constructor it returns an object relative to the epoch (Jan 01 1970). When the argument is missing it returns the current date. When it is invoked as a function, it returns a String representation of the current time.

20. Function.length

length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number does not include the rest parameter. By contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function.

The Function constructor is itself a Function object. Its length data property has a value of 1.

21. match()

The match() method retrieves the matches when matching a string against a regular expression.

str.match(regexp);

A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). An Array containing the matched results or null if there were no matches.

22. exec()

The exec() method executes a search for a match in a specified string. Returns a result array, or null.

regexObj.exec(str)

No comments:

Post a Comment