7670

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.

The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.

The two ways are:

var functionOne = function() {
    // Some code
};

And,

function functionTwo() {
    // Some code
}

What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?

1
  • Why is it a var and not a const? Commented Jun 14 at 17:21

42 Answers 42

1
2
7

new Function() can be used to pass the function's body in a string. And hence this can be used to create dynamic functions. Also passing the script without executing the script.

var func = new Function("x", "y", "return x*y;");
function secondFunction(){
   var result;
   result = func(10,20);
   console.log ( result );
}

secondFunction()
Sign up to request clarification or add additional context in comments.

1 Comment

This does not answer the question asked here.
6

This is called a Function Expression:

var getRectArea = function(width, height) {
    return width * height;
};

console.log("Area of Rectangle: " + getRectArea(3,4));
// This should return the following result in the console: 
// Area of Rectangle: 12

This is called a Function Declaration:

var w = 5;
var h = 6;

function RectArea(width, height) {  //declaring the function
  return area = width * height;
}                                   //note you do not need ; after }

RectArea(w,h);                      //calling or executing the function
console.log("Area of Rectangle: " + area);
// This should return the following result in the console: 
// Area of Rectangle: 30

Hope this helps explain what is the difference between Function Expression and Function Declaration and how to use them. Thanks.

Comments

3

I prefer defining function as variable:

let first = function(x){
   return x[0];
}

Instead of:

function first(){
    ....
}

Because i can use expressions and decorators when defining the function. For example:

let safe = function(f){
  try {f()...}
}
let last = safe(function(x){return x[0]}).

Also with ES6 its much shorter:

 let last = x => x[0]
 ...........
 function last(x){
     return x[0];
 }
......

let last = safe(x => x[0]);

Comments

3

Difference function declaration and function expression:

Javascript has first class functions. This means that they can be treated just like any other variable. Functions can be passed as arguments in a function, be returned from a function, and can be stored in variables.

However storing function in a variable (function expression) isn't the only way to create a function, this can also be done via a function declaration. Here are the key differences:

  1. Function expressions can be anonymous whereas a function declaration must have a name.
  2. Both have a name property which is used to identify the function. A function expression's name property is the name of the variable which it is bound to, whereas the name of a function declaration is simply the given name.
  3. Function declarations are hoisted whereas, function expressions are not. Only the variable is hoisted to have the value of undefined.

Here is an example:

try {
  functionOne();
} catch (e) {
  console.log('i cant run because im not hoisted');
}

functionTwo();

// function expression, does not get hoisted
let functionOne = function randomName() {
    // Some code
};

// function declaration, gets hoisted
function functionTwo() {
   console.log('I get hoisted');
}

try {
  randomName(); // this isn't the proper name, it is functionOne
} catch (e) {
  console.log('You cant call me with randomName my name is function one');
}

:

1 Comment

Declaration of let functionOne is hoisted. But it does not get initialized, not even with an undefined value. Hence, the error: Uncaught ReferenceError: Cannot access 'functionOne' before initialization
1

Expression in JS: Something that returns a value
Example: Try out following in chrome console:

a = 10
output : 10

(1 + 3)
output = 4

Declaration/Statement: Something that does not return a value
Example:

if (1 > 2) {
 // do something. 
}

here (1>2) is an expression but the 'if' statament is not. Its not returning anything.


Similarly, we have Function Declaration/Statement vs Function Expression
Lets take an example:

// test.js

var a = 10;

// function expression
var fun_expression = function() {
   console.log("Running function Expression");
}

// funciton expression

function fun_declaration() {
   console.log("Running function Statement");
}

Important: What happens when JavaScript engines runs the above js file.

  • When this js runs following things will happen:

    1. Memory will be created variable 'a' and 'fun_expression'. And memory will be created for function statement 'fun_declaration'
    2. 'a' will be assigned 'undefined'. 'fun_expression' will be assigned 'undefined'. 'fun_declaration' will be in the memory in its entirety.
      Note: Step 1 and 2 above are called 'Execution Context - Creation Phase'.

