Tutorials Tonight's Logo
Follow Us

JAVASCRIPT FUNCTION


What Is A Function In Javascript?

A function is one of the fundamental building blocks in javascript, it is a group of code statements which performs some specific task.

A function may return some output to the user or can do the computation to result in some output.

The basic idea of the function is to reduce the number of repeated code blocks and executing a code block whenever needed.

javascript function

Javascript Function Declaration

To use a function you must first declare it. In javascript, the function is declared by using the function keyword:

  • Start function with the function keyword
  • Then write the name of the function after space. The naming convention of function is the same as a variable naming convention.
  • then a list of parameters are given, enclose in parentheses and separated by commas like (parameter1, parameter2, ...)
  • Then javascript statements are enclosed in curly braces {...}
  • At the end of the function use return keyword to return any object or value.

javascript function syntax

function name_of_function (parameter1, parameter2,...) {
    // javascript statements
    return something;
}

Below is an example of a function which takes two numbers as an argument and returns the sum of the number. To call a function write name of the function with their arguments in parenthesis, if there is no argument then let the parenthesis be blank.

// Function declaration
function hello() {
  console.log("Hello World!");
}
▶ Try It

Javascript function call

Just defining a function does nothing until it is invoked or called.

How to call a function in javascript?

To call a function directly in javascript write the name of the function and give the required parameters in parenthesis. If there is no parameter then write blank parenthesis.

See the example below the 'sum' function defined in above example is called by giving 2 parameters:

// Function declaration
function hello() {
  console.log("Hello World!");
}
// Function calling
hello();
▶ Try It

Call Javascript Function From HTML

You can call a javascript function from HTML using some event. When an event occurs like button click, mouse move, document load, etc then you can use some event handler to trigger the event.

In the following example, there is a function that alerts a message, it is invoked as page loads and when the button is clicked.

<body onload="my_function()">
  <h2>Use some event to call a function from HTML.</h2>
  <button onclick="my_function()">Click</button>
  <script>
    function my_function() {
      alert("function executed!");
    }
  </script>
</body>
▶ Run The Code

Note: You can call a function from any event we want and as many times.


Javascript function parameter

Javascript function parameters are the values that are passed in the function to be used inside its statements. Parameters are extra added information that is given to the function while execution of the code.

The actual values that are passed in the function are known as arguments while the variable that is declared in the function is known as a parameter.

The data type of javascript function parameter could be any valid data type, example string, number, array, etc

In the example below function is taking 2 arguments 'user' and 'message' to be used in the function.

function message(user, message) {
    console.log("User: " + user + " || Message: " + message);
  }
message("Annie", "What's Up!");
message("Cluster", "Doing Good!");
▶ Try It

In Javascript functions, you can pass more or fewer arguments than the actual defined parameters. When a number of arguments are less than parameters then rest parameters will be undefined and when the number of arguments are more than parameters then extra arguments will be ignored.

Let's see an example to understand.

function fullName(firstname, lastname) {
  console.log(firstname + " " + lastname + "
"); } fullName("Stephen", "Hawking"); // output: Hello Stephen Hawking fullName("Stephen", "William", "Hawking"); // output: Hello Stephen William fullName("Stephen"); // output: Hello Stephen undefined
▶ Try It

Javascript Function Return

Javascript function can return an object or some value when invoked.

To return something from the function return keyword is used with the return value separated by space.

To use the return value of the function you can assign the function to some variable and when the function returns some value it gets stored in the variable.

Function stop execution when reached to return statement even if there are more statements in the function after a return.

function multiply(a, b) {
  var result = a * b;
  return result;
}
var value = multiply(4, 6); // storing return value in a variable
console.log(value);
▶ Try It

The return value can be placed anywhere in the function but as soon as function find return statement it stops further execution of the code in a function.

Also, you can use return statement without returning any value, you can do this to stop function to execute further in a certain condition.

function pass(mark) {
  if (!mark) {
    console.log("Invalid Marks!");
    return;
  }
  if (mark > 40) {
    console.log("Pass!");
    return true;
  }
  else {
    console.log("Fail!");
    return false;
  }
}
pass(60);
▶ Try It

Javascript Function Local Variable

The variables that are defined inside the function have local scope. Means these variables can't be accessed outside the function.

But a function can access the variable that is defined outside the function.

In the example below the variable, 'a' is defined inside the function, which has local scope and is undefined outside the function.

function localVariable() {
  let a = 10;
  console.log("Value of 'a' inside function is " + a);
}
console.log("value of variable 'a' outside function is " + typeof a);
localVariable(); // function call
▶ Try It

Javascript Function Expression

Function expression let us define the function and assign it to some variable explicitly. The variable, the function is assigned to is used to invoke the function.

A function expression, in general, has no name hence it is also called an anonymous function.

It is more convenient to pass as an argument in callback functions.

Here is an example of function expression 'sum', which takes 2 arguments and return the sum of the number.

var sum = function (num1, num2) {
  return num1 + num2;
}
console.log(sum(12, 32));
▶ Try It

Javascript Function Declaration VS Expression

These are 2 important difference between function declaration and function expression:

  1. A function declaration can be hoisted but function expression can't be hoisted. It means you can use a function before it is declared while you can't use before function expression is declared.
    hello(); // run successfully
    function hello() { // function declaration
      return "Hello World!";
    }
    hello(); // error function not declared
    let hello = function() { // function expression
      return "Hello World!";
    }
  2. Function declaration is loaded before execution of any code but function expression loads only when the interpreter reached that line of code.

Javascript Immediately Invoked Function Expression(IIFE)

Immidiately Invoked Function Expression (IIFE) is the function is executed right after the function is declared.

Syntax of IIFE

(function () {
  // statements;
})();

The variables defined inside IIFE is not accessible outside the function.

(function(){
  console.log("Function executed immediately after it is declared.")
})();
▶ Try It

If you assign IIFE to some variable then it stored function's return value not the function itself.

var example = (function(){
  return "Returned value is stored."
})();
console.log(example);
▶ Try It

Points to remember:

  1. Function in javascript is declared using the function keyword.
  2. A function can have any number of arguments starting from 0.
  3. You can call javascript function from HTML using some event.
  4. As soon as function reaches return statement it stops further execution of it.
  5. Variable defined in a function has local scope.

More Learning

Want to learn more about programming and web development? We have a few recommendations for you.


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.