pauloabmiranda
5/20/2016 - 7:41 AM

Javascript tricks

Javascript tricks

/* 1) Converting to boolean using !! operator */
// will return false only if it has some of these values: 0, null, "", undefined or NaN, 
// otherwise it will return true

var cash = 0;
var hasMoney = !!cash; //false


/* 2) Converting to number using + operator */

var strNumber = '100';
strNumber = +strNumber; // 100


/* 3) Short-circuits conditionals */

user && user.login();


/* 4) Detecting properties in an object */

if ('querySelector' in document) {
    document.querySelector("#id");
} else {
    document.getElementById("id");
}


/* 5) Merging arrays */

array1.push.apply(array1, array2);


/* 6) Converting NodeList to Arrays */

[].slice.call( (container || document).querySelectorAll('p') );