4 questions about JavaScript objects and the specifics around accessing properties and creating them [duplicate] - javascript

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 3 years ago.
I'm currently trying to learn JavaScript. I have some experience with Java and C++. I've been trying to find a clear cut and specific explanation of accessing and creating properties in JavaScript and have been unable to find one. Some question I have about objects:
var myObj = {
firstName: "Vinnie",
lastName: "Glaser"
}
1.) When defining objects, sometimes people put quotations around the key and sometimes they don't. What significance does this have? If there are no quotations around the key value is it still considered a string?
2.) When accessing properties of objects, sometimes people put quotations around the key and sometimes not. What is the significance of this?
3.) What practical differences are there between myObj[key] and myObj.key? There have been a few scenarios in which one is necessary over the other but I'm not sure why.
4.)
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
Why doesn't this work?
Thank you for the help.

1.) When defining objects, sometimes people put quotations around the key and sometimes they don't. What significance does this have? If
there are no quotations around the key value is it still considered a
string?
2.) When accessing properties of objects, sometimes people put quotations around the key and sometimes not. What is the significance
of this?
All valid keys are interpreted by the system as strings regardless of whether they are in quotes or not and regardless of what the key actually is. Even a key of 1 would be processed as "1" and you can see this in your browser's debugger, so it's not about making the key a string or not. It's simply about whether the key name is valid syntax without them. For example, most people would say that a property (key) name can't contain spaces:
let obj = {
my property : "foo"
};
But, that's not true. It's just the un-quoted key names that contain a space is invalid syntax. You can do it with quotes:
let obj = {
"my property" : "foo"
};
// Then, you access the property through array-like syntax
console.log(obj["my property"]);
3.) What practical differences are there between myObj[key] and myObj.key? There have been a few scenarios in which one is necessary
over the other but I'm not sure why.
Syntax. In the above example, it would be invalid syntax to try either of these:
obj.my property
obj."my property"
But, if you access keys using array-like syntax, you would have to pass in the index and in that case strings are legal syntax:
obj["my property"]
4.) Why doesn't this work:
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
Without quotes around the index values, the system believes that what you are passing are variables, so it attempts to get the values out of the variables. It would work if the values you are passing in were declared variables that have values and those values mapped to existing keys in the object.
let myObj = {
full : null,
first : "Scott",
last : "Marcus"
};
let fullName = "full";
let firstName = "first";
let lastName = "last";
myObj[fullName] = myObj[firstName] + " " + myObj[lastName];
console.log(myObj[fullName]);

Related

