What is the difference between "new Array () / new Object ()" and "[] / {}" respectively?

3

In javascript there are two ways to create arrays and objects , they can be created using literal objects:

  • new Array() - Object - arrangement
  • new Object() - Object - object
  • or they can be created from their primitive objects which are:

  • [] - Object - arrangement
  • {} - Object - object
  • What is the difference between using the literal object to use the primitive object?

      

    I understand that for the new Array() , the constructor can receive a parameter to define the property length of the created array, but is this the only difference?

        
    asked by Jorius 10.05.2017 в 17:04
    source

    2 answers

    4

    Gathering differences I found:

    • The one you comment on. The constructor, effectively new Array allows to add the size of the array.
    • Speed. The execution of the literals in javaScript is practically twice as fast. You can follow the following operation token that exemplify the different steps that the compiler executes when performing one or another operation.

      []: ARRAY_INIT  
      [1]: ARRAY_INIT (NUMBER)  
      [1, foo]: ARRAY_INIT (NUMBER, IDENTIFIER)  
      new Array: NEW, IDENTIFIER  
      new Array(): NEW, IDENTIFIER, CALL  
      new Array(5): NEW, IDENTIFIER, CALL (NUMBER)  
      new Array(5,4): NEW, IDENTIFIER, CALL (NUMBER, NUMBER)  
      new Array(5, foo): NEW, IDENTIFIER, CALL (NUMBER, IDENTIFIER)  
      

      Being:

      ARRAY_INIT - > A simple initialization
      IDENTIFIER - > The idneitfication by the compiler of the Array object
      CALL - > The call to the constructor
      () - > Elemenos of the constructor, which produce different outputs for each other.

    • The literal generates a "runtime array" while Array () generates an object with functions that give access to the array, this causes certain limitations when accessing methods.

    In summary use whenever you can literals, it has many advantages over the object.

        
    answered by 10.05.2017 / 17:13
    source
    -2

    I understand that both array and string inherit from the Object class in Javascript.

    In the first instance I would say that String is used for text fields in HTML, to which you can apply styles for Text fields and functions for String.

    And array, in my opinion, are used for more complex data, such as nesting one or more html elements (object type), even managing an object tree. This is very useful when we work with grids for example.

    I leave you more info with the different methods and properties, I hope you find it useful !!

    String (Object) Javascript: link

    Array (Object) Javascript: link

        
    answered by 10.05.2017 в 17:38