javascript function declarations and differences in scope [duplicate] - javascript

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
I couldnT find an answer easily, so even if this question is a dupe, the answers donT come up using these keywords.
I want to know the difference between the different way of declaring functions in a sample app.js
var foo = function()
{
//..
}
function bar()
{
//..
}
var baz= function()
{
//..
}
function qux()
{
//..
}
// other??
I m also not clear about the scope where I can use each function. Thanks!

There are four ways to create a function in JavaScript.
Function declaration
This will create a variable foo in the current scope and assign a named function to it.
function foo () {
}
Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. It is considered good coding practise to define them before you use them though.
Anonymous function expression
This will create a function without a name and use it in an expression. In this example it is assigned to the variable something.
something = function () {
};
Named function expression
This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer.
something = function foo () {
};
Function constructor
Do not use function constructors. They are eval by another name. You can read about them on MDN if you're interested.

Related

Does the way a JS function is defined affect it's "performance"? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 7 years ago.
Is there ANY difference in the following two ways of defining a functions?
METHOD 1)
var printName = function(name){
return("Hi! My name is ",name)
}
VS
METHOD 2)
function printName(name){
return("Hi! My name is ",name)
}
and I mean ANY, I'm new at JS and want to lay down my understanding of functions and Objects before I advance as I feel these 2 features are the 2 I'll use the most.
Yes there is a difference, but none that would affect the performance of the function code when it's called.
The difference has to do with when the function is created, but the performance is identical. Using your examples:
printName_1("Drew"); // This will fail, as printName_1 is not defined (yet)
printName_2("user4820485"); // This will work
var printName_1 = function(name){
return "Hi! My name is "+name;
}
function printName_2(name){
return "Hi! My name is "+name;
}
Functions that are declared using the latter syntax are initialized at the beginning of the block where they appear, so it looks like they can be called before they are defined.

Named function expression [duplicate]

This question already has answers here:
Why JavaScript function declaration (and expression)?
(5 answers)
Closed 8 years ago.
I'm assigning a named function expression to a property of an object:
var foo = {};
foo.bar = function bar(){
console.log('bar');
};
foo.bar() => bar
bar() => ReferenceError: bar is not defined
Why can't I call bar() directly, why isn't it defined?
I know that I can simply chain the assignment like var bar = foo.bar = function(){}, so I'm not looking for a work-around or other solution, I'm only interested in why it doesn't work.
I've tested in Chrome console and Node.JS.
Named function expressions are simply not supposed to work that way. The function name is only visible inside the function, not outside.
A function instantiation expression that happens to have a name is not the same thing as a function declaration statement. Those are two distinct syntactic (and semantic) entities in the language.

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.

What is the difference between these two? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Are named functions preferred over anonymous functions in JavaScript? [duplicate]
(4 answers)
Closed 9 years ago.
I saw the following JavaScript functions works exactly same, Then what is the difference between them other than syntax.
The function are:
var functionName=function(){
//some code here
};
function functionName(){
//some code here
}
I call them in the same way as:
functionName();
Please dont' tell me there syntax is different, Other than that is there any difference like
1)speed of execution
2)Memory utilization etc.
Thanks in advance!
This has been answered many times in StackOverflow. It is just the way of naming. So taking up some points from the answers, I would say:
Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there.
Advantages & Disadvantages:
There are few advantages to naming functions:
names for meta analysis. functionInstance.name will show you the name.
Far more importantly, the name will be printed in stack traces.
names also help write self documenting or literate code.
There is a single disadvantage to named functions expressions
IE has memory leaks for NFE
Another main difference
The difference is that functionTwo is defined at parse-time for a script block, whereas functionOne is defined at run-time. For example:
<script>
// Error
functionOne();
var functionOne = function() {
}
</script>
<script>
// No error
functionTwo();
function functionTwo() {
}
</script>
References
var functionName = function() {} vs function functionName() {}
Are named functions or anonymous functions preferred in JavaScript?
Named function expressions demystified
Function Declarations vs. Function Expressions.
var functionName = function() {} vs function functionName() {}
1st one is Named Function Expressions, which should return some value to the caller.
2nd one is just a function, it's upto you whether you return value or not

Why are anonymous functions treated differently from named functions here? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
Today I stumbled upon the following phenomenon:
foo();
bar();
function foo()
{
console.log("inside foo");
}
var bar = function()
{
console.log("inside bar");
}
FireBug complains with the following error message:
bar is not a function
Several tutorials claim that function f() and var f = function() are basically the same thing. Evidently, they are not, but what exactly is going on here?
Function declarations are available anywhere in the scope they're defined in, even before their physical definitions.
var bar = function() { ... }; is a normal variable that happens to hold a function. Like all other variables, it can only be used after its assigned.
(You cannot observe the future value of a variable)

Categories

Resources