This question already has answers here:
Getters \ setters for dummies
(14 answers)
Closed 5 years ago.
my so far understanding with object literal is we can use it like the key value pair, where key is the property and the value can be a actual value, a function or a anonymous function
function a() {
return 'value b';
}
var result = {
'keya': 'valueA',
'keyb': a,
'keyc': function () {
console.log('some value');
}
};
till i read this block of code
var obj = {
log: ['test'],
get latest() {
if (this.log.length == 0) return undefined;
return this.log[this.log.length - 1];
}
}
console.log(obj.latest); // Will return "test".
my question is, in the above code the function latest() doesnt have any key then how can it be used inside a object literal, am i missing something
This is ES6 (which is also called ES2015) syntax, it's a newer version of Javascript that lets you do this.
You would've had to have the key there in ES5 code.
Related
This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 5 years ago.
I've noticed things like this work:
let x = { a: 1 };
function reassignProperty(obj, key, newValue) {
obj[key] = newValue;
}
reassignProperty(x, "a", "hello");
console.log(x.a); //prints hello
But this doesn't:
function reassignObject(obj) {
obj = { a: "some new value" };
}
reassignObject(x);
console.log(x.a); //still prints hello
It seems you can reassign properties of an object (pointers within an object), even if the values are reference types themselves. i.e. we could do things like reassignProperty(x, "a", { inner: 55 }), and it will still be the same outside the function scope. But reassigning the reference to the object itself doesn't?
I've seen people argue javascript passes variables into functions by value, but not by reference. Why then does it seem to able to reassign the properties inside the object, and have access to the changes outside the function scope? This doesn't seem to me to be strictly "pass by value"
In the second case use dot notation instead of object literal
let x = {
a: 1
};
function reassignObject(obj) {
console.log("Passed from function call ", obj);
if (obj.hasOwnProperty('a')) {
obj.a = "some new value"
}
console.log("After reassinging value ", obj)
}
reassignObject(x);
console.log(x.a);
This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
I entered this expression in the Firefox and Chrome Dev Console and I wonder why it is valid JavaScript:
var x = { a (b) {} };
console.log(x);
x is then set to an object with the property "a" containing a function called "a" with an argument identifier "b".
How is this valid JavaScript syntax? The colon is missing after "a" and I do not understand the function definition.
This is ES6 / ES2015 syntactic sugar (Property shorthand).
With ES6:
const obj = {
a(b) {
// Shorthand method
// `this` context is `obj`
},
c
};
is equal to
var obj = {
a: function a(b) {
},
c: c
};
In JavaScript, when you write:
var x = { a (b) {} };
It will consider it as:
var x = {
a: function (b) {
}
}
For example, you can check this and it will clear your doubt:
var x = { a (b) { console.info('function called') } };
x.a();
This will call the function which is assigned to property a of object x.
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
Is there a short form of doing such operation:
function doObject(key, value){
let object = {};
return object[key] = value;
}
UPD: forget about function, I use it just to isolate scope and provide to params key and value. I don't need to implement the function but logic that it does
const doObject = (key, value) => ({[key]: value});
// ^^^^^^^^^^^^ ^ ^^^^^
// 1 2 3
Arrow function syntax
Wrapping with braces allows you to return an object literal without the extended syntax. (Otherwise, it thinks the {} are the block delimiters.
Computed object literal property key.
You can use a computed property name for the object:
function doObject(key, value){
return {
[key]: value
};
}
This question already has answers here:
Accessing Properties in object [duplicate]
(3 answers)
Closed 7 years ago.
I used to believe that there is no difference between them but after seeing this piece of code, all my information about objects in Javascript failed.
var search = function(name) {
for(var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
This code works. But
var search = function(name) {
for(var x in friends) {
if(friends.x.firstName === name) {
console.log(friends.x);
return friends.x;
}
}
};
this doesn't.
Thanks for explaining.
friends.x is not the same thing as friends[x], it's the same thing as friends['x'].
When you use friends[x] the value x can be a variable (or any expression), but when you use friends.x the x is a literal name, it won't use the variable x.
As #Guffa already explained, friends.x and friends['x'] are the same, the difference in those approaches is that when you use [] this syntax you can use variables, 'property like this', or reserved words, this is good when you do not know exactly the property you will need.
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.
Heres the situation:
I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this:
[ { key: '1' }, { key: '1' } ]
(.map() returns an array of objects fyi)
I need key to actually be the string from this.attr('name').
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).