HtmlCssMonk

Functions in JavaScript | Learn basic JS

coding, programming, css

Functions

A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.


Function Invocation

The code inside the function will execute when “something” invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.

JavaScript allows us to write our own functions as well. Let’s see how !!

The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax –

<script type="text/javascript">

    function functionName([arg1, arg2, ...argN]){  
 //code to be executed  
}  
</script>

Simple Function

Let’s see the simple example of function in JavaScript that does not has arguments.

Example –

<html>
  <body>
    <script>  
      function msg(){  
      alert("hello! this is message");  
      }  
    </script>  
    <input type="button" onclick="msg()" value="call function"/>  
  </body>
</html>

This Code will produce the following result on your webpage –


Function with Arguments

We can call function by passing arguments. Let’s see the example of function that has one argument.

Example –

<html>

<body>
  <script>
    function getcube(number) {
      alert(number * number * number);
    }  
  </script>
  <form>
    <input type="button" value="click" onclick="getcube(4)" />
  </form>
</body>

</html>

This Code will produce the following result on your webpage –


Function with Return value

We can call function that returns a value and use it in our program. Let’s see the example of function that returns value.

Example –

<html>

<body>
  <script>
    function getInfo() {
      return "Hey Monk , Keep Learning !!";
    }  
  </script>
  <script>
    document.write(getInfo());  
  </script>
</body>

</html>

This Code will produce the following result on your webpage –


Advantages of JavaScript Functions

  1. Code reusability: We can call a function several times so it save coding.
  2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.

Previous topic – Loops in JS


Leave a Comment

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