Differences in objects? - javascript

I've seen two ways to use objects, I would like to know what's the difference or it's just different syntax?
Option 1
body(data) = {
item1: data.val1;
item2: data.val2;
item3: data.val3;
}
Option 2
body(data) = {
item1 = data.val1,
item2 = data.val2,
item3 = data.val3
}
body.item1 = '';
body['item2'] = '';

In your example there is no difference, but the array-like syntax will help you once you need to use a variable as the object property, let's say:
const foo={}
const prop= 'item4';
foo[prop] = 'something good'
alert(foo.item4)//Should alert "something good"

There is no difference, you can access properties on Objects via the dot notation or the square brackets notation. To be compliant to the coding standards (and on the why the brackets notation is useful) you should always use the dot notation to reference to properties; the only case in which you should be using the square brackets notation is when you want to reference to a property that is not hard coded but will be referenced at run time. (I.E. when you use a variable to know which property to get).

Related

JS - Difference between period and [] while accessing a JSON object [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
What is the difference between accessing a JSON object using period (.) and [] notation in Javascript. For instance,
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
I'm sure accessing the "firstName" and the "lastName" variables give me the same output type (string),i.e.
console.log(typeof person.firstName); // returns string
console.log(typeof person.lastName); // returns string
Also, accessing it both the ways, using . or [] will give me the same result:
console.log(person.firstName); // returns Foo
console.log(person['firstName']); // returns Foo
I'm trying to understand when to use which notation and when not to and the actual difference between them. I read somewhere that we can't use the dot notation if the data is complicated, I'm not sure what it means, tested out a couple of sample input data:
"firstName": " Foo Bar "
"firstName": "####$% Foo Bar!!!"
Interestingly, both gives me the same result, can someone please explain me what's the actual difference between these two notations and when to access which?
They are both valid ways of accessing Object Values.
Welcome to Stackoverflow!
The main difference between the two is that using bracket notation allows you to define and access properties with spaces in them -- something one cannot do with dot notation.
var foo = {
"I AM BAR": 1
}
If you wanted to access the single property "I AM BAR" on foo, with bracket notation, it would look like: foo["I AM BAR"]. This is not possible with dot notation.
There are not difference.
The [] approach is useful when you need find a key with a variable.
Like:
const theKey = 'test';
theArray[theKey]; // this work
theArray.theKey; // this dont work
Using dot notation you must provide the exact propertyName but you are able to work with the name when using [].
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
Using . you can only access by
console.log(person.firstName); // returns Foo
Using [] you could access value with variable
let couldChange = 'Name';
console.log(person['first'+couldChange]); // returns foo
console.log(person['last'+couldChange]); // returns bar
Most of the time you will use dot notation. Unless you need the property on the object you need to access to be dynamic. This is because the value you pass into the brackets could be a variable as long it resolves to a string. Check out this link for more info:
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
Most of the time, there's no difference, see Property accessors (MDN), but you cannot use dot notation when the property name is not a valid identifier name, e.g. when it's representation is not a string, or when you need to use a variable to name the property.
obj[1] // is valid
obj["1"] // is the same
obj.1 // is NOT valid
const propertyName = 1;
obj[propertyName] // the same as obj[1]
obj.propertyName // not same
Using brackets can allow you to use a variable value to access object properties whereas dot notation won't. For example:
var propName = 'age';
var o = {
name: 'Tom',
age: '29',
about: 'He\'s a cool guy!'
};
console.log(o.propName); // <-- Will be undefined
console.log(o[propName]); // <-- Bingo

Why symbol-type key in Object have a bracket around them [duplicate]

This question already has answers here:
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 5 years ago.
I just started JS, wondering why there are [] around Symbol. For example: in an object.
var bow = {
[Symbol('apple')] : something,
[Symbol('banana')] : something,
....
}
Also, when it comes to iterator:
var iterableObject = {
[Symbol.iterator] : function() {.....}
}
Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
The bracket notation is just another way of accessing a property on an object. In particular, it's used when the property name is not valid for use with the dot notation, such as Symbol.iterator.
You may also want to look at computed property names: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
These are similar but are instead used to set properties when an object is defined rather than get properties from an already defined object.
The square brakets are just part of object literal syntax.
When you make an object using object literal syntax it is now possible to use variables to set the keys inside the object.
const string = 'whatever'
const normalObject = {
[string]: 'something else'
}
This results in normalObject having one property, 'whatever' pointing to 'something else'
// normalObject
{ whatever: 'something else' }
The use of brackets in object literal syntax is just to allow you to use a variable to set the key in an object.
bringing this back to your example this is just allowing you to use Symbols as keys in your object.
You may have noticed that this is a little weird. Up until very recently an object could only have String keys. Symbols are not the other thing you can use as keys in an object.
var bow = {
[Symbol('banana')] : something,
[Symbol('banana')] : something,
....
}
this will result in an object with two different Symbol(banana) pointing to something.

How to add an empty array to object?

I'm having trouble adding my empty array into my object via the bracket notation method. I know how to get my empty array into the object via dot notation, but I just don't understand why the bracket notation isn't working for me.
Update: I understand my problem now; the context switch between dot notation & bracket notation blinded me & I completely failed to recall that in my 3rd block - animal[noises] (forgot the "") was trying to access the property value of the property noises, which I hadn't created yet in my object
Creating & adding properties to my object
var animal = {};
animal.username = "Peggy";
animal["tagline"] = "Hello";
Which will then create this:
animal {
tagline: "Hello",
username: "Peggy"
}
Why won't the following work when I'm trying to add it into my object?
var noises = [];
animal[noises];
I'm getting this in my console (same as above):
animal {
tagline: "Hello",
username: "Peggy"
}
I was able to get my result this way:
animal.noises = [];
Which outputs this into my console:
animal {
noises: [],
tagline: "Hello",
username: "Peggy"
}
But that still leaves me with the question: why doesn't this work via bracket notation?
Use
animal.noises = noises;
or
animal['noises'] = noises;
As when you are using animal[noises]; it means when you are trying to read data from the object.
For animal[noises],
animal is the object
and noises is the key/property of the object animal
And an array cannot be a key. If you want to put noises array in animal object you can do it as follows,
animal['noises'] = noises;
In your case you have to try
animal['noises']=noises
Array [] notation is used to get property of an object that requires a quote around it. Array notations are commonly used to get identifiers of objects having special characters included.say,
var animal={
"#tiger":'carnivore' // you can't have #tiger without quote as identifier
}
console.log(animal.#tiger) // it will give ERROR
console.log(animal['#tiger']) // it will print out 'carnivore'
this link has good explanation on array and dot notation .

The preferred way to access and create an object's properties?

In Javascript, you can create an object with a property name this way:
var person = { name: "Tucker" };
But also that way:
var person = { "name": "Tucker" };
Are these two equivalent? Which one is preferred?
Same goes with accessing a property:
person["name"] = "Dale";
vs.
person[name] = "Dale";
In Eloquent JavaScript, the author says that The part between the brackets can be any expression. It is converted to a string to determine the property name it refers to..
So, I guess directly putting a string between the brackets would be considered best practice.
Last but not least, properties can be accesses by using the dot notation:
person.name = "Dale";
if the property is a valid variable name. Does it actually makes sense to use this notation over the seemingly more flexible bracket notation?
These are the same, the only difference is that if your key is reserved keyword, you need the quotes:
var person = { name: "Tucker" };
var person = { "name": "Tucker" };
var person = { "for": "Tucker" }; //Need quotes here
When accessing, the same rules apply
person["name"] = "Dale"; //Sets the person object's name attribute to "Dale", the brackets are needed for variables or expressions.
person.name = "Dale"; //Same operation, different syntax
person[name] = "Dale"; //Sets the attribute equivalent to the value of the variable name, not necessarily "name"
Does it actually makes sense to use this notation over the seemingly more flexible bracket notation?
It is entirely up to you, or whoever decides your project's coding standards. The dot notation is simpler and reminiscent of Java/C/C++ (if you're into that sort of thing) and brackets, as you noted, are more flexible.
There's no 'best way', and it really depends on what you're doing.
var person = { name: "Tucker" };
Is fine, but if 'name' is actually 'name with a space' then you need:
var person = { "name with a space": "Tucker" };
For accessing properties, unless you're in a for ... in loop I would recommend dot notation:
person.name
Of course you can't do:
person."name with a space"
So do:
person["name with a space"]

Accessing JS attributes - data.att vs. data["attr"]?

var person = {name: "Johen", address: "USA"}
Is there a difference between the following 2 ways to access the person's attributes? Are there any performance implications?
var name = person.name
var address = person["address"]
Thanks!
They are equal. You need the array syntax if the key contains characters not allowed outside a string though. The same applies if you want to use a dynamic key - long time ago people used to use messy hacks like foo = eval('obj.' + propname); but foo = obj[propname]; is much nicer of course
IMO the obj.property syntax is much nicer since it's shorter and more natural.
Both "dot" and "square bracket" access methods for object properties are described in ECMA-262 section 11.2.1. Dot access can be used only in limited cases where the name conforms to the rules for allowed characters for identifiers.
Square bracket notation can be used where the name is evaluated from an expression. It essentially says "evaluate the expression and use the result as the property name" so you can do things like:
function foo() {return 'foo'}
var obj = {};
obj[foo()] = 'foo';
Array properties are accessed in exactly the same way as object properties - arrays are just objects with a special length property.

Categories

Resources