I am working through a node.js beginners tutorial and came across this piece of code:
const respondEcho = (req, res) => {
const { input = '' } = querystring.parse(
req.url.split('?').slice(1).join('')
)
}
The syntax of this line const { input = '' } = querystring.parse() is a little confusing to me.
It seems like a declaration of a constant object set equal to a method which returns key value pairs. What I don't understand however is the assignment inside the curly braces - if this was an object declaration then it would be like this rather:
const {input: ''}
The input='' seems like it would be a default value on the object. Could someone explain the meaning of this syntax?
const { foo = '' } = bar
means that you are destructuring the foo property from bar and you are assigning a default value to it incase it is falsy.
It is practically the same as doing:
let foo = bar.foo;
if (foo === undefined) {
foo = '';
}
It is a destructuring assignment with a default value in the case that the value unpacked from the object is undefined.
Related
I'm looking for a better syntax for writing the following code, and I would like to know if there is an option for assigning the return value of a function by using a destructuring assignment:
const object = {
property: 10,
getFunction() {
return "getFunction value";
}
}
const {property, getFunction} = object;
console.log("Property: ", property, " getFunction: ", getFunction);
Here, this code returns the following, which is totally normal:
"Property: 10, getFunction: [Function: getFunction]"
I'd like to know if there is a syntax option to write something like: (won't work)
const {property, getFunctionValue: getFunction()} = object;
And get the "getFunction value" from the assignment.
Unfortuntely, the syntax you're looking for doesn't exist (I've also wanted to do it many, many times). You can't call a function you're retrieving as part of a destructuring operation.¹ You're not allowed to use an arbitrary expression for the "from" part of a destructuring pattern. Destructuring always does property access, not function calls.
You'll have to do it separately, e.g.:
const { property } = object;
const getFunctionValue = object.getFunction();
or similar.
¹ unless it's the getter function for an accessor property
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 4 months ago.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
Second try:
var A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?
The correct way is:
const A = 0;
const LOOKUP = {};
LOOKUP[A] = 'A';
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
const LOOKUP = { A : "A"};
The left side of the colon means that the key is the string "A". The string part is implicit, since all keys are strings (or symbols). So to access the property, you need to do console.log(LOOKUP.A) or console.log(LOOKUP["A"])
If you want the key to be a computed value, then you need to use square brackets:
const LOOKUP = { [A]: "A" };
That means that we should resolve the variable A, and use its value as the key. That key is the number 0, which then gets coerced into the string "0". You can then look it up by any of console.log(LOOKUP["0"]), console.log(LOOKUP[0]), or console.log(LOOKUP[A])
Looks like you are searching for some enums (typescript):
enum ETest {
A = 1
};
console.log(ETest['A']); // 1
console.log(ETest[1]); // A
Doing LOOKUP[A] is like doing LOOKUP[0] which is undefined.
You should try it as
console.log(LOOKUP["A"])
This has nothing to do with const or var keyword. The way you are trying to access an object property is incorrect.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP["A"]); // Correct Approach: Property access through bracket notation should be done using a string (or a variable assigned to a string).
console.log(LOOKUP[0]); // Property `0` doesn't exist on object `LOOKUP`, so it'll return `undefined`.
I found a fix for my application, but I copied and pasted the code, which doesn't match with the rest of the code, I want to turn these ternary operators into if/else statements.
const name = persona ? persona.player_name : steamID.getSteamID64();
I tried to do:
const name = persona;
if (name = persona) {
persona.player_name;
} else {
steamID.getSteamID64;
}
But it didn't work, any help will be appreciate it thanks!
Just do:
let name = '';
if (persona) {
name = persona.player_name;
} else {
name = steamID.getSteamID64();
}
The mistake is, that the ternary operator doesn't check for equality in this example but for undefined, that means that you example will translate to the following:
let name = undefined;
if (persona !== undefined) {
name = persona.player_name;
} else {
name = steamID.getSteamID64();
}
It would be written in human language like this: If persona is defined, assign property player_name to the variable named name. If persona is not defined, assign the result of steamID.getSteamID64() to name.
This is possible because just checking if(foo) is a shorthand for if (foo !== undefined). And the ternary operator is an inline if-condition, so if(foo) can be translated to foo ? then : else.
You could take a var statement for declaring the value and assign later.
const needs a value and be careful by taking name as variable, becaus this is a short form of the window's name window.name.
var name;
if (persona) name = persona.player_name;
else name = steamID.getSteamID64();
I have encountered the following code online:
function bar() {
return {
x: 4,
y: 5,
z: 6
};
}
var which = "x",
o = {};
( { [which]: o[which] } = bar() );
console.log( o.x );
I understand that this code is an example of the "destructuring syntax" that was introduced in ES6.
I also understand that o[which] is searching for a key named which in object o and if found, return the value for the which key.
But I'm not really sure how the [which]: part of the expression works.
In destructuring syntax, when you see from : to, it means that the value of the property identified by from is taken from the thing being destructured and assigned to the variable or property identified by to. So looking at that line:
( { [which]: o[which] } = bar() );
...we see that the value of the property identified by [which] is retrieved from the object returned by bar and assigned to the property identified by o[which]. Since [which] is used rather than which, it's the value of the which variable that determines the name of the property taken from bar's returned object, just like when you use brackets syntax when retrieving or setting the value of a property on an object.
The non-destructuring version would look like this:
const tmp = bar();
o[which] = tmp[which];
The [which]: construct is part of computed properties syntax (ES2015+).
In the following JS (es6) code, what is going on with the variables inside of the curly braces with the colon?
const { foo: bar } = ...
Normally when you see this it is doing variable assignment from right to left, as in Objects. In objects it would assign the variable bar to the object key foo, but that doesn't seem to be what is going on here. What is this doing?
It is best to think of destructuring kind of like the opposite of declaring an object, so where
const hidingSpotConnection = ...
const obj = { connectionType: hidingSpotConnection };
would make an object obj with a key connectionType containing the value from the hidingSpotConnection variable,
const { connectionType: hidingSpotConnection } = ...
takes the value from the connectionType key and stores it in a variable called hidingSpotConnection.