array-like in Javascript detail explanations [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Does javascript have a method to replace part of a string without creating a new string?
(4 answers)
Closed 1 year ago.
var a = 'cat' ;
a[0] = 'r' ;
a = 'cat'
Why..??
In case of string although you can access elements by array notation, if you try to change its content it will fail silently i.e. will not throw any error but will not change content either.
Please explain me detail.
Strings are primitive values in javascript, and are therefore immutable. This is just how the language works so there's not much to explain besides that. You can read more about it here!
It is not throwing an error because you're probably not running it in strict mode.
Strings are immutable, in JavaScript only objects and arrays are mutable. You can search for mutable data types in JavaScript in Google.
"A mutable object is an object whose state can be modified after it is created." MDN.
You can read more here: Mutable

Is Object and Array in Javascript the same thing? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Are Javascript arrays primitives? Strings? Objects?
(7 answers)
Closed 2 years ago.
I'm looking for an elegant way of understanding JavaScript array and objects.
I came to an anomaly in which I got stuck.
Since in PHP or other languages, when we make an array e.g
$a = [
admin => 1,
staff => 2
];
so if we want to access its element we can do so by for e.g $a[admin] and we will get 1.
similarly if its an object e.g
$a = (object) [];
$a->sadd = 'sas';
we can access it with arrow
$a->sadd
and if we try to access object elements in the style of array i.e like this $a['sadd'] it will throw error that you can not use it as array style.
But I was surprised by the anomaly in JavaScript.
I have observed that in JavaScript no matter what I am making, an array or object, the elements of both can be accessed via dot or via array style and i found no difference in there accessing style.
for e.g
var a = {sadd : 1}
I can access its element via a['sadd'] or a.sadd both will give 1
So I am confused by this anomaly and wondering whether array and object both datatypes are considered same in JavaScript?
An array is indeed an object.
Javascript is a dynamic language and accepts mixed types of entities. Also while accessing, dot notation seems to be more clearer (atleast imo) and is preferred. Bracket notation is used for dyanamic keys.
The difference between array and objects boils down to their usecase:
Array -> Contiguous block of memory
Object -> key-value pair (like a dictionary)
Your php example is actually creating what we'd call an object in JS, not an array. In JS an array is a list of items, which you can find items by array[i], or by looping.
An object is a collection of fields, which you can go into by object.fieldName or object[fieldName].
This can be confusing in JS though, because theoretically everything is an "object", including arrays, due to the way things are handled lower down..
I would recommend following along with the https://justjavascript.com/ course for good mental models on how objects work in JS.

Unfamiliar use of square brackets during multiple variable declaration in Javascript [duplicate]

This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 5 years ago.
I'm a beginner to Javascript and encountered this syntax usage(simplified):
var testString ="firstName, lastName";
var [a,b] = testString.split(", ");
My question is what typeof variable a & b then becomes at line2?
My simplistic investigation seems to indicate a & b are assigned respective string values.
But what goes on under the hood? why do we use square brackets [] here? Isn't an array returned & created in the process by .split()? Otherwise, what objects were created in the background?
Links to understand this style of declaration for [a,b] would also be welcomed.
But what goes on under the hood?
// You declare a string variable
var testString = "firstName, lastName";
// Split method help you to divide the string value according with the
//indicated separator, in this examle the comma
var [a,b] = testString.split(", ");
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
Since the split function returns an array, with the var [a,b] = array
you are assigning the value in index order, in the example:
console.log(a); // 'firstName'
console.log(b); // 'lastName'
And they are simple string variables. You may want to vist the links below:
Destructuring asignation
split function
Further resources: Since you have mentioned you are beginning with JS, I suggest you to read books mentioned in this magnific post
This is destructuring assignment. It resembles the pattern-matching found in many functional languages.

JS arrays - advanced assignment [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 6 years ago.
This is related to the arrays in Javascript, which I am trying to use in a complex logic.
Consider the following code:
a['a1'] = 'AJA'
We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).
So, if we go ahead and interpret this:
console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)
It logs :
A
J
A
AJA
Now, all I need is to assign a new character at the 4th position.
When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.
I know that we can do this using string concatenation, i.e.
a['a1'] = a['a1'] + 'Y' and get this accomplished.
But why wasn't the first method working? By what other ways can do this?
Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.
You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.
let a = {};
a['a1'] = 'AJA';
a.a1[1] = 'A';
console.log(a.a1);
For more you can see MDN Documentation
As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:
var s = 'ss';
When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)

Difference between quoted and un-quoted JavaScript object properties [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 6 years ago.
Is there a difference between quoted and un-quoted JavaScript object property/method names?
For example, what is the difference between these two:
var obj1 = {
property1 : "Value 1",
method1 : function() {
return true;
}
};
var obj2 = {
"property1" : "Value 1",
"method1" : function() {
return true;
}
};
There is no difference in JavaScript. However you will have to quote property names that happen to be reserved words (such as class), or names that contain invalid characters (such as first-name).
Up until ES 3 you need to quote reserved words of the language (new, default, class, etc.). In the new version, however, this will be unnecessary.
But since ES 5 is not well-supported yet, you need to stick with quoting all reserved words.
If you don't want to memorize the full list of words, you better off with quoting everything.
Extra: this is why you don't have float and class properties on an element. You have to use cssFloat/styleFloat and className instead.
Another addition is that you need to quote every key in a JSON string. The reason is because they wanted it to be language independent, in order not to interfere with stupid restrictions like the one in ES3.

Categories