Skip to content

Instantly share code, notes, and snippets.

@aarontam
Last active January 30, 2016 01:58
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 aarontam/57b2ac6d415bd4f699cb to your computer and use it in GitHub Desktop.
Save aarontam/57b2ac6d415bd4f699cb to your computer and use it in GitHub Desktop.
Random JS quirks, tricks, tips, and hacks.
/*
* Disclaimer: I neither endorse nor necessarily support these techniques. In general, I value readability over brevity, but I found
* some of these to be somewhat interesting and worth noting and sharing, as I have seen them used extensively.
*/
/* Convert any value to a Boolean */
var myVal = null;
!!myVal; // false
myVal = 0;
!!myVal; // false
myVal = 1;
!!myVal; // true
myVal = 2;
!!myVal; // true
/* Convert the result of an indexOf to a Boolean representing whether or not the item was found */
var myArr = [1, 2, 3];
~myArr.indexOf(1); // -1
~myArr.indexOf(2); // -2
~myArr.indexOf(3); // -3
~myArr.indexOf(4); // 0
// Note that the result of ~ is effectively -(x + 1)
// All together now...
!!~myArr.indexOf(1); // true
!!~myArr.indexOf(2); // true
!!~myArr.indexOf(3); // true
!!~myArr.indexOf(4); // false
// Setting default values
function myFunction (myParam) {
myParam = myParam || 'my default string';
return myParam;
}
myFunction(); // 'my default string'
// Note that this will set the default value for all falsy values
myFunction(0); // 'my default string'
myFunction(null); // 'my default string'
myFunction(false); // 'my default string'
/* Simultaneously checking for null and undefined */
var myUndefinedVal,
myNullVal = null;
myUndefinedVal == null; // true
myNullVal == null; // true
/* Multiple ways to assign a conditional value */
var myConditional = Math.floor(Math.random()*2), // either 0 or 1
myConditionalValue;
// Standard if/else
if (myConditional) {
myConditionalValue = 'yes';
} else {
myConditionalValue = 'no';
}
// Ternary
myConditionalValue = myConditional ? 'yes' : 'no';
// Logical AND
myConditionalValue = myConditional && 'yes'; // this only works if you want a falsy value for the failure condition of the conditional
// Switch
switch (myConditional) {
case 1:
myConditionalValue = 'yes';
break;
case 0: // or default
myConditionalValue = 'no';
break;
}
/* Early-exit conditions */
// Standard function
function myStandardFunction (myParam) {
if (myParam) {
// do something with a truthy myParam value
}
}
// Short-circuiting function
function myEfficientFunction (myParam) {
if (!myParam) return;
// do something with a truthy myParam value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment