Difference between Function Declarations and Function Expressions

Difference between Function Declarations and Function Expressions

There are 3 notable ways to write functions in JavaScript. Which are function declarations, expressions, and arrow functions. With multiple options available, it is necessary to know the appropriate situations to use one or the other.

When To Use Function Declaration

A refresh. Function declarations are declared like this:

function refresh(){
        alert(' This is a function declaration memory refresh');
}

As a general rule of thumb, a function declaration is the default way of writing functions. It can be given preference over others if a function is needed to be called before its declaration.

showName(); // function call
function showName(){
    alert(`${name}`);  // function declaration
}

A function declaration has this special ability because the JavaScript engine sees it first during the initialization stage. Before a web page is run, the JavaScript engine makes two sweeps: one for initialization and the second for execution.

The Initialization Stage is to check for global variables and function declarations, so if a function call is encountered before its declaration, it moves down the page for the declaration.

Note that this is not the same for function assignment, as it is seen by the JavaScript engine during runtime (execution stage).

When To Use Function Expressions

A refresh.

let refresh = function(){
   alert('This is a function expression memory refresh');
 }

A condition-based scenario where a function expression can pull off seamlessly unlike a function declaration. i.e the function output depends on the user's input or values.

let user = prompt('Who are you?', '');
if(user === 'Admin'){
    function getPassword(){
      prompt('Enter Password');
  }
} 
else {
    alert('Welcome');
}

getPassword(); //Uncaught SyntaxError: getPassword has already been declared

The function calls above won't work because function declarations are only visible within the code blocks where they were created which in this case, the if and else blocks.

Moreover, this can be solved using function expressions by assigning the functions to a variable declared outside the blocks.

let user = prompt('Who are you?', '');
let getPassword;

if (user === 'Admin'){
     getPassword = function(){
      prompt('Enter Password');
  };
} 
else {
    alert('Welcome');
}

getPassword();