Skip to content

Instantly share code, notes, and snippets.

@ericqweinstein
Last active April 7, 2016 04:42
Show Gist options
  • Save ericqweinstein/bfc0b3f65eec083b20af to your computer and use it in GitHub Desktop.
Save ericqweinstein/bfc0b3f65eec083b20af to your computer and use it in GitHub Desktop.
Top Six Things Your Grandmother Doesn't Know About JavaScript

Top Six Things Your Grandmother Doesn't Know About JavaScript

  1. It will sort things lexicographically and not tell you

    [5, 1, 10].sort();
    // => [ 1, 10, 5 ]
    // Numbers go in, numbers come out. You can't explain it!
    
    [5, 1, 10].sort(function (a, b) { return a - b; });
    // => [ 1, 5, 10 ]
    // Requires a custom comparator to work properly
  2. isNaN does not actually tell you if things are numbers; it only distinguishes between NaN and !NaN

    isNaN(NaN);
    // => true
    isNaN(2);
    // => false
    isNaN(true);
    // => false
    isNaN(null);
    // => false

    Oh, wait, no, that's not how it works at all

    isNaN(undefined);
    // => true
    isNaN({});
    // => true

    Maybe use Number.isNaN()?

  3. Addition is non-commutative

    {} + [];
    // => 0
    [] + {};
    // => '[object Object]'
  4. Hoisting: not just for pirate flags!

    // You would think this would be a ReferenceError. You would be wrong!
    
    console.log(a);
    
    var a = 'Hello, world!';
    
    // Prints `undefined`; JS hoists `var a;` to the top of the current scope,
    // but the assignment is still done below
  5. Everything is an object

    3.toString();
    // => SyntaxError: Unexpected token ILLEGAL

    ...if you know how to ask

    3..toString();
    // => '3'
  6. IEEE 754 floating point numbers are neat

    999999999999999999999999 === 1000000000000000000000000;
    // => true
@ericqweinstein
Copy link
Author

I should include implied globals:

foo = 'string'; // Global!

And calling constructors without new is just... bad times

@rufus2021
Copy link

this one really made me angry when i found out.

  [].push(5) // 1 (the new length of the array! cause JavaScript) 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment