How to declare a react js declare function? - javascript

There are many different ways of declaring a function, some end with semicolon others not. I would like to know what the difference is:
A
addUser = id => {
this.setState(// ...);
};
B
selectTask(option) { this.setState({task: option}); }

This is more related to Javascript then React itself.
First one is a function expression and semicolons are recommended for them since there could be some edge and weird cases we can encounter. Examples:
const foo = function() {
console.log("first");
};
// Do not bother with this function too much, it is here to mimic our error,
// and does not have to be an arrow function.
(() => console.log("second"))();
What we expect is here to see second as output and if you run this we actually see. What if we omit semicolon in the first expression?
const foo = function() {
console.log("first");
}
(() => console.log("second"))();
What happens here is since we omit semicolon our second iife function is taken into account as an argument for our first function and our first function is executed but this is not what we intended here.
But, for function declarations this is different.
function foo() {
console.log("first");
}
(() => console.log("second"))();
Omit the semicolon or do not, the result is the same: We see second as output and this is what we expect. Hence, semicolon is not recommended here.
Now, arrow functions are a little bit different about that. Actually they are function expressions and can have two kinds of body type. A concise one which has one single expression and return is explicit. The other one is a body block and needs a return. Now, bear with me since there are different cases here.
const foo = () => console.log("first");
( () => console.log( "second" ) )();
Here we have concise body, a single expression with a semicolon. Everything is as expected, we see "second". But if we omit semicolon:
const foo = () => console.log("first")
( () => console.log( "second" ) )();
it does nothing since there is an explicit return in our arrow function. Now with a regular body block either with semicolon or not:
const foo = () => { console.log("first") }
( () => console.log( "second" ) )();
it is being treated as a function declaration and our result does not change. Actually I'm not quiet sure about my explanation of "treated as a function declaration", if someone corrects me I will be glad to edit my answer.

Option A: is Called Arrow Function
Arrow functions don’t redefine the value of this within their function body. This makes it a lot easier to predict their behavior when passed as callbacks and prevents bugs caused the by use of this within callbacks. Since it is arrow function or function expression it needs to end with a semi-colon.
Option B: is Normal Function it requires this and bind to be used in callbacks. It is a function declaration statement, hence there is no need of semicolon.
Important: Avoid arrow functions and bind in render in react.

if we are binding in render then we don't need to end with semicolon
Click Me
else
this.handleClick = this.handleClick.bind(this);

Related

What is the difference between these two Module pattern forms in Javascript? [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Closure call in JavaScript [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

What is the difference between these function calls? [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

What is the difference between these 2 JavaScript declarations?

For one of them the "()" is inside, for the other one it is outside. Here they are:
var a = (function() {
return {
bla: function() {
console.log('a');
}
};
} () );
var b = (function() {
return {
bla: function() {
console.log('b');
}
};
}) ();
a.bla();
b.bla();
There is no difference.
The [unnecessary] parenthesis are just in different places. The function declaration is already an expression due to where it is located. The parenthesis would make a difference, while still resulting in equivalent code, if the declaration was in a statement context (and ironically they would turn it back into an expression context), which it is not.
The common use of parenthesis in a similar scenario is for self-invoking functions. The parenthesis are required in this case because
function x () { alert("hi!") } ()
is parsed as
function x () { alert("hi!") }; ()
when it appears as a statement -- or "top level element of a block" -- where it is parsed as a "FunctionDeclaration". Thus the following form is often used:
(function () { alert("hi!") })()
This works because function ... is no longer a statement, as above, but an expression (parsed as a "FunctionExpression"), and the expression can continue so the Automatic Semicolon Insertion does not occur as in the previous case. Also note that the function name can be omitted.
However, because in the post the function ... appears in an on the right of an = (in an "AssignmentExpression") it is therefore already in an expression context (is parsed as a "FunctionExpression") and thus no additional parenthesis are needed.
All of these are identical, but I prefer the 2nd form (for consistency within my code):
a = function () {} ()
b = (function () {}) ()
c = (function () {} ())
Happy coding.
There is no real difference. Both work in the same way. If you want to pass JSLint, you will need to use the first pattern, where the invocation parentheses are inside the other set of parentheses. If you don't, you will get the following error:
Move the invocation into the parens that contain the function.
Also note that the first set of parentheses are not required. It will work without them, but again will fail JSLint:
Wrap an immediate function invocation in parentheses to assist the
reader in understanding that the expression is the result of a
function, and not the function itself.
A couple of related questions:
JSLint error: "Move the invocation into the parens that contain the function"
Solution for JSLint errors
There is no practical difference, it's just a subtle difference in how you make the Javascript engine think of the function as a value.
Using ( function(){} () ); you are causing the function to be a value because a statement can't start with a parenthesis. Using ( function(){} ) (); you are using the parentheses to first evaluate the function as a value, then call it.
I think is the same difference of this:
var myObj = {bla:'blabla'};
var a = (myObj);
var b = myObj;
...no difference :)
the ending brackets mean that : When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself. (taken from here)
So, if you use {}(), the function is immediately executed and the variable is assigned with the function result.
Then if you use ({})(), if there's a function between (), it is executed and the value is assigned to the variable.
They are the same thing if they contain the same functions in my opinion.

Is there any difference between putting function call on a self-executing javascript function before or after final parenthesis [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Categories