Empty object being used as an array in JavaScript [duplicate] - javascript

This question already has answers here:
How can I add a key/value pair to a JavaScript object?
(26 answers)
Closed 7 years ago.
I am new to JavaScript and learning.
I see some code where variable is declared as abcBean={};
and then being used as
abcBean[SOME_SET.KEY] = false
Can someone please explain how an empty object is being used as an array?

(Disclaimer: I work on Microsoft's Chakra JavaScript engine)
In JavaScript, all objects are prototype instances and their properties are defined at runtime. They can be accessed using dot-syntax (object.property) but also by name (object['property']) which enables some interesting meta-programming scenarios.
Internally (inside a JavaScript engine) JavaScript prototype objects are typically implemented as a kind of dictionary or hashtable. You can also use Number instances as keys too, not just names, which has the interesting effect of a JavaScript object exhibting a kind of duality where it is both an array (indexed by integer offset) as well as a dictionary (indexed by integer key).
For example, these four objects can be considered equivalent:
var array1 = [ 1, 2, 3 ];
var array2 = new Array( 1, 2, 3 );
var dict1 = { 0: 1, 1: 2, 2: 3 };
function Constructor() { this[0] = 1; this[1] = 2; this[2] = 3; }
var dict2 = new Constructor();
In practice, engines have optimizations where JavaScript arrays and objects are handled differently based on their initialization syntax. Internally in Chakra the array1 and array2 objects will be represented as an array of integers but dict1 and dict2 will both be hashtable objects, however if you add a non-integer element to array1 or array2, or add an element by key, then Chakra will (behind the scenes) re-represent the object internally as a hashtable (or some other more appropriate representation).
Of note, this will not internally expand array1 to an 101-element-sized array:
var array1 = [ 1, 2, 3 ];
array[100] = 5;

Related

Javascript associative array does not support Array.prototype.map function [duplicate]

This question already has answers here:
Length of a JavaScript associative array
(4 answers)
Closed 4 years ago.
After long times programming, I don't know why never have seen this:
var array = [];
array['one'] = 1;
console.log(array.length);
Here is a fiddle that shows array.length is zero (0):
https://jsfiddle.net/0c9v5txe/1/
Of-course, I don't need the length of array, just array.map is not working when the length is zero.
Isn't there really a way to force Javascript update the length of an associative array when adding a new item?
JavaScript doesn't have a feature called "associative arrays".
It has objects, and arrays are a type of object designed to hold numerically indexed values. (The length property on an array is calculated based on the highest numbered numerical property).
(Since arrays are a type of object, you can store arbitrary properties on them, but this is not a good practice).
If you want to store named properties, then do not use an array. Use a plain object or a Map. These serve the same purposes as associative arrays in other languages.
You can count the enumerated properties of an object by extracting them into an array and then checking its length.
var myObject = {};
myObject.one = 1;
console.log(Object.keys(myObject).length);
you need to pass index, not value
array[index] = value;
var array = [];
array[0] = "one";
console.log(array.length)

Assigning objects in Javascript: shallow or deep copy? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 7 years ago.
I want to know if javascript does shallow or deep copy when copying objects.
const a = ['value1', 'value2'];
const b = ['value3', 'value4'];
const new_ab = [a, b];
new_ab are going to have new allocated values or a reference? If it is a deep copy, how can I make it to be swallow? Thanks.
As alluded in the comments, JavaScript operates entirely on references, the only exception being that primitive values are kept on the stack and a program does not therefore require a reference to access them. In your example all variable declarations create new values - each an instance of Array - however what is returned from declaring an array is a reference, not the array itself. For example, [1, 2] is an array of values (integers), but [a, b] is an array of references.
So... nothing is copied. We can demonstrate this by placing an object as an element of an array and inspecting that a previously assigned property is still accessible through the new 'parent' array.
(And to answer your question in the comments, yes, your example is more performant than if you (or JavaScript) were to copy values.)
'use strict';
const arrayOne = [];
arrayOne.someProperty = "This string is a property of `arrayOne`, " +
"accessed via the reference to it in `arrayTwo`."
const arrayTwo = [arrayOne];
span.innerHTML = arrayTwo[0].someProperty;
<span id="span"></span>

Iterating over sparse arrays [duplicate]

This question already has answers here:
How should I iterate over a sparse array in index order?
(2 answers)
Closed 6 years ago.
This answer says that the best way to iterate over sparse arrays is to use for X in Array
However, when I tried this I tripped up because the type of X was a string, rather than the integer index I was expecting. (All fine until I added it to another integer...)
var arr = [];
arr[10000] = "Hello";
var shifted = []
for (var x in arr)
shifted[10+x] = arr[x];
"Expected":
shifted[10010] = "Hello
Actual
shifted["1010000"] = "Hello"
Is there a better way of iterating a sparse array using the index, or should I just use Number(X) where required?
This is how V8 (and others JavaScript engines) handles arrays:
V8 uses two different methods to handle arrays:
Fast elements:
Designed for arrays where set of keys are very compact. They have a linear storage buffer that can be accessed very efficiently.
Dictionary elements:
Designed for sparse arrays which don’t have every elements inside of them. It is actually a hash table, more expensive to access than “Fast Elements”
Source: http://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/
When you are using a sparse array, the key is converted to string and then hashed. If you want numeric keys: don't use a sparse array or manually convert the key to a number.

Difference between "new Array(..)" and "[..]" in JavaScript? [duplicate]

This question already has answers here:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 8 years ago.
Is
var myCars=new Array("Saab","Volvo","BMW");
and
var myCars=["Saab","Volvo","BMW"];
exactly the same ?
Yes, for that case they are the same.
There is a difference if you have only one item, and it's numeric. This will create an array with a single item:
var myNumbers = [42];
but this will create an array with the length 42:
var myNumbers = new Array(42);
Yes, they are. However be aware that when you pass just a single numeric parameter to the Array constructor, you will be specifying the initial length of the array, instead of the value of the first item. Therefore:
var myCars1 = new Array(10);
... will behave differently from the following array literal:
var myCars2 = [10];
... note the following:
console.log(myCars1[0]); // returns undefined
console.log(myCars1.length); // returns 10
console.log(myCars2[0]); // returns 10
console.log(myCars2.length); // returns 1
That is one reason why it is often recommended to stick to the array literal notation: var x = [].
Yes, they are the same. There is no primitive form of an Array, as arrays in JavaScript are always objects. The first notation (new Array constructor syntax) was used heavily in the early days of JavaScript where the latter, short notation was not supported well.
Note that there is one behavioural difference: if you pass a single, numeric argument to new Array, like new Array(20), it will return a new array pre-initialised with that number of elements from 0 to n - 1, set to undefined.

Is it better to write: var arr=[]; than var arr=new Array();? [duplicate]

This question already has answers here:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
What is the difference between `new Object()` and object literal notation?
(12 answers)
Create an empty object in JavaScript with {} or new Object()?
(10 answers)
Closed 5 years ago.
Is it better to write
var arr=[]; then var arr=new Array();
var obj={}; then var obj=new Object();
and if so, why?
I read slide lection page 36 about that idea, but no explanation was given or example why its better.
There is not a big difference between these definitions, except that the first way uses the array/object literal and the second the array/object constructor.
The array constructor may return different results, depending on the number of arguments passed in. If you pass in one argument, a new empty array is created of the length of that argument. For example:
// arr1 is the same as arr2
var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];
alert(arr1.length == arr2.length); // true
alert(arr1[0]); // 1
alert(arr2[0]); // 1
But, passing in one argument results differently:
// arr3 has length 200 and is empty, while arr4 has length 1 and contains a number
var arr3 = new Array(200);
var arr4 = [200];
alert(arr3.length == arr4.length); // false
alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200
The speediest way to define an array or object is of course the literal way, because you don't need to call the constructor first. Anyway, the actual speed difference is negligible, really.
I did a speed test in Chrome 6, in which I defined 20 times 10000000 the same array 1, 2, 3, which gave these results:
Average speed per 10000000 calls
Array Constructor : 226.55 ms
Array Literal : 159.1 ms
As you can see, the array literal is 67,45ms faster per 10000000 array definitions.
From a typical programmer perspective, it seems that you tend to use var arr = new Array(); so as to give the feeling of typical object instantiation. But in javascript its usually good practice to use var arr = [];
Personally I dont see much difference in using both ways except for one parameter which is explained by Harmen.
Check this link too -
http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/
thomas fuchs says in his slideshow, under that video (the part saying "embrace the language" on page 20):
var arr=[] and var obj={} is better and slightly faster. I'm not sure why, but anyway, it's a pretty interesting slideshow :)

Categories