Now suppose we update the js to.

// test.js

console.log(a)  //output: udefined (No error)
console.log(fun_expression)  // output: undefined (No error)
console.log(fun_expression()) // output: Error. As we trying to invoke undefined. 
console.log(fun_declaration()) // output: running function statement  (As fun_declaration is already hoisted in the memory). 

var a = 10;

// function expression
var fun_expression = function() {
   console.log('Running function expression')
}

// function declaration

function fun_declaration() {
   console.log('running function declaration')
}

console.log(a)   // output: 10
console.log(fun_expression()) //output: Running function expression
console.log(fun_declaration()) //output: running function declaration

The output mentioned above in the comments, should be useful to understand the different between function expression and function statement/declaration.

Comments

1

One important point to note is :-

let there are two functions :-

sum(1,2);

const sum = function(first, second) {
  return first + second;
}

In above case, it will give error that sum is not defined, but

sum(1,2);

function sum(first, second) {
  return first + second;
}

This function will not any error as Hoisting will take place in this case.

Comments

1

You can't use the .bind() method on function declarations, but you can on function expressions.

Function declaration:

function x() {
  console.log(this)
}.bind('string')

x()

Function expression:

var x = function() {
  console.log(this)
}.bind('string')

x()

Comments

1

Debugger / DevTools

During a breakpoint in the debugger/DevTools, if you use the format function functionName() {} in the console, you can't use functionName() in the console subsequently (it says "not defined"), whereas after var functionName = function() {}, you can use the function.

See this question.

Hoisting

More generally, the chosen notation might affect hoisting behavior (i.e. from where the function can be called, depending on where it is defined).

Comments

0

Another difference between both function is functionOne can be used as a variable that can hold multiple functions within and functionTwo holds some block of code that gets executed all when called. Please check below :

   var functionOne = (function() {
      return {

         sayHello: function(){
                console.log('say hello')

         },
         redirectPage:function(_url){
                window.location.href = _url;
         }

      }
})();

You have a choice which function to be called. e.g functionOne.sayHello or functionOne. redirectPage. And if you call functionTwo then whole block of code will get executed.

Comments

0

The var functionOne = function() {} defines at run-time and the function functionTwo() {} defines at parse-time.

// Run-Time function declaration 
functionOne(); // Calling functionOne function here will give an Error
var functionOne = function () {
  // Some code
};

// Parse-Time function declaration 
functionTwo(); // Calling functionTwo function will not give an Error
function functionTwo() {
  // Some code...
}

The explanation between Run-time vs Parse-time javascript run-time vs parse-time

Comments

0

try {
  console.log("Success: ", add(1, 1));
} catch(e) {
  console.log("ERROR: " + e);
}

var add=function(a, b){
  return a + b;
}

1 Comment

This is not an answer. It's a code sample. It needs an explanation of what it is showing and also a counter example for the other type of declared function.
0

There are some differences between arrow function and normal function. In case of an arrow function, you are going to store a function inside a variable. I'm assuming that you have got your concepts clear for hoisting and execution context of JS. If not, please go through this tutorial . Now, let me explain the execution context a bit.

The total execution of your code happens in two phases-

  1. Memory allocation
  2. Code execution

In case of memory allocation, you just need to assign the memory spaces. Like if you do have var x = 4 in your code, after completing phase 1 your program will know, x = undefined. So, it allocates a memory space for x but no values in it. Just like a house with no people.

Now, when the code execution phase starts, it will assign the value 4 in x. Same will happen if you store an arrow function in x instead of 4. So that, you can get undefined if you try to call the arrow function on top of your program.

Now for the conventional function declaration, it will take place in phase one (Memory allocation) of the execution context. So, when the phase two starts, your program already knows what the function is and therefore you can console your function even before declaring it.

Hope it helps.

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.