Unlock the Power of Function Expressions for Enhanced JavaScript Functionality

aryan sharmaaryan sharma
8 min read

Welcome to my other blog about this JavaScript Blog Course. You can find it here↗️

In this blog, we are going to learn JavaScript Function Expressions.

What to wait?

Welcome my friend🤝

Function expressions

A function expression is a way to define a function in JavaScript by assigning it to a variable.
Function expressions are not hoisted and can only be called after they are defined.

Function expressions are often used to create anonymous functions (functions without a name) or to create functions on-the-fly.

Syntax:

let sayHi = function() {
  alert( "Hello" );
};

Here we can see a variable sayHi getting a value, the new function.

⚠️ Please note, there’s no name after the function keyword. Omitting a name is allowed for Function Expressions.

The function is a value

Let’s reiterate: no matter how the function is created, a function is a value. Both examples above store a function in the sayHi variable.

We can even print out that value using alert:

function sayHi() {
  alert( "Hello" );
}

alert( sayHi ); // shows the function code

Please note that the last line does not run the function, because there are no parentheses after sayHi. There are programming languages where any mention of a function name causes its execution, but JavaScript is not like that.

In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code.

Surely, a function is a special value, in the sense that we can call it like sayHi().

But it’s still a value. So we can work with it like with other kinds of values.

We can copy a function to another variable:

function sayHi() {   // (1) create
  alert( "Hello" );
}

let func = sayHi;    // (2) copy

func(); // Hello     // (3) run the copy (it works)!
sayHi(); // Hello    //     this still works too (why wouldn't it)

Here’s what happens above in detail:

  1. The Function Declaration (1) creates the function and puts it into the variable named sayHi.

  2. Line (2) copies it into the variable func. Please note again: there are no parentheses after sayHi. If there were, then func = sayHi() would write the result of the call sayHi() into func, not the function sayHi itself.

  3. Now the function can be called as both sayHi() and func().

We could also have used a Function Expression to declare sayHi, in the first line:

let sayHi = function() { // (1) create
  alert( "Hello" );
};

let func = sayHi;

Everything would work the same.

Why is there a semicolon at the end?

You might wonder, why do Function Expressions have a semicolon ; at the end, but Function Declarations do not:

function sayHi() {
  // ...
}

let sayHi = function() {
  // ...
};

The answer is simple: a Function Expression is created here as function(…) {…} inside the assignment statement: let sayHi = …;. The semicolon ; is recommended at the end of the statement, it’s not a part of the function syntax.

The semicolon would be there for a simpler assignment, such as let sayHi = 5;, and it’s also there for a function assignment.

Callback functions

Let's examine more instances of using function expressions and sending functions as values.

We'll create a function called ask with the following three parameters:

(question, yes, no)

question

Text of the question

yes

Function to run if the answer is “Yes”

no

Function to run if the answer is “No”

The function should pose the query and then either call yes() or no(), depending on the user's response:

function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

function showOk() {
  alert( "You agreed." );
}

function showCancel() {
  alert( "You canceled the execution." );
}

// usage: functions showOk, showCancel are passed as arguments to ask
ask("Do you agree?", showOk, showCancel);

In actuality, these features are beneficial. The main distinction between a real-life question and the example above is that real-life functions employ more intricate user interaction methods than straightforward confirmation. Such features typically provide a nice-looking query box in the browser. But that is a different tale.

Ask's showOk and showCancel parameters are referred to as callback functions, or simply callbacks.

The concept is that we pass a function and anticipate that, if necessary, it will be "called back" in the future. In our scenario, showOk serves as the callback for a "yes" response and showCancel serves as a "no" response.

We may create a similar, shorter function using function expressions:

function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

ask(
  "Do you agree?",
  function() { alert("You agreed."); },
  function() { alert("You canceled the execution."); }
);

Here, functions are declared right inside the ask(...) call. They have no name, and so are called anonymous. Such functions are not accessible outside of ask (because they are not assigned to variables), but that’s just what we want here.

