What is the difference between the function declarations below?

var foo = function(){ 
    // Some code
}; 
function bar(){ 
    // Some code
}; 

The main difference is the function foo is defined at run-time whereas function bar is defined at parse time. To understand this in better way, let’s take a look at the code below:

Run-Time function declaration 
<script>
foo(); // Calling foo function here will give an Error
  var foo = function(){ 
    console.log("Hi I am inside Foo");
 }; 
 </script>
<script>
Parse-Time function declaration 
bar(); // Calling foo function will not give an Error
 function bar(){ 
  console.log("Hi I am inside Foo");
 }; 
</script>

Another advantage of this first-one way of declaration is that you can declare functions based on certain conditions. For example:

<script>
if(testCondition) {// If testCondition is true then 
   var foo = function(){ 
    console.log("inside Foo with testCondition True value");
   }; 
 }else{
 	 var foo = function(){ 
    console.log("inside Foo with testCondition false value");
   }; 
}
</script>

However, if you try to run similar code using the format below, you’d get an error:

<script>
if(testCondition) {// If testCondition is true then 
   function foo(){ 
    console.log("inside Foo with testCondition True value");
   }; 
 }else{
 	 function foo(){ 
    console.log("inside Foo with testCondition false value");
   }; 
}
</script>
Asked on January 18, 2019 in Javascript.
Add Comment


  • 7 Answer(s)

    Function Declaration

    function foo() { ... }

    Because of function hoisting, the function declared this way can be called both after and before the definition.

    Regarding  definition:

    var foo = function foo() { return 5; }

    Heres an example which shows how to use possibility of recursive call:

    a = function b(i) { 
    if (i>10) {
    return i;
    }
    else {
    return b(++i);
    }
    }

    console
    .log(a(5)); // outputs 11
    console
    .log(a(10)); // outputs 11
    console
    .log(a(11)); // outputs 11
    console
    .log(a(15)); // outputs 15

    Edit: more interesting example with closures:

    a = function(c) {
    return function b(i){
    if (i>c) {
    return i;
    }
    return b(++i);
    }
    }
    d
    = a(5);
    console
    .log(d(3)); // outputs 6
    console
    .log(d(8)); // outputs 8
    Answered on January 19, 2019.
    Add Comment

    They’re actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.

    Function declarations load before any code is executed.

    Function expressions load only when the interpreter reaches that line of code.

    So if you try to call a function expression before it’s loaded, you’ll get an error! If you call a function declaration instead, it’ll always work, because no code can be called until all declarations are loaded.

    Example: Function Expression

    alert(foo()); // ERROR! foo wasn't loaded yet
    var foo = function() { return 5; } 

    Example: Function Declaration

    alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
    function foo() { return 5; } 

    As for the second part of your question:

    var foo = function foo() { return 5; } is really the same as the other two. It’s just that this line of code used to cause an error in safari, though it no longer does.

    Answered on January 20, 2019.
    Add Comment

    Function Declaration

    function [name](param1, param2, ...param3) {
        // Function Body & Logic
    }

    In this case, we prefix [function keyword] before respective [function name].
    One major advantage of this approach is that the complete function is Hoisted.

    Because of that, we can execute the function before declaring it.

    It is helpful when you want to abstract some logic into a function body and the actual implementation will be done at some later point of time.

    var num1 = 10;
    var num2 = 20;
    var result = add(num1, num2); // ==> 30 [Executing before declaring]
    function add(param1, param2) {
        return param1 + param2 ;
    }

    Best practiceAlways declare the function first and then execute it instead of relying on JavaScript Hoisting.


    Function Expression

    Any statement which assigns some value to some other variable is considered as an Expression.

    var a = 100;
    var b = 'Hello World';

    In case of Function Expression, a function is created without any name and then assigned to a variable.

    var [name] = function(param1, param2, ...param3) {
        // Function Body & Logic
    }
    foo(1,3,4);
    Answered on January 20, 2019.
    Add Comment

    A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. It’s helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”.
    function bar() {
    return 3;
    }
    ECMA 5 (13.0) defines the syntax as
    function Identifier ( FormalParameterListopt ) { FunctionBody }

    The function name is visible within it’s scope and the scope of it’s parent (which is good because otherwise it would be unreachable)

    1
    2
    3
    4
    5
    6
    function bar() {
    return 3;
    }

    bar() //3
    bar //function

    Answered on January 26, 2019.
    Add Comment

    Function declaration
    A function declaration is made of function keyword, followed by an obligatory function name, a list of parameters in a pair of parenthesis (para1, …, paramN) and a pair of curly braces {…} that delimits the body code.

    A function declaration looks this way:

    Try in JS Bin
    // function declaration
    function isEven(num) {
    return num % 2 === 0;
    }
    isEven(24); // => true
    isEven(11); // => false
    function isEven(num) {…} is a function declaration that defines isEven function, which determines if a number is even.

    The function declaration creates a variable in the current scope with the identifier equal to function name. This variable holds the function object.

    The function variable is hoisted up to the top of the current scope, which means that the function can be invoked before the declaration (see this chapter for more details).

    The created function is named, which means that name property of the function object holds its name. It is useful when viewing the call stack: in debugging or error messages reading.

    Let’s see these properties in an example:

    Try in JS Bin
    // Hoisted variable
    console.log(hello(‘Aliens’)); // => ‘Hello Aliens!’
    // Named function
    console.log(hello.name) // => ‘hello’
    // Variable holds the function object
    console.log(typeof hello); // => ‘function’
    function hello(name) {
    return `Hello ${name}!`;
    }
    The function declaration function hello(name) {…} create a variable hello that is hoisted to the top of the current scope. hello variable holds the function object and hello.name contains the function name: ‘hello’.

    Answered on January 26, 2019.
    Add Comment

    What is a Function Declaration?

    A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. It’s helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”.

    e.g.

    function bar() {
    return 3;
    }

    Answered on January 27, 2019.
    Add Comment

    Function Declaration

    function foo() { ... }

    Because of function hoisting, the function declared this way can be called both after and before the definition.

    Function Expression

    1. Named Function Expression
      var foo = function bar() { ... }
    2. Anonymous Function Expression
      var foo = function() { ... }

    foo() can be called only after creation.

    Immediately-Invoked Function Expression (IIFE)

    (function() { ... }());
    Answered on February 5, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.