It is quite straightforward to look at the JavaScript code snippet bellow and conclude it will output in to the console the result of 2. But for those coming from a C background, it may come as a surprise that Forward Declaration of the avg function is not required.

console.log(avg(1,2,3));

function avg(a,b,c) {

    var result = (a+b+c)/3;
    return  result;

}

In fact, JavaScript performs what is know as Function and Variable Hoisting, moving all function and variable declarations to the top before interpreting. As such, we can think of the above code snippet interpreted as:

// declaration of avg hoisted;
function avg(a,b,c) {

    var result; // Declaration of result variable hoisted

    result = (a+b+c)/3;
    return  result;

}

console.log(avg(1,2,3));  

In JavaScript, functions are First Class Citizens and can be referenced by a variable just like any other data type. With this knowledge, we could attempt to replace our function declaration with an equivalent function expression:

console.log(avg(1,2,3));

var avg = function(a,b,c) {

    var result = (a+b+c)/3;
    return  result;

}

But our code will not work anymore due to hoisting of the avg variable. We can think of the above code snippet interpreted as:

var avg; // hoisted avg variable, contains undefined

console.log(avg(1,2,3));

avg = function(a,b,c) {

    var result = (a+b+c)/3;
    return result;

}

Variable hosting can get us into other types of troubles. Looking at the code bellow, we might be trapped to assume that b contains 2 when the value of result is calculated:

var b = 2;  
console.log(avg(1,3));

function avg(a,c) {

    var result = (a+b+c)/3;
    var b = 2;
    return result;

}

Unfortunately, that is not the case. Variable hoisting will make our code be interpreted as something like:

var b = 2;  
console.log(avg(1,3));

function avg(a,c) {

    var result;
    var b;  // Contains undefined and hides the global variable b

    result = (a+b+c)/3; // will result in NaN
    return result;

}

Because of this behaviour, it is often recommended to put all variable declarations at the top of the function, so the code more clearly represents what is actually happening and to avoid being caught by surprise.