All You Need to Learn About Javascript Functions

A function is a programming construct which consists of a set of defined code. This code performs some action and can be reused multiple times which makes the code efficient and modular. In this lesson on JavaScript Functions, the following topics will be covered, starting from the basic understanding of what are JavaScript functions to more technical aspects of the generator and predefined functions. Here’s a glimpse of all of it: 

  • What are JavaScript functions?
  • Function expressions
  • Function() constructor
  • Self-invoking functions
  • Functions as values
  • Functions as objects
  • Arrow functions
  • Generator function
  • Predefined functions

What Are JavaScript Functions?

A JavaScript function is a piece of reusable code that can be called from anywhere in the program. This prevents writing the same code again and again. It helps programmers write modular code.

General Syntax:

 /general.

General Syntax - JavaScript Functions

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

Function Expressions 

A JavaScript function can also be defined using an expression. The function expression can be stored in a variable which can be later used in the place of the function call.

<script>

        var y = function(a,b){ return a*b }

        x = y(3,5)

        document.write(x)

    </script>

The code will display the product of the values 3 and 5. 

The Function Constructor

JavaScript functions are declared using the keyword function, however, functions can also be defined using the built-in JavaScript function constructor called Function() and the new keyword. 

Consider the following code: 

<script>

        var My_function = new Function("a","b","return a+b")

        var x = My_function(2,3)

        document.getElementById("demo").innerHTML = "The sum is " + x

    </script>

The function My_function is created and its definition is written within the constructor. The value returned by this function is stored in the variable x. The output of the above code is: 

constructor

    Function Constructor - JavaScript functions

Self-Invoking Functions

A self-invoking function is invoked automatically, without being called. Function expressions will execute automatically if the expression is followed by “()”. It is crucial to add the parentheses around the function to indicate that it is a function expression. The following code shows the syntactical notation of a self-invoking function.  

<script>

        (function (){

            document.write("This is a self-invoking function")

        })();

    </script>

And the output of the code is: 

self

  Self-invoking functions

Functions as Values

In JavaScript, functions are treated as values. You first define the function and then assign it to a variable. Consider the following code: 

<script>

        function Product(a,b){

            return a*b

        }

        let y = Product(2,5)*5

        document.getElementById("demo").innerHTML = "The product is " + y

    </script>  

In this case, the function was defined and then assigned to a variable while calling it. You might think that this is the same as a function expression. Well, in an expression, the function definition is assigned to a variable. It is also mandatory to use parentheses while calling the function using the variable. 

The output of the function will be: 

func-val.
Functions as values

Functions as Objects

Now that you know that functions can be assigned to variables, let’s move on to functions as objects. Functions can also be passed to other functions and returned from a function. They can also be defined as objects. A function object includes a string that holds the actual code i.e., the function body of the function. 

For instance, consider this code snippet: 

<script>

        var body = "return 2* Math.PI * rad "

        var circumference = new Function("rad",body);

        alert(circumference(5))

</script> 

Here, the string body is assigned to the definition of the function. The output will be: 

finc-obj
Functions as objects 

Arrow Functions

Functions can be written more compactly with the help of Arrow functions. Arrow functions cannot be used as constructors. 

The general syntax is: 

arrow-fun

Arrow functions - JavaScript Functions

Consider the following code: 

<script>

        const Myfunc = (a,b,c) => {return a*b*c}

        let product = Myfunc(2,3,4)

        document.write("The product of the three digits is " + product)

</script>

Here, the function Myfunc is an arrow function with parameters, a,b, and c returning the product of these values. The output is: 

javascript-arrow

       JavaScript Arrow functions 

Generator Functions

Did you observe that all the functions mentioned above return only a single value? There special functions that return multiple values, on-demand. They are called generator functions. To create a generator, we use the syntax: function*

generator.

  Generator functions

Generator functions behave differently from regular ones. When such a function is called, it returns a special object called the "generator object" instead of running the code. This object manages the execution. 

The main method of the generator is next(). When this method is called, it runs the code until the nearest yield statement. Then the execution halts and the yielded value is returned to the outer code. 

The result of next() is always an object with two properties:

value: the yielded value.

done: true if the function code has finished, otherwise false.

Consider the following code: 

<script>

        function* generateFunc(){

            yield 1;

            yield 2;

            return 3;

        }

        let generator = generateFunc();

        let one = generator.next();

        let two = generator.next();

        let three = generator.next();

        alert(JSON.stringify(one));

        alert(JSON.stringify(two));

        alert(JSON.stringify(three));

    </script> 

Here, the generator function returns values 1, 2, and 3. The generator object is used to call the next() method. The values returned by these calls are stored in the variables one, two, and three. We then alert the user with the value. The JSON. stringify() method converts a JavaScript object or value to a JSON string. 

Here’s the output: 

Generator Functions

If you observe the output, while displaying the value 3, the done property associated with it is set to true indicating that no more values are being returned. 

Predefined Functions

JavaScript has a set of predefined functions that perform a certain action when called. Here are a few of them:

eval()

Evaluates a string and returns a value

parseInt()

Parses a string argument and returns an integer value

parseFloat()

Parses a string argument and returns a floating-point number

escape()

Returns the hexadecimal encoding of an argument 

unescape()

Returns the ASCII string for the specified value

Consider the following code:

<script>

        var x = 50;

        var y = 30;

        var a = eval("x * y")  

        document.write("The result of eval is: " + a +"<br>")

        var b = parseInt("15.00")  

        document.write("The result of parseInt is: " + b + "<br>")

        var c = parseFloat("40")  

        document.write("The result of parseFloat is: " + c + "<br>")

        let msg1 = escape("JavaScript Predefined Functions") 

        document.write("The result of escape is: " + msg1 + "<br>")

        let msg2 = unescape("JavaScript Predefined Functions") 

        document.write("The result of unescape is: " + msg2)

    </script>

The example shows how all the pre-defined functions work. Here's the output: 

predefined

      JavaScript Predefined functions

Master the JavaScript fundamentals including, jQuery, Ajax, and more with the Javascript Certification Training Course. Check out the course preview!

Next Steps

To learn more about JavaScript in its entirety, then certification is highly recommended and could act as a catalyst to your coding career. Simplilearn's JavaScript Certification Training course helps individuals master the JavaScript programming language in an all-inclusive training program that includes complete JavaScript fundamentals, jQuery, Ajax, and more. You will also have the opportunity to apply your skills by building a real-time chat application.

If you have any questions or feedback, let us know in the comments section. Our experts will get back to you immediately.

About the Author

Chinmayee DeshpandeChinmayee Deshpande

Chinmayee is a Research Analyst and a passionate writer. Being a technology enthusiast, her thorough knowledge about the subject helps her develop structured content and deliver accordingly.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.