JavaScript objects - [] vs dot [duplicate] - javascript

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 9 years ago.
What is the difference, if any, between these two assignments:
var foo = {};
foo['bar'] = "some value";
foo.baz = "some other value";
console.log(foo.bar)
=> "some value"
console.log(foo.baz)
=> "some other value"
Are they synonymous? I've noticed you can add keys with the [] syntax that are not valid property names.
foo['a space'] = "does not work";
console.log(foo.a space);
=> SyntaxError: Unexpected identifier
My reason for asking is that I've cooked up a little JS library for pseudo namespacing. It is written on the assumption that the above assignments are identical (ignoring the superset allowed when using [] syntax)

foo["bar"] is equivalent to foo.bar, although foo.bar is easier to read in my opinion. As you already noticed the former syntax (foo["bar"]) allows you to use property names that are not valid identifiers. It also allows you to use dynamic property names:
var name = "bar";
foo[name] = 1;
console.log(foo["bar"]);
will output 1.

When you use ., the property name is a literal identifier. When you use this in a program, you have to hard-code the property name.
When you use [], the property name is an expression that is evaluated. It's not normally used with simple strings in quotes, because that's what . notation is for. But it's useful when you need to calculate the property, e.g.
console.log(foo["item"+i]);
This latter notation is also the only way to access properties that aren't identifiers. You can use any string as the property name this way.

They are absolutely equivalents except that you can more possibilities with [] syntax for example
var bar = 'text';
foo[bar] = 'baz';

The only difference is you can use variables in the second example however it's is always better to use dot notation like this
someObject.hello = ' hello john';
And the only time i use the other way is if i need to use a variable like this
var msg = 'goodbye';
someObject[msg] = 'goodbye john';
This would be the result
// someObject.hello => 'hello john'
// someObject.goodbye => 'goodbye john'
so use dot notation like obj.some and use obj[myVar] for variables
So the difference is you can use variables in the 2nd example
also if i done this
var myVar = 'test';
someObj.myVar = ' Hello Test ';
then this would be the result
// someObj.test => doesnt work - undefined
// someObj.myVar => ' Hello Test '

They are equivalent, but you cannot use the dot notation when the attribute-name contains a space (or other non-alphanumeric characters):
foo.a space // doesn't work
foo['a space'] // does

Related

Alert() with dynamic content javascript

