Skip to content

Instantly share code, notes, and snippets.

@thecodejack
Last active December 22, 2015 00:08
Show Gist options
  • Save thecodejack/6386785 to your computer and use it in GitHub Desktop.
Save thecodejack/6386785 to your computer and use it in GitHub Desktop.
Weird Javascript
parseFloat( 'Infinity' ) // returns Infinity
Number( 'Infinity' ) // returns Infinity
parseInt( 'Infinity' ) // returns NaN
//This happens even when we pass any radix.
// Ok, you may have seen wrapping a number literal with parens to call Number methods
(55).toFixed(2); // "55.00"
// And it is understandable that without parens you get a syntax error
55.toFixed(2); // SyntaxError: identifier starts immediately after numeric literal
// But numbers with decimals work fine without parens (WTF?)
55.888.toFixed(2); // "55.89"
// And whole numbers with two dots work as well (WTF?)
55..toFixed(2); // "55.00"
// Hey, so what about 3 dots!? Firefox gives XML-related error (WTF?)
55...toFixed(2); // TypeError: XML descendants internal method called on incompatible Number
Math.max();
// -Infinity
Math.min();
// Infinity
Math.min() < Math.max();
// false
"Why am I a " + typeof + ""; // "Why am I a number"
//this weirdness is because of '+' operator between typeof and "".
//Remember folks, parseInt() is not eval().
parseInt("1", 10); // 1
eval("1") // 1
//Pretty much the same thing....wait.
parseInt("1 + 1", 10); // 1
eval("1 + 1") // 2
//In the first example the first digit is recognized and the rest of the string is thrown away. How intuitive. eval() at least gets it right.
parseInt("1 - 1", 10); // 1
eval("1 - 1") // 0
//The string example takes the first digit and just throws out the rest of the string. And again, eval() with the correct solution.
parseInt("1" + "1", 10) // 11
eval("1" + "1") // 11
//This time they both get the wrong answer, because the strings are concatenated before the numbers are evaluated.
parseInt("1" - "1", 10); // 0
eval ("1" - "1") // 0
//Both right answers, because the subtraction symbol forces the strings into numbers before they get used.
parseInt(null, 24) === 23 // true
//Sometimes JavaScript has identity crisis:
var foo = [0];
console.log(foo == !foo); //true
console.log(foo == foo); //true
var f = function() { };
f.foo = 'foo'; // sets f.foo to 'foo'
//Functions are objects, so you can set properties on them after creation.
f.name; // is ''
f.name = 'foo';
f.name; // is still ''
//But not all the time.
var myFunction = function myFunction() { };
myFunction.name; // is 'myFunction'
//Functions happen to have magic properties. One of them is the non-standard .name, which stores the function's first name and read-only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment