Javascript function differences, is there any? [duplicate] - javascript

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 6 years ago.
When I run a function in js it seems to work fine but will this be fine?
function myfunction(){
}
VS
var myfunction = function(){
}
Because both are called the same so does it make no difference?
Sorry new to js so i'm just making sure it's good to learn this style. (The first function is what i'd prefer to use.)

This question is already asked at this link,
One of the basic difference comes from declaration, for instance :-
foo();
var foo = function(){
console.log('hi');
}
would lead to undefined, since it is called before it's declared, on the other hand,
foo();
function foo(){
console.log('hi');
}
would console 'hi' with no problem, for further insight check the above link.

As shown in the W3Schools Function guide
You can use a function declaration or a function expression.
Both are the same in general. Thought there are certain things to consider:
In a function expression the function is only defined when that line in code is reached
In a function decleration the function is defined as soon as the code is run, so it can be called before it is written in your code (due to hoisting)
The first example you wrote is a function Declaration
The second example you wrote is a function Expression
The only difference between the two is how you will invoke them in your code after you defined them.
If you are wondering which is better, it all comes down to which you are more comfortable with and think the syntax for is more readable, also try not to mix up the two to keep conventions in your code.

Related

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.

var someSome = (function () { ... } ()); a weird javascript asking? [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 8 years ago.
I cannot think of the term that JavaScript developers use for this kind of practice.
var someSome = (function () { ... } ());
-- Wrapping function within brackets. I vaguely remember someone was calling this fiif? fiff?
And there were many advantages and it was recommended java scripting practice.
Anyone got clue what I am talking about and why is it a good practice?
it might have been even without assignment like below
(function () { ... } ());
Self executing function. Often used as a wrapper around a function block to immediately invoke it, as well as give it closure.

Why is the function with in parenthesis? [duplicate]

This question already has answers here:
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 8 years ago.
Question:
Why is the function wrapped in a parenthesis? I have taken this code out of parenthesis and it works with no trouble.
What is the benefit of having the code in a (function() { ...Code Here...})(); like it is in the following example?
Code:
(function() {
"use strict";
// Doesn't work because strict mode
// enforces the fact that the second example shouldn't work
if (true) {
function fn1() {
// This won't run
console.log("doesn't work -- have a great Die Hard Day XIII");
};
fn1();
}
})();
Code Here: What would sending the JQuery word as a parameter do for this namespace. I know that the reason that the function is enclosed in (...) is to create a namespace. I guess a better question would be as to why one would pass in a variable, but I would imagine that would be in case another namespace needed the variable.
( function( $ ) {
// Init Skrollr
var s = skrollr.init({
render: function(data) {
//Debugging - Log the current scroll position.
//console.log(data.curTop);
}
});
} )( jQuery );
I have taken this code out of parenthesis and it works with no trouble.
That’s not correct; it can’t run (or even be parsed) by itself. JavaScript sees function in a place where a function declaration can be and assumes it’s a function declaration. Parentheses are used to force the context to be an expression. The practice is redundant if it’s unambiguously a function literal – say, in a variable declaration – but many find it more readable. There’s a jsHint option to enforce it, for example.
Because then they are calling it:
(function() { ... })();
^^

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

Beginner Javascript: What's the difference between 'function xyz(){}' and 'var xyz = function(){}'? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
I've been going through CodeAcademy's Javascript courses, and a few things have gone over my head. I understand how function work, and I'm trying to wrap my head around OOP and objects/methods.
My question is, what's the difference between creating a function like this:
function countTo(number){
for (var i=1; i<=number; i++){
console.log(i);
}
}
countTo(15);
and creating a function like this:
var countToTwo = function(number){
for (var i=1; i<=number; i++){
console.log(i);
}
};
countToTwo(27);
Both do the same thing and have the same output. Are they exactly the same/interchangeable? Does it matter which one I use when creating a function?
The first one is a function declaration, and is "hoisted", meaning it's immediately available anywhere in the context.
The second one is a function expression, and is treated just like any other variable declaration/assignment. The declaration of countToTwo is hoisted and immediately available anywhere in the scope in which it's declared, but the assignment stays in exactly the same place.
The short of it is that you're not able to call a function declared as an expression until the expression has been parsed.
This code should illustrate a little more clearly.
foo();
//blah();
function foo(){
alert('hoisted and works');
}
var blah = function(){
// not hoisted, would fail if called
}
​
Live Demo

Categories

Resources