When will I use this kind of function declaration? [duplicate] - javascript

This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 6 years ago.
I saw this kind of function declaration many times when reading other peoples's code.
var foo = function bar() {
console.log("Some text");
};
And I got this result.
foo(); // "Some text"
bar(); // Uncaught ReferenceError: bar is not defined(…)
Since bar stays undefined, I wonder what the purpose of writing bar there and the difference if I write it with omitting bar. However, I wonder if there is a certain condition or a reason why people write function like that.
When will I write function like that?

When you write var foo = function() {} you declare a variable named foo that has an anonymous function (function that has no name).
When you write var foo = function bar() {} you declare a variable named foo that has a function named bar. This is useful for debugging. When you have an error, it will show that it's in function bar().
Since function names are only available inside the function, calling bar() throws an error.

Related

Why does the "typeof" of a named function expression return undefined? [duplicate]

This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 3 years ago.
I'm new to JS, so please forgive me if this sounds stupid. I was playing with the concepts of function declaration and function expression.
I have the following code:
var printSomething = function printSomeString(string) {
console.log(string);
}
console.log(typeof printSomething); // function
console.log(typeof printSomeString); // undefined
If I go by the definition of hoisting in JavaScript, by the time I use printSomething and printSomeString, they should be available since their declarations have been hoisted.
typeof printSomething returns function, but typeof printSomeString returns undefined. Why so?
Isn't this named function expression already declared and hoisted before being used?
Isn't a named function expression itself a function?
Also, when I call printSomeString('Some STRING'), it returns the following
Uncaught ReferenceError: printSomeString is not defined
What is going on here?
printSomeString is a not a global variable its local variable to the another function printSomething. Try using console.log() inside it.
var printSomething = function printSomeString(string) {
console.log(typeof printSomeString)
}
console.log(typeof printSomething); // function
printSomething()

Why javascript function parentheses can not access the outside? [duplicate]

This question already has answers here:
Why a Name Function Expression not available outside function body [duplicate]
(3 answers)
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I'm curious, why not just javascript function scope it? Why just add a parenthesis can not access it? My guess is that the parentheses and javascript related operations, but do not know exactly why this child principle and design?
(function test(){
console.log( test );
})();
test();//Uncaught ReferenceError: test is not defined IE8- is ok
or
(function test(){
console.log( test );
});
test();//Uncaught ReferenceError: test is not defined IE8- is ok
When you wrap a function in parentheses like you did, it does put it in a new scope.
It also acts like a return value, which is why it can be called as an IIFE, or Immediately Invoking Function Expression.
Another way to re-write it, which will make more sense is like so:
var myFunc = (function test(){
alert('Hello!');
});
myFunc(); // Works!
test(); // Doesn't work!
To learn more about this, you should read about IIFE - Immediately-invoked function expression.
The short version - the function runs in its own scope, unless you pass parameters to it, like so:
(function test(x) {
alert(x); //alerts "yey!";
})("yey!");

Different ways of naming functions? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
In Javascript what is the difference between:
var name = function() { //stuff to do };
{name : function() { //stuff to do } };
function name() { //stuff to do };
As written by Stoyan Stefanov in "JavaScript Patterns":
In function declarations and named function expressions, the name
property is defined. In anonymous function expressions, it depends on
the implementation; it could be undefined (IE) or defined with an
empty string (Firefox, WebKit):
function foo() {} // declaration
var bar = function () {}; // expression
var baz = function baz() {}; // named expression
foo.name; // "foo"
bar.name; // ""
baz.name; // "baz"
The name property is useful when debugging code in Firebug or other
debuggers. When the debugger needs to show you an error in a function,
it can check for the presence of the name property and use it as an
indicator. The name property is also used to call the same function
recursively from within itself. If you were not interested in these
two cases, then an unnamed function expression would be easier and
less verbose.
The case against function declarations and the reason to prefer
function expressions is that the expressions highlight that functions
are objects like all other objects and not some special language
construct.

could you explain the function in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
(function(){
var foo = 'Hello world';
})();
i don't know what's use of it? and what's meaning of it/?
On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.
That said, what you have is an immediately invoked function expression, i.e. an anonymous function:
function() { ... }
which is invoked with no parameters:
(f....)();
The rationale is two fold:
it allows the function to be defined and called without giving it a name in the global name space
any variables defined within the function are also held within that scope, and don't pollute the global name space.
It's an anonymous function that executes immediately.
The idea is to create a private scope. Often one would return a closure from the anonymous function that retains access to variables created in that scope.
For example
var greet = (function () {
var foo = 'Hello world';
return function () {
alert(foo);
}
}());
greet();
This calls an anonymous function immediately.
Have a look here: What does this “(function(){});”, a function inside brackets, mean in javascript ?

Difference between 'var foo = function ...' and 'function foo() ...' [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
“Usual” functions vs function variables in JavaScript
What do you call this JavaScript syntax, so I can research it?
Is there a fundamental difference between
function foo()
{
things();
}
and
var foo = function()
{
things();
}
Or is function ... just syntactical sugar?
Thanks in advance.
They are different (but produce similar results). Basically, the first is an actual named function. The second is a regular variable declaration with an anonymous function attached to it. There are some subtle differences...they are summed up nicely here:
JavaScript Function Declaration Ambiguity (Be sure to read the comments too...more good info there)

Categories