This question already has answers here:
Object destructuring without var, let or const
(4 answers)
Closed 1 year ago.
let b = { a: 123123123 };
try {
({ a } = b); <<< what is the meaning of ()
} catch (error) {}
console.log({'a':a})
why this script work, what is the meaning of () in try-catch .
the { a } = b is wrong but ({ a } = b) is correct and the variable will go out of try-catch and give new value to a.
if there are a function in () may be a IIFE, if in expressions the () is a Grouping operator.and in my example,what is the meaning of ()
A pair of parenthesis force the contents to be treated as an expression instead of a statement.
This causes the { to be seen at the start of an object or dereferencing structure (the latter in this case) instead of a block.
Related
This question already has answers here:
Is it possible to initialize an object as a function with properties?
(2 answers)
Closed 1 year ago.
I know that I can create a function:
const fn = () => {}
And I know that I can attach a property to it:
fn.a = 'a'
Can I use some kind of object literal syntax to do what I did above in one statement?
I'm thinking something along the lines of:
const fn = {
(): {},
a: 'a'
}
You could do it in one statement like this.
const fn = Object.assign(() => {}, { a: 'a' });
How about we make a little utility function to accomplish that?
function createFunc(func, props) {
Object.keys(props).forEach((key) => (func[key] = props[key]));
return func;
}
const f = createFunc(() => console.log("hello"), { a: "A", b: "B" });
f();
console.log(f.a);
console.log(f.b);
I am reading about Reactjs, and one thing that I don't understand in the following syntax (taken from here)
this.setState(state => ({showWarning: !state.showWarning}))
is the () around the object. I understand that we use () for JSX, but the object {showWarning: !state.showWarning} is a JS object. Also I found this notation when using Redux as in
const mapStateToProps = state => ({...})
Why do we do that in React?
It's not specific to react. Arrow functions have a shorthand which allows you to skip the explicit return if you only have one statement. So a function like this:
const example = (val) => {
return 'foo'
}
can be shortened to this:
const example = (val) => 'foo';
But note that the way you do this is by leaving out the curly brackets of the function body. If you try to return an object, you're going to be sticking in curly brackets, so javascript thinks "ah, this is the function body", when really you want the brackets to mean an object literal. To clear up the ambiguity, you need to wrap the object in parentheses, so there's no possible way it could be interpreted as a function body.
const example2 = (val) => {
return { foo: 'bar' }
}
// can't become this:
//const example2 = (val) => {
// foo: 'bar' // this is not a key/value pair of an object! This is a labeled statement
//}
// so instead it becomes this:
const example2 = (val) => ({
foo: 'bar',
});
It's not exclusive to React.
When using Arrow functions, the expression to the right of the arrow is returned. But in the case of objects, the interpreter would interpret the braces as a multi-line function.
The parenthesis are there to denote that an object is to be returned as opposed to a function block declaration.
Quoted from the Syntax section of MDN:
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
// Parenthesize the body of a function to return an object literal expression:
params => ({foo: bar})
{showWarning: !state.showWarning} is definitely a valid javascript object but not everywhere it will work as an object because {} is also used for code block. If you return any object implicitly from an arrow function without () javascript will consider it a code block rather than an object
() is just used to make engine think that we are try to use an expression here not a code block which is statement
This is ES6 syntax for running a function that returns an object.
Because Javascript functions can create a new block by wrapping curly braces around, there is some ambiguity as to whether you are about to create this new block or if you're trying to return an object using implict return. So by wrapping the object in () you tell JS that you are trying to return the object inside implictly.
It just keeps the code lean and is more modern so that's why people use it.
Examples:
const ex1 = () => 1 // returns 1, no ambiguity
const ex2 = () => {return 1} // same as above, but with explicit return
const ex3 = () => {a: 1} // error! thinks it's a new block, not an object
const ex4 = () => ({a: 1}) // returns {a: 1} because wrapped in ()
This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Es6 Arrow function to normal js
(2 answers)
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 3 years ago.
Actually, I'm working with someone else code and they used arrow function in a line. I'm having trouble to replace it with regular function.
This is the line:
const R = (elem) => object(document.querySelector(elem));
I've tried to change it like:
const R = function(elem) {
object(document.querySelector(elem))
};
But no good result. :(
Arrow functions have a built in way to shorten a return syntax: If an arrow function is simply returning a single line of code, you can omit the statement brackets and the return keyword. This tells the arrow function to return the statement. So the only thing you need to do is to add the return keyword explicit if you are not using an arrow function.
const R = function(elem){ return object(document.querySelector(elem)) };
And be careful if you try to translate an arrow function which is using this keyword.
UPDATE: Response to comment
In the following code there are parenteses used to define an object with a function as property. If you don't use parenteses you need braces and return inside this arrow function, otherwise you get an SyntaxError.
const object = (elem) => ({
css: function(attribute, value) {
elem.style[attribute] = value;
return object(elem);
}
});
Without arrow functions it becomes:
const object = function(elem) {
return {
css: function(attribute, value) {
elem.style[attribute] = value;
return object(elem);
}
};
}
This question already has answers here:
Curly Brackets in Arrow Functions
(3 answers)
What does the arrow function with a () after means? [duplicate]
(3 answers)
Closed 4 years ago.
I am taking a course on React Native and realize that the instructor declares functions in two different ways, for seemingly no different reasons. Please explain when each function declaration should be used:
example = () => ();
vs
example = () => {};
Thank you
Arrow functions can differ in function bodies (Thanks Robbie). The concise function body can only consist of a single expression which is evaluated and implicitly returned. The conventional block function body requires the return keyword or it will return void.
example1 = () => 1 + 1;
example2 = () => {
const result = 1 + 1;
return result;
};
example3 = () => {
const result = 1 + 1;
};
example1() has a concise body and will implicitly return the result of the expression 2.
example2() has a block body and does explicitly return 2.
example3() has a block body and no explicit return, therefore it returns void.
Note that the normal braces () around a concise function body are required if you want to return an object literal:
example = () => ({some: 'object'});
This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Closed 5 years ago.
I creating an object that uses async function methods with babel-polyfill/babel-preset-es2017, however I am having a problem with this:
let obj = () => {
return {
doAsync: async () => {
let thing = await longProcess()
return this.transform(thing)
},
transform: (thing) => {
return psuedoCodeTransform(thing)
}
}
}
let instance = obj()
instance.doAsync()
// TypeError: cannot read property 'transform' of undefined`.
Is this something described in ES2017, a babel-polyfill/regeneratorRuntime gotcha?
Arrow functions do not create their own context. They don't have their own this and this will refer to the enclosing scope's context. In this case (no pun intended), this does not refer to the same object as instance at all.
If you log this inside doAsync, you'll notice it's the window global.
Joseph the Dreamer's response is exactly right obviously, but since I work best by example, here is your code changed which should make it work. Notice the only change is actually defining doAsync as a normal function instead of arrow function:
let obj = () => {
return {
doAsync: async function() {
let thing = await longProcess()
return this.transform(thing)
},
transform: (thing) => {
return psuedoCodeTransform(thing)
}
}
}
let instance = obj()
instance.doAsync()
// TypeError: cannot read property 'transform' of undefined`.