-
-
Save SigBaldi/d9f87320977ba844d349 to your computer and use it in GitHub Desktop.
JavaScript Funky Behaviours
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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