What is wrong with alert({s[prop]}) but fine with this placeholder={s[prop]}
It says I am missing a ',' after 's' and ':' after ']'
In React, the { }s around attributes are essentially expression delimiters - they indicate that what follows between the brackets is an expression. So, if you have const str = 'foobar', then:
placeholder={str}
evaluates to
placeholder='foobar'
But, in alert, you're not writing JSX - you're writing plain JS. When in an expression context, { indicates the start of an object literal. But the following is not a valid object literal:
const obj = {
s[prop]
}
because objects require keys and values (usually). Perhaps you wanted to do
alert(s[prop])
The only time an object literal doesn't require a value is when you're using the shorthand syntax, when you have a variable in the current scope and want to define an object with a property with the same name as the variable, and the same value as a variable, eg:
const str = 'foobar';
const obj = { str };
This results in an object like { str: 'foobar' }.
In any other situation, you'll need to define the property name in addition to the value, eg
{ somePropertyName: s[prop] }
alert(s['use your key'])
Please use in this way. Avoid using {} in alert(), If you use you will see [object Object] instead of actual dynamic content.
try with
alert(s[prop])
In JSX to print any JS variable it must be wrap inside curly braces, but not required when using in JS, alert is the JavaScript function.

Why does a string literal beside an array like this not throw a syntax error in javascript?

During my coding I made a mistake by calling a function like this
someFunction( 'abc' [someValue] )
I had forgotten the colon inside the function call.
After I found the error I played around.
An assignment like this does not throw an error as well.
let a = 'abc'[someValue];
I would expect a syntax error here. Is there an explanation for this?
A string in Javascript can behave as an object and, as such has properties such as .length and methods such as .slice. So, for any property access on an object in Javascript, one can use either the dot notation as in:
str.length
or the [] syntax as in:
str["length"]
or using a variable:
let len = "length";
str[len]
So, what you have with:
'abc' [someValue]
Is just that syntax. A string followed by a property access. That is legal Javascript. It attempts to get the property from that object with the name of whatever string is in the someValue variable.
Here's are a couple working examples:
// simple property access
let prop = "length";
console.log("abc"[prop]);
// method call
console.log("one fine day"["slice"](4, 8));
One would not generally code this way with a string, but it's perfectly legal as it's just part of how one can access properties on an object in Javascript.
Because that's not a syntax error. The engine thought you were trying to get a letter from that string, so if someValue was a number it will work perfectly fine
let a = "abc"[0]
console.log(a, "abc"[1]) //a, b

What does ${} (dollar sign and curly braces) mean in a string in JavaScript?

I haven't seen anything here or on MDN. I'm sure I'm just missing something. There's got to be some documentation on this somewhere.
Functionally, it looks like it allows you to nest a variable inside a string without doing concatenation using the + operator. I'm looking for documentation on this feature.
Example:
var string = 'this is a string';
console.log(`Insert a string here: ${string}`);
You're talking about template literals.
They allow for both multiline strings and string interpolation.
Multiline strings:
console.log(`foo
bar`);
// foo
// bar
String interpolation:
var foo = 'bar';
console.log(`Let's meet at the ${foo}`);
// Let's meet at the bar
As mentioned in a comment above, you can have expressions within the template strings/literals. Example:
const one = 1;
const two = 2;
const result = `One add two is ${one + two}`;
console.log(result); // output: One add two is 3
You can also perform Implicit Type Conversions with template literals.
Example:
let fruits = ["mango","orange","pineapple","papaya"];
console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya
It's used to reference a variable within string:
let someVar = "World!"
console.log(`Hello ${someVar}`); // Output is Hello World!
const firstName = 'Sachin';
const age = 16
alert(${firstName} is ${age} years old)
//Sachin is 16 years old
It's used as a variable interpolation ${variable_name}

Inline object literal with a variable property

Why does Javascript syntax not support inline object literals with a variable property? For example:
const f = function (arg) {
console.log(arg);
}
f({}['some key'] = 1) // 1
f({ 'some key' : 1}) // [object Object] { some key: 1 }
Is there another alternative other than the two steps?
var o = {}
o['some key'] = 1
f(o)
Thanks!
Why does Javascript syntax not support inline object literals with a variable property?
You seem to be asking about variable properties, yet your examples do not use variables. Specifically, this example will work just fine.
f({ 'some key' : 1})
However, if you actually did want to use a variable without first creating the object, ECMAScript 6 now allows this.
So if this is your variable:
var my_variable = 'some key';
You can now use square brackets around the property name in the object literal, and it will use the value of the expression you provide:
var o = {[my_variable]: 1};
The o object will have a property named "some key". This only works in the implementations that support this syntax of course.

Why aren't variable names converted to strings when using bracket notation in javascript?

Considering: var foo = {"5" : "ten", fighter : "Grohl"};
Why is this the result?
foo[5];
"ten"
foo[1 + 4];
"ten"
foo[fighter];
ReferenceError: fighter is not defined
Of course, if I start with this: var fighter = 'fighter'; then I get Grohl as expected.
My understanding is that when using bracket notation the expression inside the brackets are evaluated and converted to a string. So, in foo[5], toString() is called on 5 in order to evaluate it to a string, which must be used with bracket notation. So my question is:
Why isn't the same luxury afforded to fighter? I know that foo['fighter'] works, but to know isn't to necessarily understand. I'd like to understand what's going on here.
Edit: Why would I expect this to be the case indeed. If fighter was a variable that held another string... say 'Dave', then how would javascript know whether I meant the reference to 'Dave' or if I wanted to convert fighter to the actual string, 'fighter'. Obviously javascript can't read my mind. Thanks to #DaveNewton and #pointy for the illumination.
Because that's just not what the basic semantics of the language dictate. When you put fighter in brackets, you're saying "please evaluate this subexpression and use its value as the object property name". The subexpression fighter is a reference to a symbol, not a string constant.
If you want to use an identifier's name as a literal property name, use the . operator:
foo.fighter
In your other examples, the same thing is going on. The subexpressions 5 and 1+4 are evaluated in exactly the same way they'd be evaluated elsewhere. That is, consider:
var x = 1 + 4;
What do you expect that "x" will be? OK, so then:
var x = fighter;
Clearly to expect that "x" would be the string "fighter" would be seriously weird; how would you ever reference a variable if the language did that?

Categories