Skip to content

Instantly share code, notes, and snippets.

@SigBaldi
Forked from gsans/gist:93a6a9edbdf2a393bbb4
Last active February 10, 2017 12:46
Show Gist options
  • Save SigBaldi/d9f87320977ba844d349 to your computer and use it in GitHub Desktop.
Save SigBaldi/d9f87320977ba844d349 to your computer and use it in GitHub Desktop.
JavaScript Funky Behaviours
(function () {
'use strict';
var u; //undefined
//Declares a variable, but does not define a value for it.
/*
** Falsy values:
** • false Surprise!
** • 0 Digit zero
** • "" Empty string
** • undefined
** • null
** • NaN A special Number value meaning Not-a-Number!
**
** Truthy values: All other values are truthy, including "0" (zero in quotes),
** "false" (false in quotes), empty functions, empty arrays, and empty objects.
*/
// all pass this test
console.log(!false==true); // true
console.log(!0==true); // true
console.log(!""==true); // true
console.log(!u==true); // true
console.log(!null==true); // true
console.log(!NaN==true); // true
// but falsy is not always false
console.log("-");
console.log(false==false); // true
console.log(0==false); // true
console.log(0===false) // false
console.log(""==false); // true
console.log(u==true); // false
console.log(u==false); // false WAT?!?
console.log(null==false); // false WAT?!?
console.log(NaN==false); // false WAT?!?
//take home
// 1) Use negation with falsy values. Don't use == or !=
// if (!falsy) // good
// if (falsy==false || falsy!=true) // won't work as expected
// Weird cases
console.log("-");
console.log(undefined==null) // true
console.log(undefined===null) // false
console.log("0"==0) // true
console.log("0"===0) // false
console.log([]==true); // false
console.log([]==false); // true
console.log([]===true); // false
console.log([]===false); // false
// Apparently normal…
console.log("-");
if([]) console.log("truthy"); // truthy
if(![]) console.log("falsy"); // not falsy
var isItTruthy = "truthy?";
if([]) {
isItTruthy = "yes"; // this runs
}
console.log(isItTruthy); // yes
// …or not?
if ([]==true) {
isItTruthy = "no"; // this does not run
}
console.log(isItTruthy); // truthy
if ([]==false) {
isItTruthy = "yesss"; // this does run
}
console.log(isItTruthy); // yesss
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment