Self Invoking Functions [duplicate] - javascript

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 4 years ago.
Importance of using ! in this code
var testValue;
!function test() { testValue = 3; }();
console.log(testValue);

The ! indicates to the interpreter to parse what follows as an expression rather than as what would otherwise be a function declaration. Function declarations can't be invoked on the same line, so without the !, a SyntaxError would be thrown:
var testValue;
function test() { testValue = 3; }();
console.log(testValue);
Only function expressions can be immediately invoked. Though, to indicate a function expression, it would probably be clearer to use parentheses around the function rather than !, and there isn't all that much point to naming the function test if the function name isn't used anywhere, eg:
var testValue;
(() => {
testValue = 3;
})();
console.log(testValue);

Functions are not automatically objects. You should define it inside brackets or assign it to a variable. If you use ! for function definition. It means
!(function(){console.log("hi");})
Now you can insert () to run that function.

Related

What exactly is function expression? [duplicate]

This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Why JavaScript function declaration (and expression)?
(5 answers)
Why use named function expressions?
(5 answers)
Closed 1 year ago.
I thought before that function expression can be any function that is store in some variable. For example, this is function expression, because function is stored in func variable.
let func = function() {
console.log(5);
};
And here's function expression, because callback function is stored in function's paremeter callback.
function func(callback) {
callback();
};
func(function() {
console.log(5);
});
//That's what I mean:
//let callback = function() {...}
But... recently I've found out that this callback function can also be considered as function expression. Why? This function isn't stored in some variable.
let arr = [18, 50];
let obj = {
name: 'Karina',
};
arr.forEach(function func(value) {
console.log(`${this.name} is ${value} years old`);
}, obj);
So, my question is...What exactly make function function expression?
I thought before that function expression can be any function that is store in some variable.
No. The variable to store to does not matter. The let func = …; is not part of the function expression, the function expression is only the part (expression) that comes in the middle.
let func = function() {
// ^^^^^^^^^^^^
console.log(5);
//^^^^^^^^^^^^^^^^^^
};
//^
This function isn't stored in some variable.
Actually there's no difference between your second and third snippet. You're passing the function constructed from the expression to a function, regardless how that function is declared (with parameters, with rest syntax, without parameters, or as a builtin like forEach).
But yes, you can have function expressions completely without variables, like in
!function() {…}();
// ^^^^^^^^^^^^^^
void function() {…};
// ^^^^^^^^^^^^^^
(function() {…})();
// ^^^^^^^^^^^^^^
Basically, function expressions are just the literal syntax (as in: object literal, string literal) for function objects.
I'm also learning about functional programming and found out that using a function as a value is indeed a function expression, as you said, by assigning an anonymous function to a variable. But I think the main difference relies on the function declaration being hoisted right? So context comes to play and all of that fun stuff :)

Why function aren't hoisted after return statement? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 months ago.
const func = () => {
someFunction() // error here
return function someFunction() {
console.log('hello')
}
}
func()
I've created closure and wanted to check hoisting inside of func function. Each time when you create function declaration it hoists your variable up to the top. Why is someFunction not hoisted?
When you put a function after return statement, it no longer is a function declaration, but rather a function expression. Unlike declarations, function expressions are not hoisted.
Function expressions in JavaScript are not hoisted, unlike function
declarations.
- MDN
You have a (named) function expression in your return statement. This function is not a function statement and because of this, it is not hoisted.
Another reason is, a function expression has no name. That means, you can not access it by the a name outside of the function. The name of a function expression is only available inside of the function with it name (for example for recursions).

javascript named function call throwing error [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
What's the point of naming function expressions if you can't really reference them by the names you give them? [duplicate]
(5 answers)
Closed 5 years ago.
var boo= function foo(){
console.log("I am foo");
}
boo(); // output: I am foo
foo(); // output: Uncaught ReferenceError
I am little confused with javascript named function. Can any one please explain why in above code snippet the foo() function call is throwing the error. Thanks in advance
var boo= function foo(){
There is a clear difference between a function and function expression.
What you have is an expression resolved to a variable. The way you are expecting to work needs to be a function or a variable resolved by a function expression.
From MDN docs
Here is an example of an anonymous function expression (the name is
not used):
var myFunction = function() {
statements
}
It is also possible to provide a name inside the definition in order
to create a named function expression:
var myFunction = function namedFunction(){
statements
}
One of the benefit of creating a named function expression is that in
case we encounted an error, the stack trace will contain the name of
the function, making it easier to find the origin of the error.
As we can see, both example do not start with the function keyword.
Statements involving functions which do not start with function are
function expressions.

Why Self-Executing Anonymous works? [duplicate]

This question already has an answer here:
Difference in these tiny syntax variations for an IIFE? [duplicate]
(1 answer)
Closed 6 years ago.
I know about Self-Executing Anonymous. And usually we create them as
(function(){ return 1;})()
the reason - parser feature which didn't run if we use
function(){ return 1}()
But today I found that next code works too ( check brackets order )
(function(){ return 1;}())
function(){ return 1; }() still give me SyntaxError, as it should
Please explain why? Thx for reference to get more details
P.S. the question is about (function(){ return 1;}()) variant!
(function() {})()
and
(function() {}())
are equivalent.
To call second example you can include + operator before function
+function(){ return 1 }()
See Immediately-Invoked Function Expression (IIFE)
The phrase IIFE is a better term for these functions .. Immediately Invoked Function Expressions.
As for why they are the same: The outer parens () simply make an expression and the () together do the invocation.
(function(){ return 1;})()
is the same as:
(function(){ return 1;}())
(function(){ return 1;})()
becomes
(functionexpression)()
becomes
functionexpression()
and
(function(){ return 1;}())
becomes
(functionExpression())
becomes
functionExpression()
for the same reason that
(3)+2 is the same as ((3)+2).
EDIT
function(){ return 1; }()
Does NOT work because a function statement is different from a function expression. Function statements cannot be immediately invoked.

What is the point of using a named function expression? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Why use named function expressions?
(5 answers)
Closed 9 years ago.
I'm going through this blog about the difference between function declarations and function expressions.
It gives these two examples. They call the first an "anonymous function expression" and the second a "named function expression."
// anonymous function expression
var a = function(){
return 3;
}
// named function expression
var b = function bar(){
return 3;
}
I tested these two in Chrome's JS console and I see the following:
a()
=> 3
b()
=> 3
bar()
=> bar is not defined
My question is: In the second function expression declaration, what is the point of "bar"? In general, why does one ever use a named function expression?
Some people prefer to do it like this because if errors occur, your functions have names. It's mostly a matter of preference and how often you have trouble with unnamed functions.
You don't normally see it used in a var declaration, but instead when declaring callbacks:
callbackFunction(function success() { ... }, function fail() { ... })
That way you know which argument is which, they're labelled, and if one of them fails you get a precise indication of which one broke.
var b = function bar(){
return 3;
}
bar()
=> bar is not defined
The identifier bar is only available inside of the function. Try
var b = function bar() {
console.log(bar);
}
b();
why does one ever use a named function expression?
To allow referencing a function expression that was not assigned to a reachable or constant variable, e.g. for recursion in an IEFE.
Also, named functions show up different during debugging, e.g. in call stack (trace)s or breakpoint listings. Often you can use a (named) function declaration instead of a function expression, see also http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html.

Categories

Resources