I've looked around to see whether Javascript supports associative arrays and despite the fact that it clearly says that it doesn't, it seems to work anyway?
I'd love to know if anything has changed in the specifications and whether or not it's recommended to use them.
Sample code:
var foo = new Array;
foo["bar"] = "It works";
console.log(foo["bar"]);
You should use objects for that, they are first-class citizens in JavaScript:
var foo = {
"bar": "It works"
};
console.log(foo.bar);
console.log(foo["bar"]);
In Javascript, foo["bar"] is semantically equivalent to foo.bar. But this is Javascript object, not associative array. As you can see, however, you can treat the object as associative array.
I've looked around to see whether Javascript supports associative arrays and despite the fact that it clearly says that it doesn't
Where did you see that it clearly stated that JavaScript does not support associative arrays?
Associative arrays--a collection of key/value pairs (also called maps, dictionaries, and many other names in various contexts)--are the fundamental datatype in Javascript. However, in JavaScript, they are called "objects".
However, given your sample code:
var foo = new Array;
foo["bar"] = "It works";
it seems you may be asking a slightly different question, which is "Can a JavaScript array contain properties (other than its numerically indexed ones)"?
The answer, as well documented, and covered in countless question here on SO, is "yes". The reason is that in JavaScript, arrays are a special type of object, so like all objects, they can have named properties.
whether or not it's recommended to use them.
If you mean is it recommended to hang named properties off a JavaScript array, opinions differ. You can take a look at this question.
Related
Are arrays merely objects in disguise? Why/why not? In what way(s) are they (such/not)?
I have always thought of arrays and objects in JS as essentially the same, primarily because accessing them is identical.
var obj = {'I': 'me'};
var arr = new Array();
arr['you'] = 'them';
console.log(obj.I);
console.log(arr.you);
console.log(obj['I']);
console.log(arr['you']);
Am I mislead/mistaken/wrong? What do I need to know about JS literals, primitives, and strings/objects/arrays/etc...?
Are arrays/objects merely strings in disguise? Why/why not? In what way(s) are they (such/not)?
Arrays are objects.
However, unlike regular objects, arrays have certain special features.
Arrays have an additional object in their prototype chain - namely Array.prototype. This object contains so-called Array methods which can be called on array instances. (List of methods is here: http://es5.github.com/#x15.4.4)
Arrays have a length property (which is live, ergo, it auto-updates) (Read here: http://es5.github.com/#x15.4.5.2)
Arrays have a special algorithm regarding defining new properties (Read here: http://es5.github.com/#x15.4.5.1). If you set a new property to an array and that property's name is a sting which can be coerced to an integer number (like '1', '2', '3', etc.) then the special algorithm applies (it is defined on p. 123 in the spec)
Other than these 3 things, arrays are just like regular objects.
Read about arrays in the spec: http://es5.github.com/#x15.4
Objects are an unordered map from string keys to values, arrays are an ordered list of values (with integer keys). That's the main difference. They're both non-primitive, as they're composed of multiple values, which also implies pass-by-reference in JavaScript.
Arrays are also a kind of object, though, so you can attach extra properties to them, access their prototype and so on.
In your revised example, you're only taking advantage of the fact that an array is actually an object, i.e. you can set any property on them. You shouldn't do that. If you don't need an ordered list of values, use a plain object.
Strings can be either primitive or objects, depending on how they were declared.
var str = 'yes';
Gives you a primitive, while,
var str = new String('yes');
will give you a String object.
All arrays are the same (Whether or not they were defined with [] or new Array()), are of the type object and inherit from the "Array" object's prototype. There aren't real classes in Javascript, everything is an object, and there's a system defined object called Array. It has a property called 'prototype' (of type object), and when you use the new keyword on an object with a prototype property, it creates an instance with a reference to the contents of the prototype and stores it in your variable. So all arrays you've ever used in Javascript are objects and instances of Array's prototype property.
In any case, although arrays really are objects, they behave like arrays because of their useful properties and functions (Such as length, slice, push etc).
Another note, although I said there are no classes, when you do this:
console.log(Object.prototype.toString.call(your_object));
it will give you a string in the form [object Object]. But what's useful is that when you call it with an array, you get [object Array] same with functions which give [object Function] and a number of other system defined types, which assists in differentiating between normal objects and arrays (Since the typeof operator will always just return the string 'object').
Try this
var a = Array;
and go into firebug and examine the contents of a, especially it's 'prototype' property.
Edit: Changed the wording a bit, to be more correct. In fact when you use the new keyword, it creates an instance which references the prototype object. So any changes made to the prototype after the instance's declaration, will still affect the instance.
Edit: In answer to your latest revised question (are arrays/objects actually strings in disguise): No. They are objects, as I've explained. Strings are either a primitive type, or an object type (An instance of the String object) which contains the primitive equivalent as one of it's properties.
Arrays are not primitives in Javascript, they are objects. The key difference is that as a result, when you pass an array to a function it is passed by reference, not by value.
So yes! Arrays are objects in javascript, with a full blown Array.prototype and everything (don't touch that though...)
The confusion comes from the fact that javascripts lets you access object attributes in two ways:
myObj.attribute
or
myObj["attribute"]
Really what makes an array an array has nothing to do with the way you store data -- any object can store values using the syntax you use to store the array -- what makes an array an array is the fact that array methods (e.g. shift() and sort()) are defined for Array.prototype.
Trying to be brief with what I believe to be of the most significance: arrays have a number of methods that objects do not. Including:
length
push
pop
An object declared as var x = {foo:bar} has no access to a .length() method. They are both objects but with the array as a sort of superset with methods mentioned as above.
I don't feel I this is even close to being of Crockford standard in terms of explanation but I'm trying to be succinct.
If you want to get some quick results, open up Firebug or your javascript Console and try Array.prototype and Object.prototype to see some details
Update: In your example you declare an array and then do:
foo['bar'] = 'unexpectedbehaviour';
will produce unexpected results and won't be available in simple loops such as:
var foo=[0,1];
foo['bar'] = 2;
for(var i=0;i<foo.length;i++){
console.log(foo[i]);
}
//outputs:
//0
//1
An array can accept foo['bar']=x or foo.bar=y like an object but won't necessarily be available to be looped through as highlighted above.
Not that I'm saying that you can't iterate through the properties of an object, just that when working with an Array, you're utilising that unique functionality and should remember not to get confused.
In JavaScript you have a few types, everything else is an object. The types in JavaScript are: boolean, number, and string. There are also two special values, "null" and "undefined".
So the quest "is a JavaScript array an object?" is slightly ambiguous. Yes, a JavaScript array is an "object" but it is not an instance of "Object". A JavaScript array is an instance of "Array". Although, all objects inherit from Object; you can view the inheritance chain on the MDC. Additionally, arrays have slightly different properties than an object. Arrays have the .length property. They also have the .slice(), .join(), etc methods.
Douglas Crockford provides a nice survey of the language's features. His survey discusses the differences you are asking about. Additionally, you can read more about the difference between literals and constructors in question #4559207.
Arrays are Objects, but of a specialized nature. Objects are collections of values indexed by keys (in Javascript notation, {'key': 'value'}), whereas Arrays are Objects whose keys are numeric (with a few functions and properties). The key difference between them is obvious when you use a for each loop--an Object will iterate over all the values in its properties, whereas an Array will return the keys instead. Here's a link to a JSFiddle demonstrating the difference--notice that the first for each, which uses an array, returns the indexes, not the values; in contrast, the second for each returns the actual values at those keys.
I'm currently learning Javascript (I'm familiar with C# and Python), and currently the tutorial I'm reading is discussing comparison between two objects. In the coding I've done (I've had various projects), this sort of thing has never really been needed. Given that this might be important for the future, I thought I'd look for when/where to use object comparison, but all I can find are questions/answers on how it works, not why you should use it and when. I can't think of any situations off the top of my head where comparisons between primitives wouldn't be better, so any help in this area would be appreciated.
You would use it when you have two variables which refer to objects, and you want to see whether they refer to the same object. For example, with the window object, you can do
if (window !== window.top) {
console.log('This script must be running in an iframe!');
}
I can't think of any situations off the top of my head where comparisons between primitives wouldn't be better
Many objects (including window) can't just be converted to a unique primitive easily.
You may be able to use JSON.stringify to convert a plain object to a string, and then compare those strings, but this won't help you compare whether the objects are actually the same object in memory:
const obj1 = { prop: 'val' };
const obj2 = { prop: 'val' };
// They are not the same object
console.log(obj1 === obj2);
// But if you convert them to a primitive string first, you won't be able to tell
console.log(JSON.stringify(obj1) === JSON.stringify(obj2));
At the risk of a circular argument, you use it when you need to use it. :-)
I'd say it's roughly the same as in C#. In both cases, when you use an equality operator, it tests to see whether they're the same object (rather than separate but equivalent objects).
For instance, suppose you have an array of objects, and the contents of that array can change. Later, you have an object you should remove. You'd compare the object to remove with the objects in the array to see if you should remove it (often in a filter operation):
arrayOfObjects = arrayOfObjects.filter(obj => obj !== objToRemove);
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 5 years ago.
Closely related questions:
associative array versus object in javascript
Why does JavaScript not throw an exception for this code sample?
javascript array associative AND indexed?
I have the following code sample:
var someVariable = {abc: "def", ghi: "jkl"}
someVariable["SomeProperty"] = "dfsdfadsd"
alert(someVariable["SomeProperty"])
var someOtherVariable = { abcd: "defsd", ghij: "dfsdfdss" }
someOtherVariable.SomeOtherProperty = "adfsdfsd"
alert(someOtherVariable.SomeOtherProperty);
alert(someOtherVariable["SomeOtherProperty"])
All of them do exactly what they look like - they attach a property to their respective objects. The alert shows the expected string in every case. My understanding from the related questions is that there's no functional difference between the two.
I also encountered the following statements in W3Schools's JavaScript arrays tutorial:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
If that's the case, why is array syntax permitted here at all? (Again, my understanding from the related questions is that the actual distinction between an associative array and a JavaScript object is, at a minimum, slightly blurry, and that that's how JavaScript is implementing object properties "under the hood").
As far as I know (and please correct me if I'm wrong as JavaScript isn't my primary language), it's not possible to do other things you'd expect to be able to do with an array (e.g. iteration with a for loop), so why bother having both syntaxes? In C# you can do something like:
// A C# dictionary is basically an associative array
Dictionary<string, int> dict = new Dictionary<string, int>();
// Fill dictionary ...
foreach (string key in dict.Keys) {
int value = dict[key];
// Do something with the value
}
but I'm not aware of a way to do a similar thing with JavaScript properties. There's a clear necessity for this syntax in C# (keys are definitely not properties of dict), but why does JavaScript have this (given that they're exactly equivalent)? Am I missing something, or is this actually completely redundant?
Why does JavaScript allow array syntax to access properties?
It isn't "array syntax".
Square brackets are a standard way to access the properties of an object.
Arrays are just a type of object.
Square bracket notation has some advantages over dot notation for accessing properties:
You can use any expression to define the name, including variables and function calls.
You can access properties which have names that are invalid in an identifier (such as those which start with a number, which is why you commonly see them used to access arrays).
It's also more verbose and potentially less efficient.
the actual distinction between an associative array and a JavaScript object is, at a minimum, slightly blurry, and that that's how JavaScript is implementing object properties "under the hood"
JavaScript doesn't have a feature called "associative arrays". (W3Schools is not a trustworthy source).
It has objects, which are (at their core) collections of property:value pairs. (This is similar to PHP's associative array feature).
It has arrays, which are objects which inherit from the Array constructor, gaining methods like forEach and properties like length (which uses a getter function to determine its value based on the properties with a name that is the highest integer value).
var a = Int32Array(10);
console.log(Array.isArray(a)); // prints false to the console (Firefox)
Is there a reason why a typed JavaScript array is not an array or is this a bug that needs to be reported?
No, typed arrays aren't arrays, it doesn't need reporting.
They're a very distinct set of objects with different functions. In the specification, they're described as objects which
present an array-like view of an underlying binary data buffer
A good reason not to confuse them : they don't even offer the functions you have on arrays, for example splice.
It also doesn't follow the spec of Array.isArray as it's not an "Array object" as can be verified by setting the value at an out of range index using the bracket notation and checking the length isn't changed.
I know that Javascript Arrays are actually objects, and because they are objects, they can have properties. Here's an example:
var a = [1, 2, 3];
a.currentIndex = 2;
a.next = function() { ... };
a.prev = function() { ... };
a.length // returns 3
To me this seems like it could come in very handy. I see numerous reasons why you might want to store state or utility functions on the actual array itself and not on some other variable. It even seems better than having the array as a property of an object with the other stuff stored on that object.
Here's my question:
Does anyone know of any issues with storing properties on a Javascript array? Does it work in all browsers? Is there any evidence that this will change with future versions of Javascript? Is there any general wisdom about whether or not it's a good practice?
(p.s. For the record, I don't need to iterate over the array with a for...in loop. I understand that such a loop would include the properties as well)
Since you already ruled out the for in issue, my answer here is a clear "no" - there is no issue to worry about. All Array.prototype methods will only apply on the "indexed" keys (0...n).
The best example here is the well know jQuery library, it also uses Array-Like objects to store DOM nodes on but it also has lots of methods which are attached to that object (jQuery uses the prototype there tho). However, other librarys like Zepto, just put those methods directly on the "array" object itself.
So again, no there is no other caveat and you're save doing it.
Just throwing out one more thing -- None of the "copying" array prototype functions will copy any of your extra properties, if that's important, i.e. .splice, .slice, concat will give you new "clean" arrays without currentIndex, etc
Yes it works in all browsers. And it is valid javascript (arrays are objects). One could think of a number of reasons why you want to use the Array constructor instead of an object, but if this is your preferred coding style, go with it.