Object and Object Literals in javascript [duplicate] - javascript

This question already has answers here:
What is the difference between `new Object()` and object literal notation?
(12 answers)
Closed 6 years ago.
Will anyone please explain the difference between object and object literals in JavaScript?
So far I learned by searching google is given bellow:
1) Object is a collection of name-value pairs like: address:"my address".
2) Object Literals are a sequence of name-value pairs separated by commas and surrounded by curly braces. For example: {address: "my address", roll: 0001}
But its still not making sense to me. I can't find out the basic differences between these two. Actually, I'm confused with the 'collection of name-value pair' and 'sequence of name-value pairs'.

An object literal is simply an object that is literally defined, as in
var object_literal = {
key1 : "value",
key2 : "value2",
}
However there are many types of objects in javascript, for instance
var obj1 = new Date(); // object
var obj2 = function() {}; // object
var obj3 = new RegExp(); // object
and many, many more, but these are not literal objects

Related

JavaScript: Why Declare Object with Constructor instead of Blank Literal? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
creating objects - new object or object literal notation?
Literal notation VS. constructor to create objects in JavaScript
I'm going through my very first Javascript tutorial.
I just found two ways to create a JS object.
var person = new Object();
person.name = "Tom";
person.age = "17";
and
var person = {};
person.name = "Tom";
person.name = "17"
Any difference between these two ways of object creation? Since the second looks simpler, can we always use it under any condition?
Not only is the second syntax easier to read and not only will it work under any condition, but the first syntax might not work under all conditions:
function Object() {
// Oh crap, we have redefined Object!
return []; // return an array because we are EVIL
}
var person = new Object(); // not what we think it is
But {}, being a syntactic construct, is immune to such evil trickery.
In addition, the object literal notation can be partially optimized at parse time, since after all there's only one object type that could be created. That may result in a minuscule performance increase.

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

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;

Iterate over Javascript object [duplicate]

This question already has answers here:
How do I iterate over a JSON structure? [duplicate]
(13 answers)
Closed 8 years ago.
I have a Javascript object
var a = {
"tag1": "Stocks",
"acctType1": "individual",
"compare1": "contains",
"match_name1": "scrapedaccounttype",
"text1": "dog ",
"tag2": "Stocks",
"acctType2": "individual",
"compare2": "contains",
"match_name2": "scrapedaccounttype",
"text2": "cat"
}
I need to use this Javascript object to do some more math, but I am not sure about how I would be iterating over the Javascript object.
I can have any number of tags (tag1, tag2, tag3, tag4 ... ) or similarly other keys like (acctType1, acctType2, acctType3.... ) so I need to iterate over them individually and do some manipulation to use these variables in a different function.
While , for each what would help my cause here. Note that I could have any number of tags(tag1,tag2...) or comapare(compare1, compare2, compare3..)
I would need to process all of them individually.
What you have is NOT JSON. It is JavaScript defining an Object literal, commonly referred to as a JS object. JSON (JavaScript Object Notation) is a string that can be parsed to produce an object literal.
For your JS object (which has ample online documentation), you can iterate over the object keys by:
var a={"tag1":"Stocks","acctType1":"individual","compare1":"contains","match_name1":"scrapedaccounttype","text1":"dog ","tag2":"Stocks","acctType2":"individual","compare2":"contains","match_name2":"scrapedaccounttype","text2":"cat"}
Object.keys(a).forEach(function (k) {
console.log(a[k]);
});
Or:
for (var key in a) {
if (a.hasOwnProperty(key)) {
console.log(a[k]);
}
}

Javascript object constructor vs object literal [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
creating objects - new object or object literal notation?
Literal notation VS. constructor to create objects in JavaScript
I'm going through my very first Javascript tutorial.
I just found two ways to create a JS object.
var person = new Object();
person.name = "Tom";
person.age = "17";
and
var person = {};
person.name = "Tom";
person.name = "17"
Any difference between these two ways of object creation? Since the second looks simpler, can we always use it under any condition?
Not only is the second syntax easier to read and not only will it work under any condition, but the first syntax might not work under all conditions:
function Object() {
// Oh crap, we have redefined Object!
return []; // return an array because we are EVIL
}
var person = new Object(); // not what we think it is
But {}, being a syntactic construct, is immune to such evil trickery.
In addition, the object literal notation can be partially optimized at parse time, since after all there's only one object type that could be created. That may result in a minuscule performance increase.

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.

Categories