This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Should Javascript Objects keys be quoted in?
(3 answers)
Closed 2 years ago.
Here upperLeft and lowerRight are not in quotes but why it does not raise any error ?
example:-
Object literals can be nested. For example:
var rectangle = { upperLeft: { x: 2, y: 2 },
lowerRight: { x: 4, y: 5 } };
this is about object initializer in javascript.
Object can have keys only as string or symbol, anything else then these will be converted to string internally.
Object internally converts its keys to string, so 1 and "1" both are same. So here upperLeft and lowerLeft doesn't throw any error here because it treats them as string only
let obj = {
1: '1',
hey: 'hey'
}
console.log(obj["1"])
console.log(obj[1])
console.log(obj[1] === obj['1'])
The expression in object initialiser are evaluated during initialisation so you can use any expression to have a dynamic key or value.
let key = 'key'
let newKeyValue = "Some value"
const obj = {
[key] : 'some value',
[1 + 2] : 'some more value',
newKey: newKeyValue
}
console.log(obj)
Legal identifiers means anything which follows the following rules
Identifier should have only alphabets, numbers, $ and _
First character should not be number
But in object keys you can use any legal string it will work where as while defining variable you can't use reserved words and illegal identifiers
const obj = {
"1abc" : 'some value'
}
console.log(obj['1abc'])
const do = "no you can't"
Note:- To access invalid identifier you need to use [] bracket notation
Related
This question already has answers here:
Object destructuring with property names that are not valid variable names
(2 answers)
Closed 3 years ago.
The following works fine:
const o = {one:1,two:2,three:3};
const {one,...others}=o;//one=1, others={two:2,three:3}
But how would I do the following:
var o = {['this-is-one']:1,two:2,three:3};
var {['this-is-one'],...others}=o;
Currently that gives me a SyntaxError: Unexpected token ','
I suspect it would not work because this-is-one would be invalid for a constant name (it only works for property values).
You need a renaming of the variable name, because the the given key is not a valid variable name.
var o = { 'this-is-one': 1, two: 2, three: 3 },
{ 'this-is-one': thisIsOne, ...others } = o;
console.log(thisIsOne);
console.log(others);
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
I am trying to create a program that defines the variable finalResult based on variable input. The input variable should call on an object inside of object A:
var input = "";
var A = {
AA: {
result: 0
},
AB: {
result: 1
}
}
var finalResult = A.input.result;
So if input = "AA", then the final result should be 0, but if input = "AB", then the final result should be 1.
You can do A[input].result, which assumes the value of input is present as a property in A. If the property isn’t present you’ll get an error trying to access result on undefined. You can guard against this by OR’ing it with an empty object:
(A[input] || {}).result // undefined if A[input] isn’t present
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 years ago.
I have a global object with various properties whose values are strings. When a user types a string into an HTML input, I'm using javascript to assign that string to a variable. I need to convert that string to a property name and return the string associated with that property.
For example:
myglobalobject = {
propertyname : "String value to be returned."
}
function GetInput(){
mystring = document.getElementById('input').value;
myproperty = convertstringToProperty(str); //This is where I need a solution
return myglobalobject.myproperty;
}
Just use a computed property:
return myglobalobject[mystring];
This is a generalization of the fact that property accesses using dot notation are the same as accessing with brackets and a string literal:
obj.prop === obj["prop"];
So when you have something that isn't a string literal, just use the bracket notation.
Well, properties can be accessed with, you guess it, a string:
const myObject = {
property1: 0,
property2: 1,
};
const inputFromUser = 'property1';
console.log(myObject[inputFromUser]);
You don't even need a function:
var myglobalobject = {
propertyname : "String value to be returned."
}
function GetInput(){
mystring = 'anotherKey';
return myglobalobject[mystring] = undefined;
}
GetInput()
console.log(myglobalobject)
This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
What does the arrow function with a () after means? [duplicate]
(3 answers)
ES6 Fat Arrow and Parentheses `(...) => ({...})` [duplicate]
(2 answers)
What does arrow function '() => {}' mean in Javascript? [duplicate]
(2 answers)
Closed 5 years ago.
I've seen JavaScript code such as this:
let a = () => ({ id: 'abc', name: 'xyz' })
What do the parentheses ( … ) wrapping the object refer to in this instance? Is it a shorthand for return?
No. Those parentheses produce an object literal. Arrow functions have many syntaxes, one of which is:
( … ) => expression
This will implicitly return an expression, for example:
() => 1 + 1
This function will implicitly return 1 + 1, which is 2. Another one is this:
( … ) => { … }
This will create a block to house multiple statements if you don't want to implicitly return an expression, and if you want to do intermediate calculations or not return a value at all. For example:
() => {
const user = getUserFromDatabase();
console.log(user.firstName, user.lastName);
}
The problem arises when you want to implicitly return an object literal. You can't use ( … ) => { … } because it'll be interpreted as a block. The solution is to use parentheses.
The parentheses are there for the { … } to be interpreted an object literal, not a block. In the grouping operator, ( … ), only expressions can exist within them. Blocks are not expressions but object literals are, thus an object literal is assumed. Thus, instead of creating a block, it will use this syntax:
( … ) => expression
And implicitly return an object literal. Without the parentheses, it will be interpreted as labels and strings, not keys and values of an object literal.
let a = () => {
id: 'abc', //interpreted as label with string then comma operator
name: 'xyz' // interpreted as label (throws syntax error)
}
The comma here would be interpreted as the comma operator, and since the operands must be expressions, and labels are statements, it will throw a syntax error.
It allows you to create an expression, so
let a = () => ({ id: 'abc', name: 'xyz' })
specifies that a when invoked, returns the enclosed object
If you remove the () in this case, it will throw an error because it is not a valid function body statement, because the {} in let a = () => { id: 'abc', name: 'xyz' } are interpreted as the boundaries of a statement, but the content inside is not valid if you look at it.
let a = () => {
id: 'abc', /* Not valid JS syntax */
name: 'xyz'
}
What do the curly braces surrounding JavaScript arguments for functions do?
var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
A second possible answer has arisen since this question was asked. Javascript ES6 introduced Destructuring Assignment.
var x = function({ foo }) {
console.log(foo)
}
var y = {
bar: "hello",
foo: "Good bye"
}
x(y)
Result: "Good bye"
The curly braces denote an object literal. It is a way of sending key/value pairs of data.
So this:
var obj = {name: "testing"};
Is used like this to access the data.
obj.name; // gives you "testing"
You can give the object several comma separated key/value pairs, as long as the keys are unique.
var obj = {name: "testing",
another: "some other value",
"a-key": "needed quotes because of the hyphen"
};
You can also use square brackets to access the properties of the object.
This would be required in the case of the "a-key".
obj["a-key"] // gives you "needed quotes because of the hyphen"
Using the square brackets, you can access a value using a property name stored in a variable.
var some_variable = "name";
obj[ some_variable ] // gives you "testing"
Curly braces in javascript are used as shorthand to create objects. For example:
// Create an object with a key "name" initialized to the value "testing"
var test = { name : "testing" };
alert(test.name); // alerts "testing"
Check out Douglas Crockford's JavaScript Survey for more detail.
var x = {title: 'the title'};
defines an object literal that has properties on it. you can do
x.title
which will evaluate to 'the title;
this is a common technique for passing configurations to methods, which is what is going on here.