This question already has an answer here:
Definition of name property in assignment expression
(1 answer)
Closed 1 year ago.
I create objects using two different notations and then console.log them:
object = {key: 'value', func: function() {}};
console.log(object);
output: { key: 'value', func: [Function: func] }
object.key = 'value';
object.func = function() {};
console.log(object);
output: { key: 'value', func: [Function] }
Why there's a difference in the outputs? Does it matter?
This has nothing to do with dot notation and bracket notation.
In example (a) you are declaring a property name (func) and value (a function) in an object literal. In example (b) you are assigning a function to a property afterwards.
In the first case, func is used as a Binding Identifier which is used to give the function a name.
That isn't the case in the second example.
This isn't likely to make much difference, but function names can be useful when debugging. You can give a function expression a name explicitly:
object.func = function func () {};
Related
This question already has answers here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I am new to React. Recently I came across an application wherein some function had the definition as:
async function (a, b) => {//body} which is quite understandable. But also in the same apllication some functions had the structure as async function ({a,b}) => {//body}. What is the difference between defining function between the above two methods?
The second example is destructuring the function arguments. It basically provides a shorter syntax for extracting an object key's value without the dot notation mess
Let's say you have an object
const myObject = { x: 1, y: 2 };
So, when you pass myObject to the function, you can call the variables without the dot notation. This makes the code easier to read.
function myFunction({ x, y }) {
//Here you can use directly x instead of myObject.x
}
You can read more about destructuring here
in the first function your parameter are 2 different variables
, in the second function they are parameters of the object you are passing
like
let Cat = {
name:"catty",
color:"gray"
}
secound example you pass the whole object like this
function ( Cat ) {}
function ( { name , color } ) {
/// here you can use name and color as "catty" and "gray"
}
if you use the first expample you would have to specify the parameters like this
function (Cat.name , Cat.color) {
}
the word async refers to waiting this function to call
In the first case, there are 2 arguments passed into the function, in the second the first argument passed into the function is an object which is being destructured.
const obj = { a: 1, b: 2 }
async function foo({ a, b }) => {
a; // 1
b; // 2
}
foo(obj);
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }
This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
Accidentally I written a code like below,
var x = {hai:10,test(){ alert("I am alive")}};
x.test(); //alerting the value
It is working fine and I wonder how this code is working? since it was considered previously as an invalid grammar. And I know, In ECMAscript 6, there is a shorthand for assigning properties has been introduced.
Example:
var x = 5, y = {x}; // is as same as var x=5,y={x:x};
But I am not sure about the function definition. Can anyone explain about it with proof from documentation?
This is a Feature coming with ES2015. You can skip the function-keyword for method-definitions (not for plain functions).
So { doSth(){/*...*/ } } is simply a shorthand for { doSth: function(){/*...*/ } }
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions
MDN
Starting with ECMAScript 2015 (ES6), a shorter syntax for method
definitions on objects initializers is introduced. It is a shorthand
for a function assigned to the method's name.
Syntax
var obj = {
property( parameters… ) {},
*generator( parameters… ) {},
// also with computed keys:
[property]( parameters… ) {},
*[generator]( parameters… ) {},
// compare ES5 getter/setter syntax:
get property() {},
set property(value) {}
};
You are now able to shorten this to:
var obj = {
foo() {},
bar() {}
};
MDN Links to ECMA
Enhanced Object Literals
Object literals are extended to support setting the prototype at
construction, shorthand for foo: foo assignments, defining methods,
making super calls, and computing property names with expressions.
Together, these also bring object literals and class declarations
closer together, and let object-based design benefit from some of the
same conveniences.
var obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
Reference : https://github.com/lukehoban/es6features#enhanced-object-literals
This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 7 years ago.
I have object. I want to add properties but I want to compute the suffix for all properties in my object during definition.
var myObject = {
foo: "bar",
[ "prop_" + "Access foo property: foo" ]: 42
};
Below is my expected output:
{
foo: "bar",
prop_bar: 42
}
It's not the case that i'm unable to achieve it. i can able to achieve by the below snippet and its working fine but i want this to be done during declaration.
let myObject = {
foo: "bar"
};
myObject[ "prop_" + myObject['foo'] ] = 'hello'
Note to Reviewers: I have already reviewed the below questions.
Is there a shorthand for this in ES6/ES7?
ES6 Object Literal Property Value Shorthand
How to use ES6 computed property names in node / iojs?
ES6 Computed (dynamic) property names
I feel that there will be better solution than above approach, below are my questions.
What is best approach for this scenario?
How many ways we can achieve this ?
Its not possible during declaration ?
You can create factory function to do this, e.g.:
const create = v => ({
foo: v,
["prop_" + v]: 42
});
let myObject = create("bar");
or inline:
let myObject = (v => ({
foo: v,
["prop_" + v]: 42
}))("bar");