Such code appears in our scripts very naturally, it’s in the spirit of JavaScript.

Function Expression vs Function Declaration

Let's list the main distinctions between expressions and function declarations.

Difference between them in the Code Syntax:

Function Declaration:

function sum(a, b) {
  return a + b;
}

Function Expression:

let sum = function(a, b) {
  return a + b;
};

A Function Expression is created when the execution reaches it and is usable only from that moment.

Once the execution flow passes to the right side of the assignment let sum = function… – here we go, the function is created and can be used (assigned, called, etc. ) from now on.

Function Declarations are different.

A Function Declaration can be called earlier than it is defined.

For example, a global Function Declaration is visible in the whole script, no matter where it is.

That’s due to internal algorithms. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an “initialization stage”.

And after all Function Declarations are processed, the code is executed. So it has access to these functions.

For example, this works:

sayHi("John"); // Hello, John

function sayHi(name) {
  alert( `Hello, ${name}` );
}

The Function Declaration sayHi is created when JavaScript is preparing to start the script and is visible everywhere in it.

…If it were a Function Expression, then it wouldn’t work:

sayHi("John"); // error!

let sayHi = function(name) {  // (*) no magic any more
  alert( `Hello, ${name}` );
};

Function Expressions are created when the execution reaches them. That would happen only in the line (*). Too late.

Another special feature of Function Declarations is their block scope.

In strict mode, when a Function Declaration is within a code block, it’s visible everywhere inside that block. But not outside of it.

For instance, let’s imagine that we need to declare a function welcome() depending on the age variable that we get during runtime. And then we plan to use it some time later.

If we use Function Declaration, it won’t work as intended:

let age = prompt("What is your age?", 18);

// conditionally declare a function
if (age < 18) {

  function welcome() {
    alert("Hello!");
  }

} else {

  function welcome() {
    alert("Greetings!");
  }

}

// ...use it later
welcome(); // Error: welcome is not defined

That’s because a Function Declaration is only visible inside the code block in which it resides.

Here’s another example:

let age = 16; // take 16 as an example

if (age < 18) {
  welcome();               // \   (runs)
                           //  |
  function welcome() {     //  |
    alert("Hello!");       //  |  Function Declaration is available
  }                        //  |  everywhere in the block where it's declared
                           //  |
  welcome();               // /   (runs)

} else {

  function welcome() {
    alert("Greetings!");
  }
}

// Here we're out of curly braces,
// so we can not see Function Declarations made inside of them.

welcome(); // Error: welcome is not defined

What can we do to make welcome visible outside of if?

The correct approach would be to use a Function Expression and assign welcome to the variable that is declared outside of if and has the proper visibility.

This code works as intended:

let age = prompt("What is your age?", 18);

let welcome;

if (age < 18) {

  welcome = function() {
    alert("Hello!");
  };

} else {

  welcome = function() {
    alert("Greetings!");
  };

}

welcome(); // ok now

Or we could simplify it even further using a question mark operator ?:

let age = prompt("What is your age?", 18);

let welcome = (age < 18) ?
  function() { alert("Hello!"); } :
  function() { alert("Greetings!"); };

welcome(); // ok now

When to choose Function Declaration versus Function Expression?

As a rule of thumb, when we need to declare a function, the first thing to consider is Function Declaration syntax. It gives more freedom in how to organize our code, because we can call such functions before they are declared.

That’s also better for readability, as it’s easier to look up function f(…) {…} in the code than let f = function(…) {…};. Function Declarations are more “eye-catching”.

…But if a Function Declaration does not suit us for some reason, or we need a conditional declaration (we’ve just seen an example), then Function Expression should be used.

I Hope you loved the blog❣️

See u in the next blog...Stay tuned🎶

Don't forget to follow me on:
Twitter And LinkedIn

4
Subscribe to my newsletter

Read articles from aryan sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

aryan sharma
aryan sharma

Hey, Awesome ones! Aryan this side👋 Full-Stack Developer, Life-Long Learner, Optimistic Using this blog to help code newbies. Learn with me! :)