Functions in JavaScript

Other languages like C, C++, JAVA, C# and Python, JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.

JavaScript Function Syntax

JavaScript function is explained as :
To define a JavaScript function function is used is identified by it's name and also it is followed by parentheses().

You can use a function name with letters, digits, underscore and dollars sign etc.

There can be parameters in between the parentheses with there seperated name and also seperated by commas:
(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3)
{
  // code to be executed
}
        

JavaScript Function Example

<script type = "text/javascript">
function msg() { alert("hello! this is message"); } </script> <input type="button" onclick="msg()" value="Click here"/>

Output of above code


JavaScript Function Arguments

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

<script type = "text/javascript">
function getsquare(number) { alert(number*number); } </script> <input type="button" onclick="getsquare(5)" value="Click here"/>

Output of above code


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.

<script type = "text/javascript">
function getInfo() { return "hello javatpoint! How r u?"; } </script> <script type = "text/javascript"> document.write(getInfo()); </script>

Output of above code

hello javatpoint! How r u?


JavaScript Function Methods

Let's see function methods with description.

Method Description
apply() It is used to call a function contains this value and a single array of arguments.
bind() It is used to create a new function.
call() It is used to call a function contains this value and an argument list.
UndefinedtoString() It returns the result in a form of a string.

Advantages of JavaScript Functions

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








The Best

Comment here

If you have any query, if you want to know something about any of technical course related to computer science field, if you have any suggestion about relevant to uploaded content or if you anything wrong here (any mistake in content) than please contact us. Keep in mind, comment should be according to community guidelines.