Javascript Array Instantiation [duplicate] - javascript

This question already has answers here:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 8 years ago.
What is the correct way on instantiate empty array in javascript?
var array=new Array();
var array=new Array;
var array=[];
All of them look same. Is there any difference?

var array=[];
works best.
Ref - http://jsperf.com/array-instantiation

There is one more way:
var array = Array() ;
They all will produce the same result, an empty object Array. I think the best way is using the array literal shortcut [] as it is what use less characters, it is what most people do.
Note that the same does not apply in the case of Boolean, Number and String, as those constructors will return primitives of type 'object' (object Boolean, object Number and object String respectively) while their literals will return primitives of types 'boolean', 'number' and 'string' respectively (and will behave differently in some situations), but array primitive type it is 'object' in any case.

Related

is this method object.keys returning an array or keep it an object [duplicate]

This question already has answers here:
Why does typeof array with objects return "object" and not "array"? [duplicate]
(3 answers)
Closed 2 years ago.
I'm learning JavaScript, so pardon any mistakes in how I phrase the question.
let nan={
n:3,
j:4
};
let nag = Object.keys(nan)
> nag
(2) ["n", "j"]0: "n"1: "j"length: 2__proto__: Array(0)
> typeof nag
"object"
Why is nag an object and not an array? And that makes difference when you want to access, you will be not able to access with dot notation I think we need in that case square bracket
This is because internally javascript engines store Arrays as objects. Therefore, when you ask for the typeof an array, it returns an object since that is what it is. Essentially, in javascript, Array is an abstraction over native object (an indexed collection object).
If you want to know whether a variable is an Array and not an object you should use Array.isArray(nag). This returns a boolean.
You can lookup the docs here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
or if you are in the mood, lookup the typeof spec at:
https://www.ecma-international.org/ecma-262/#sec-typeof-operator
tip: With JS, whenever in doubt, lookup the specs. It's probably the best place to clear up confusions
In Javascript, everything that is not a primitive (numbers, bigints, strings, symbols) are objects. This includes arrays. Objects also have square bracket notation to look up a key, and the dot notation is just a shorthand for looking up a string key:
const a = {
foo: "bar"
};
a.foo // "bar"
a["foo"] // "bar"

Why does the typeof a numerical array index in a "for..in" loop considered a string? [duplicate]

This question already has answers here:
Why does javascript turn array indexes into strings when iterating?
(6 answers)
Is a JavaScript array index a string or an integer?
(5 answers)
Why is key a string in for ... in
(3 answers)
When iterating over values, why does typeof(value) return "string" when value is a number? JavaScript
(1 answer)
Closed 1 year ago.
I noticed that in Javascript a variable used as the index in a for..in loop will be always a string even if I define it the following way:
var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';
for(i in s_array){
alert(typeof(i)); // String
}
Why is it considered a string and not a number?
The for(x in y) syntax is intended to iterate over the properties of an object (not the indexes of an array), and property names are always stored as strings.
The fact that it also works for arrays is a side effect of array elements being properties on the array object.
To understand the difference, consider this code:
var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';
s_array['foo'] = 'bar';
console.log("Object:");
for(i in s_array) {
console.log(i);
}
console.log("Array:");
for(var i = 0, l = s_array.length; i < l; i++) {
console.log(i);
}
which provides the following output:
Object:
0
1
foo
Array:
0
1
There's a foo property on the object, but it's not actually an element inside the array.
Arrays are essentially objects with managed set of indexed keys.
Since every key in an object is of type string hence it is a string as well.
Consider your array as :
{"0" : "foo" , "1" : "bar"}
So your
for(i in s_array){ alert(typeof(i)); }
can be read as
for each key in the s_array
In js arrays are high-level, list-like objects (associative arrays).
indexes eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit toString conversion.
source: MDN

In JavaScript, why don't any objects equal each other, except strings? [duplicate]

This question already has answers here:
Difference between the javascript String Type and String Object?
(2 answers)
Closed 9 years ago.
Everything in JS is an object. I've always known that, and I totally understand that. I know why {} !== {}. It's two different objects. Same as if you were to write out new Object() == new Object().
Some other examples:
{} == {} // => false
[] == [] // => false
/ / == / / // => false
new String() == new String() // => false
But, Strings are objects too (it's why you can do ''.replace() and extend them), so why does this work:
'' == '' // => true
Obviously it'd be a huge headache to compare two strings if this didn't work, but this seems inconsistent with the rest of the language. Internally, what's going on? Is it just a one-off or is there some other concept behind this?
JavaScript basically treats strings and numbers as scalars at all times, converting them to objects when a method is called, and converting back afterward, in cases where you aren't explicitly declaring new String("");
Same with numbers.
Without string/number/boolean equality, you'd have a hard time doing much of anything.
It is a one-off.
Reference
There is a difference between string literals and string objects. The article goes into more detail if you are interested.
The same is true for booleans and numbers. These primitives are compared different from objects.
There are five primitive types in JavaScript: Number, String, Boolean, Undefined, and Null. Comparing the empty string literal "" to itself is no different from the comparison 5 === 5.

Can a javascript array be both numerical and associative? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript array associative AND indexed?
I am returning an array from a function and am wondering if I can have both a string association and numerical associations as well.
Ex:
array[0] = green;
array[1] = blue;
array['what'] = colors;
In some way yes, because it's some type of Object. But it's wrong use of them :)
Use objects ({}) for named (stringish) indexes and arrays([]) for number indexes.
Arrays are just objects with a special length property and some handy inhertited methods. Since arrays are objects, their property names are strings however the numeric ones ('0','1','2', etc.) are visited by array methods whereas non–numeric ones (e.g. length) aren't. Also, many array methods are generic and can be applied to any object with suitable properties (i.e. a numeric length property and some numeric property names).
Note that to be considered an index, the property name must satisfy the rules for index names so:
var x = [];
x['00'] = '00'; // length = zero as '00' is not an index
x['0'] = '0'; // length = 1 as '0' is an index
It's generally considered bad form to use an array where a plain object will do, though there are no consequences for doing so other than if you mess with the length property.

check object Equal object javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do you determine equality for two JavaScript objects?
I want to check if two objects not different :
var v1 = {id:"llll", dd="kkkk"};
var v2 = {id:"llll", dd="kkkk"};
if (v1 == v2)
{
alert("lll");
}
not work why ????
Because objects are compared by reference:
Functions
Objects (Host objects, native objects/constructors and instances)
A common instance is {}, which is similar to new Object.
The following object types are compared by value, not by reference:
Strings
Numbers
Booleans
null and undefined
Additionally, there's one object which is never equal to itself, not even by reference:
var test = NaN;
alert ( test == NaN ); // false
alert ( test == test ); // false (!)
To check whether two objects are equal, you have to define equality:
"Two objects are equal if they contain the same property names and values"
Which implies that object A has to have the same number of properties as object B, and that every property in A has also to be a property of B.
Try using "===" instead of "==" to compare the objects.

Categories

Resources