JavaScript Function

function in javascript

A JavaScript Function is a block of code designed to perform a particular task.

The main advantages of using JavaScript Function :

  • Code reuse: Define the code once, and use it many times.
  • Use the same code many times with different arguments, to produce different results.

JavaScript Function Example

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

<script>

function msg(){

alert("hello! this is message");

}

</script>

<input type="button" onclick="msg()" value="call function"/>

Function Parameter

Functions can take parameters. Function parameters are the names listed in the function’s definition.

 function sayHello(name) {

   alert("Hi, " + name);

}



sayHello("David");

//Alerts "Hi, David"

Multiple Parameter

You can define multiple parameters for a function by comma-separating them.

When calling the function, provide the arguments in the same order in which you defined them.

 function sayHello(name, age) {

  document.write( name + " is " + age + " years old.");

}



sayHello("John", 20)

//Outputs "John is 20 years old."

Return Function

A function can have an optional return statement. It is used to return a value from the function.

This statement is useful when making calculations that require a result.

  function addNumbers(a, b) {

   var c = a+b;

   return c;

}

document.write( addNumbers(40, 2) );

//Outputs 42

Spread the love

Leave a Comment

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