10

!rant

Does anyone know a JS dev who uses constructors for simple things like object and arrays, instead of literal.
Meaning:
var arr = [] ;
vs.
var arr = new Array() ;

And if you do this. Why? Just seems tougher to read to me. I saw a use for dynamically creating regex, and I get that. But any other legit reasons?

Comments
  • 6
    if you can do something like new Array(20) to create an array with 20 undefined i would understand it since then arr.length is 20..
  • 1
    @romangraef This.
  • 1
    @romangraef ahhh. Great point.
  • 2
    not JS, but I know a PHP dev who does this
    And then every array key after it is

    $arr = [];
    $arr[“key1”] = 123;
    $arr[“key2”] = 456;

    And so on 🤦‍♂️🔫

    Instead of

    $arr = array(“key1” => 123, “key2” => 456);
  • 2
    @romangraef True, but if you map over it and expect to get 20 results back you'll be disappointed 😄

    So basically
    (new Array(20)).fill(0).map(x => "woop woop")
    is what you need if you want that sort of thing 😄
  • 1
    Wow. Yeah that's just. Wow. Does he at least get paid per line lmao?
  • 0
    The first one should be quicker, as it doesn't require a name lookup
  • 0
    @AlgoRythm it is. Constructors always carry some overhead.
  • 0
    My preffered way is with [] but I dont really care if someone is using constructor. People are making more fked up things in js than this.
  • 1
    @C0D4 but that aint an array, thats a map ._.
  • 0
    @insanealec that I could live with 😎
    But one per line 🤮
Add Comment