1

Could you guys please explain the difference between the two following variables?

var test = {};
var test2 = [];

Are they not both declaring an array variable? If not, when to use which?

4 Answers 4

4

The first creates an object (empty object with no properties at all).

The second creates an empty array.

Let's take an example of manipulating an object:

var test = { firstName: 'Foo', lastName: 'Bar' };
alert(test.firstName);

you could also dynamically extend an existing empty object and add properties to it:

var test = {  };
test.firstName = 'Foo'; // or an equivalent: test['firstName'] = 'Foo';
alert(test.firstName);

and an array:

var test2 = [ { firstName: 'Foo', lastName: 'Bar' }, 
              { firstName: 'Foo 2', lastName: 'Bar 2' } ];
for (var i = 0; i < test2.length; i++) {
    alert(test2[i].firstName);
}

or to add elements to an array:

var test = { firstName: 'Foo', lastName: 'Bar' };
var test2 = [ ];
test2.push(test); // the array contains 1 element now
alert(test2[0].firstName);
Sign up to request clarification or add additional context in comments.

8 Comments

So then it almost seems the first is an associative array and the second is normal indexed array?
I don't think this example is the best way to explain the difference between arrays and objects; it's confusing to create an array of objects if you want to point out the differences between them ;)
@Felix Kling, Rick, Harmen, I totally agree with you. Your insight is very useful and correct. Thank you for those precisions. I just wanted to point the differences the way I did because I see many questions here by people trying to do $.each in jQuery AJAX success callbacks and asking why it doesn't work whereas the server sent { ... } instead of [ ... ]. Maybe it's because I am coming from a .NET background where there is a precise distinction between an array and an object and wanted to believe it was the same in javascript, whereas you explained that it is not exactly right...
... objects can be considered as associative arrays indeed.
I think Felix was referring to your second sentence: "The second creates an array of objects (an empty array...)". I'm guessing your brain was already working ahead on the rest of your answer when you typed "of objects". ;)
|
3

The first variable test is an object, which has variable keys and values, while the second variable test2 is an array, and has fixed keys (0, 1, 2, 3, ...)

For example:

var test = ['a', 'b', 'c'];

alert(test[0]);       // alerts 'a'


var test2 = {
  first: 'a', 
  second: 'b', 
  third: 'c'
};

alert(test2.first);    // alerts 'a'
alert(test2['first']); // alerts 'a'

Comments

1

the first is an object notation the second is an array object (which is an object itself).

you can store associative data in objects but array keys can only be numeric.

1 Comment

array keys can only be numeric ... arrays are objects too, so you can also set string properties. You should not use an array this way, but that does not mean you cannot.
0

Here I provide you a link of a code that I prepare to explain you with examples and details about: JavaScript variable declarations and types, click the link read the code, test yourself and give a like.

https://code.sololearn.com/Wef3g7HLH5SM/?ref=app

Bellow is the code:

<!-- 

In JavaScript you don not have to declare explicitly the type of variables, however JavaScript variables
can hold many data types: numbers, strings, objects. Below I am going to provide you couple examples, 
I hope they help you!

-->

<!DOCTYPE html>
<html>
    <body>

    <p id="demo"></p>

    <script>
    // Single line comment

    /*
      Multi-lines comment
    */

    /*
      The typeof operator can return one of these primitive types:

        * string
        * number
        * boolean
        * null
        * undefined
    */


    var person = undefined; // a variable without a value, has the value 'undefined'
    var vehicle  = "";      // The value is "", the typeof is "string"
    /* 
      null type, is "nothing". It is supposed to be something that doesn't exist.
    */
    var house = null;      // Value is null, but type is still an object
    var number = 1;
    /* 
      JavaScript has dynamic types. Meaning that
      you can use the same variable to hold different data types.
    */
    var x;              // Now x is undefined
    var x = 6;          // Now x is a Number
    var x = "Sam";      // Now x is a String

    /*
      Numbers can be written with, or without decimals places
    */
    var x1 = 2.50;     // Written with decimals
    var x2 = 5;        // Written without decimals

    /*
      Extra large or extra small numbers can be written with 
      scientific (exponential) notation
    */
    var a = 123e4;      // will print: 1230000
    var b = 123e-4;     // will print: 0.0123

    /*
      Booleans can only have two values: true or false.
    */
    var y = true;
    var z = false;

    /* 
      Single or double quotes can be use to write Strings. 
    */
    var stringVariable1 = "This is my name: 'Sam'"; // Using single quotes
    var stringVariable2 = 'Here, my name: "Sam"'; // Using double quotes

    /*
      JavaScript arrays are written with square brackets.
      Array items are separated by commas.
    */
    var girls = ["Julia", "Mary", "Olivia"];

    /*
      JavaScript objects are written with curly braces.
      Object properties are written as name: value pairs, separated by commas.
    */
    var userData = {firstName:"John", lastName:"Doe", userName:"JDoe",
        password:123456};

    document.getElementById("demo").innerHTML =


    typeof person + "<br>" +
    typeof vehicle + "<br>" +
    typeof number + "<br>" +
    typeof y + "<br>" +
    typeof house + "<br>" +

    number + "<br>" +
    x + "<br>" +
    x1 + "<br>" +
    x2 + "<br>" +
    a + "<br>" +
    b + "<br>" +
    y + "<br>" +
    z + "<br>" +
    stringVariable1 + "<br>" + 
    stringVariable2 + "<br>" +
    // here I am going to print the value on array, index 0
    girls[0] + "<br>" +
    userData.firstName + "'s userID: " + userData.userName + 
                         " and pwd: " + userData.password;
    </script>

    </body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.