Difference between "{}" and "new Object()" [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
creating objects - new object or object literal notation?
What exactly is the difference between the following:
var myData = new Object();
myData["name"] = "ATOzTOA";
myData["site"] = "atoztoa";
and
var myData = {};
myData["name"] = "ATOzTOA";
myData["site"] = "atoztoa";
Update
What I got is this...
var myData = {
"name" : "ATOzTOA",
"site" : "atoztoa",
};
is a shortcut to
var myData = new Object({
"name" : "ATOzTOA",
"site" : "atoztoa",
});
Am I right?

There is no difference (technically). {} is just a shortcut for new Object().
However, if you assign an object literal, you may directly form a new object with multiple properties.
var myData = {
name: 'ATOzTOA',
size: 'atoztoa'
};
..which might feel more convenient. Also, it reduces the access on the object and is ultimately faster. But that is about microoptimizations. More important is that its a lot less to type.

Nothing. {} just a short hand for new Object()
Its same logic as your full name is 'Mark Zuckerberg' and people call you ' Hi Mark'

No difference in my view , Both are initializing the object. nothing else , it is a shortcut.

Related

difference between `new Object()` and object literal notation? [duplicate]

This question already has answers here:
What is the difference between `new Object()` and object literal notation?
(12 answers)
Closed 4 years ago.
can anyone tell me actually what it is (var abc={} <==this one is object or?) if that is object what different between var abc=new Object() and var abc={};
Another question is scanner scan =new Scanner(); is same concenpt with var abc= new Object(): ??
Objects can be defined by either of these two methods:
var abc = {};
var abc = new Object();
There is minimal difference between the two, however the first method is preferred by most.
If Scanner is of type Function then you instantiate it like so:
var scan = new Scanner();
The Scanner function might have been created like this:
function Scanner(total = 5){
this.scans = total;
}
You could use this function like this:
var scan = new Scanner();
console.log(scan); // Output: Object
console.log(scan.scans); // Output: 5
scan = new Scanner(100);
console.log(scan.scans); // Output: 100
scan.scans = 50;
console.log(scan.scans); // Output: 50
var scan2 = { scans: 5 };
console.log(scan2); // Output: Object
console.log(scan2.scans); // Output: 5
For an empty object, both var abc = {} and var abc = new Object() works but there are different approaches with different scenarios/requirements to choose the appropriate style.
You can read more at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Go to "Creating new objects"
For
var scanner = new Scanner();
Scanner must be a function.

Can you evaluate a property name within a JS object? [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I know that you can evaluate the value of a property inside of a JS object, like the following:
let object = {
value: 5+5
};
I am wondering if there is any possible way to evaluate the name of an attribute with JS, i.e. achieve the following:
let object;
object[5+5].value = "ten";
As something like:
let object = {
5+5: "ten"
};
Yes in ES2015, no in ES5, but first let's clear one thing up: that's JavaScript, not JSON.
In ES2015 (formerly known as ES6):
var something = "foo";
var object = {
[something]: "bar";
};
alert(object.foo); // "bar"
Inside the [ ] can be any expression you like. The value returned is coerced to a string. That means you can have hours of fun with stuff like
var counter = function() {
var counter = 1;
return function() {
return counter++;
};
};
var object = {
["property" + counter()]: "first property",
["property" + counter()]: "second property"
};
alert(object.property2); // "second property"
JSON is a serialization format inspired by JavaScript object initializer syntax. There is definitely no way to do anything like that in JSON.
Sure. Try this:
'use strict';
let object = {
[5+5]: "ten"
};
console.log(object); // Object {10: "ten"}

Variable variables in JavaScript? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 months ago.
In PHP I can mess around with variable variables and I'm wondering if I can do the same in JavaScript.
I want to create a new object with a property which's name is based on the value of a variable.
if ( obj.name === 'foo' ) {
var data = { foo: value };
}
if ( obj.name === 'bar' ) {
var data = { bar: value };
}
Is there a shorter way of doing this without using eval()? Something like:
var data = { obj.name: value };
Try this:
var data = {};
data[obj.name] = value;
You can read some more about js objects Here.
Objects in JavaScript are simply hash maps. You can access members by indexing with their names. For your problem you can use
var data = {};
data[obj.name] = value;
I've used this to implement a dynamic dispatch mechanism for arithmetic operations on different numerical types as described here.

How do I add to a JavaScript object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Adding members to an existing object
Lets say you have the following object:
var object = {
name: "Shawn"
};
I want to know if there is a function so I can add a new "section" to this object.
Like this for example:
object.add('age',14);
To turn the above object to:
var object = {
name: "Shawn",
age: 14
}
If you ask, "What have I tried". My answer is: "Nothing, i wouldnt be asking if I knew how to do this". I think it should be possible to do. But I just don't know how I will do it.
I looked at w3schools and don't recall seeing a built in function for this. Thanks you.
You can add function properties and methods by using the dot operator .:
obj.age = 24;
This is also equivalent:
obj['age'] = 24;
Use array syntax:
object['age'] = 14;
Or if the property name does not need to be dynamic:
object.age = 14;
var obj = {
name: "Shawn"
};
obj.age=14;
alert(obj.age)
It is as simple as:
var object = {
name: "Shawn"
};
object.age = 14;
var object = {
name: "Shawn"
};
object.age = 14;

create object using variables for property name [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
Is it at all possible to use variable names in object literal properties for object creation?
Example
function createJSON (propertyName){
return { propertyName : "Value"};
}
var myObject = createJSON("myProperty");
console.log(myObject.propertyName); // Prints "value"
console.log(myObject.myProperty); // This property does not exist
If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:
var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"
If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):
Create the object first, and then add the property using square bracket notation.
var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"
If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.
ES6 introduces computed property names, which allow you to do
function CreateJSON (propertyName){
var myObject = { [propertyName] : "Value"};
}
Note browser support is currently negligible.
You can sort of do this:
var myObject = {};
CreateProp("myProperty","MyValue");
function CreateProp(propertyName, propertyValue)
{
myObject[propertyName] = propertyValue;
alert(myObject[propertyName]); // prints "MyValue"
};
I much perfer this syntax myself though:
function jsonObject()
{
};
var myNoteObject = new jsonObject();
function SaveJsonObject()
{
myNoteObject.Control = new jsonObject();
myNoteObject.Control.Field1= "Fred";
myNoteObject.Control.Field2= "Wilma";
myNoteObject.Control.Field3= "Flintstone";
myNoteObject.Control.Id= "1234";
myNoteObject.Other= new jsonObject();
myNoteObject.Other.One="myone";
};
Then you can use the following:
SaveJsonObject();
var myNoteJSON = JSON.stringify(myNoteObject);
NOTE: This makes use of the json2.js from here:http://www.json.org/js.html
One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.
function func(prop, val) {
var jsonStr = '{"'+prop+'":'+val+'}';
return JSON.parse(jsonStr);
}
var testa = func("init", 1);
console.log(testa.init);//1
Just keep in mind, JSON property names need to be enclosed in double quotes.

Categories