Function Expressions in JavaScript

Function Expressions in JavaScript

In this article, I am going to discuss Function Expressions in JavaScript with Examples. Please read our previous article where we discussed JavaScript Functions in Detail. At the end of this article, you will understand What is Function Expressions in JavaScript and the different ways to create JavaScript functions with examples.

What are Functions in JavaScript?

A function is a small named snippet of code

  1. Can be invoked using their identifier (name)
  2. Functions can take parameters of any type
  3. Function can return a result of any type. undefined is returned if no return statement is reached

Each function is given two special objects:

  1. this contains information about the context. Different depending of the way the function is invoked
  2. arguments contains all passed arguments
Functions as Objects

In JavaScript functions are first-class objects

  1. One of the most powerful features in JavaScript
  2. We can set properties on them
  3. We can invoke methods on them
  4. They have properties of their own such as length, caller, name, apply, call

Functions are objects and they can be used as objects

  1. Can be passed as arguments to other functions
  2. Can be stored in an array
  3. Can be assigned to variables
  4. Can be returned by another function
Example:
<html>
<head>
</head>
<body>
    <script type="text/javascript">
        function maxe(arr) {
            var maxValue = arr[0];
            for (var i = 1; i < arr.length; i++) {
                maxValue = Math.max(maxValue, arr[i]);
            }
            return maxValue;
           	          alert(maxValue);
            console.log(maxe.name);//Print maxe
            console.log(maxe.length);//Print 1
        }
    </script>
    <form>
        <input type="button" value="click" onclick="maxe('hello')" />
    </form>
</body>
</html>

Output:
maxe
1

Creating Functions in JavaScript

Functions can be defined in several ways:

Function declaration
function printMsg(msg) { console.log(msg); }

Function expression
var printMsg = function (msg) { console.log(msg); }

Function constructor
var printMsg = new Function(‘msg’, ‘console.log(“msg”);’);

JavaScript Function Declaration

Function declarations use the function operator to create a function object. Function declarations are loaded first in their scope. No matter where they appear. This allows using a function before it is defined

Example:

<html>
<head>
</head>
<body>
    <script type="text/javascript">
        function printMsg(msg) {
            console.log("Message: " + msg);
        }
    </script>
    <form>
        <input type="button" value="click" onclick="printMsg('Hello')" />
    </form>
</body>
</html>
Function Expressions in JavaScript

Function expressions are created using the function literal

  1. They are loaded where they are defined
  2. Cannot be used beforehand
  3. Can be invoked immediately

The name is optional (can be anonymous). Function expressions do no need an identifier (it is optional). It is better to define it for making debugging easy. Otherwise the debuggers show anonymous. It can be stored in a variable.

Example:

<html>
<head>
</head>
<body>
    <script type="text/javascript">
        var printMsg = function (msg) {
            console.log("Message: " + msg);//Message:Hello
        }
        var printMsg = function printMsg(msg) {
            console.log("Message: " + msg);//Message:Hello
        }
    </script>
    <form>
        <input type="button" value="click" onclick="printMsg('Hello')" />
    </form>
</body>
</html>
Function Constructor in JavaScript

Function constructor is similar to expressions. A constructor initializes a function object and is loaded when the parser reaches it. The function constructor form is:
new Function([optional argument1, argument 2, …], body);

Bad practice: function constructor gives low performance and messy code

Example:

<html>
<head>
</head>
<body>
    <script type="text/javascript">
        var printMsg = function (msg) {
            var printMsg = new Function("msg", "console.log(msg);");
            printMsg("Hello!");
        }
    </script>
    <form>
        <input type="button" value="click" onclick="printMsg('Hello')" />
    </form>
</body>
</html>
Function Expression vs. Function Declaration

Function declarations are loaded first. They can be used before they are declared and can be overridden. Function expressions are loaded when reached and can be used only after creation.

Imagine two function declarations in the same scope have the same name, Which will be the one to execute? Will see in the next example

Example:

<html>
<head>
</head>
<body>
    <script type="text/javascript">
        if (true) {
            var printMsg = function printMsg(msg) {
                console.log("Message (from if): " + msg);
            }
        }
        else {
            var printMsg = function printMsg(msg) {
                console.log("Message (from else): " + msg);
            }
        }
        printMsg("message");
    </script>
    <form>
        <input type="button" value="click" onclick="printMsg('Hello')" />
    </form>
</body>
</html>

Output:

Message (from if): Hello

JavaScript Function Properties

Each function is an object which is created either with declaration, expression or constructor. Functions have properties:

  1. function.length (The count of parameters the function expects and the arguments object is not counted)
  2. function.name (Identifier of the function and returns an empty string if anonymous is there)
JavaScript Function Methods

Functions have methods as well

  1. function.toString(): Returns the string that represents the source code of the function
  2. function.call(obj, arg1, arg2, …): Calls the function over the obj with arg1, arg2, …
  3. function.apply(obj, arrayOfArgs): Applies the function over obj using the arrayOfArgs as arguments

Note: Basically call and apply do the same. One gets args, the other gets array of args

Function Methods – Apply and Call
  1. function.apply(obj, arrayOfArgs): Invokes the function with obj used as this and arguments passed as array of values
  2. function.call(obj, arg1, arg2, …): Invokes the function with obj used as this and Arguments separated by commas

Difference: the way of receiving the arguments

Examples: function.apply(obj, arrayOfArgs)
<html>
<head>
</head>
<body>
    <script type="text/javascript">
        function printMsg(msg) {
            var numbers = [1, 54, 2, 324, 2];
            var max = Math.max.apply(null, numbers);
            console.log(max);
        }        
    </script>
    <form>
        <input type="button" value="click" onclick="printMsg('Hello')" />
    </form>
</body>
</html>

Output: 324

Examples: function.call(obj, arg1, arg2, …)
<html>
<head>
</head>
<body>
    <script type="text/javascript">
        function printMsg(msg) {
            console.log("Message: " + msg);
        }
        printMsg.apply(null, ["Important message"]);// Here "this" is null, since it is not used in the function
    </script>
    <form>
        <input type="button" value="click" onclick="printMsg('Hello')" />
    </form>
</body>
</html>

Output: Message: Important message

In the next article, I am going to discuss JavaScript Recursive Function in detail. Here, in this article, I try to explain Function Expressions in JavaScript with examples. I hope this Function Expressions in JavaScript article will helps you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

2 thoughts on “Function Expressions in JavaScript”

  1. I’m not getting result for this.. not sure whats the issue.

    function maxe(arr) {
    var maxValue = arr[0];
    for (var i = 1; i < arr.length; i++) {
    maxValue = Math.max(maxValue, arr[i]);
    }
    return maxValue;
    alert(maxValue);
    console.log(maxe.name);//Print maxe
    console.log(maxe.length);//Print 1
    }

    1. function maxe(arr) {
      var maxValue = arr[0];
      for (var i = 1; i < arr.length; i++) {
      maxValue = Math.max(maxValue, arr[i]);
      }
      alert(maxValue);
      console.log(maxe.name);//Print maxe
      console.log(maxe.length);//Print 1
      }

Leave a Reply

Your email address will not be published. Required fields are marked *