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.
Related
This question already has answers here:
Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
(14 answers)
Closed 5 years ago.
var array = [1,2,4];
array+1 //gives '1,2,41'.
Can anyone explain this behaviour?
Can anyone explain this behaviour?
This answer attempts to explain this behavior from the point of view of spec.
As per spec, during the run-time evaluation of +, both expressions (left and right) are converted to their primitive values.
Let lprim be ToPrimitive(lval).
Let rprim be ToPrimitive(rval).
toPrimitive tries to pass hint:number (since invoked during arithmetic evaluation) to OrdinaryToPrimitive
If hint is "string", then
a. Let methodNames be «"toString", "valueOf"».
Else,
b. Let methodNames be «"valueOf", "toString"». //this gets invoked
Since one of the values were casted to string via 4a) above, string concatenation takes place.
Hence
[1,2,4] + 1 => [1,2,4].toString() + "1" => "1,2,4" + "1" => (finally) "1,2,41"
Array is casted to string - then concatenated with integer value which is also casted to string.
When you use the + sign with a declared javascipt object (var array), even if one of the elements is a number, it doesn't perform an arithmetic addition operation - it concatenates the values as two strings.
In your example, your array [1,2,4] is being casted into a string with a value of 1,2,4. So 1,2,4 concatenated with 1 is 1,2,41
What did you expect? [2,3,5]?
You haven't wrote a mutator for array, you added 1 to array (which is an object). Why do you expect for object to be able to add 1 to it?
JS figured out you need a primitive from that object and listed that object into a string. Now it knows how to "add" 2 strings (precisely its concatenate) so it did.
If you expected an entire array to get +1 on all elements. You want:
for (var i=array .length; i--;) {
array [i]++;
}
Or
array = array.map(function(e) {return '#' + e});
Or in ES6 and beyond arrow function with map
array = array.map(i => i + 1);
When the operands of an operator are different types, they will be converted to a common type.
Both an array and a Number can be converted to string, this is called coercion.
If you would like to add 1 to an array, you can do this:
var array = [1,2,4];
array.push(1);
This question already has answers here:
When is the comma operator useful?
(15 answers)
Closed 1 year ago.
I have the following:
let currentLocalStorage = [];
currentLocalStorage = (initialLoad) ? JSON.parse(localStorage.getItem('tasks')): (currentLocalStorage.push(taskInput.value),currentLocalStorage)
which works but I would like to get a reference or documentation for the following:
: (currentLocalStorage.push(taskInput.value),currentLocalStorage)
so basically we are pushing on to the array and then defaulting to the array. I was surprised that we can do this and was wondering where one we look for the documentation
This is using the comma operator. Because .push() returns the new length of the array, you want to make sure you don't assign that to currentLocalStorage, so you use the comma operator to have that expression evaluate to currentLocalStorage.
So it effectively becomes currentLocalStorage = currentLocalStorage in that case, except now the array has one more item thanks to .push().
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)
This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 6 years ago.
I am new to JavaScript objects so please bear with me.
This is my JavaScript:
var dragSources = {
elementSources: {
squareSource: document.getElementById('squareSource'),
circleSource: document.getElementById('circleSource')
},
ifDragSource: function(elem) {
console.log(this.elementSources.length);
}
};
If you look at console.log(this.elementSources.length); you can probably tell that I am trying to get the length of the elementSources property. However, it returns undefined. What am I doing wrong?
It's an object, not an array, therefore it doesn't have a length property.
You could use Object.keys(this.elementSources).length to get the number of keys.
The .keys() method essentially returns an array of the object's keys.
In this case, Object.keys(this.elementSources) returns:
["squareSource", "circleSource"]
Then we are just getting the length of that array, which is 2.
var dragSources = {
elementSources: {
squareSource: document.getElementById('squareSource'),
circleSource: document.getElementById('circleSource')
},
ifDragSource: function(elem) {
console.log(Object.keys(this.elementSources).length);
}
};
dragSources.ifDragSource(); // 2
Technically if you need the length property in a code you have to store the length value directly in the object.
Using Object.key function decreases the code efficiency .
every time you invoke that function to access that value you have to re-run the same function again and again.
in order access to the length property in a js array, the BIG O is always equal to 1.
because when you update the array the length property would be updated consequently
But in that case the big O would be in the size of the Object and (O) = n
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 :)