JavaScript Functions

In this lecture, you will learn about JavaScript functions and how they are used to configure code into smaller and more reusable units. In this lecture you will understand the function in a very simple language for learning.

  JavaScript is an object-based language. Everything in JavaScript is an object.

  The JavaScript function is used to perform the operation. We can call the JavaScript function multiple times to reuse the code.

Tip : To declare a function, use the function keyword and then the name.

JavaScript Function Syntax

  Functions can be defined using the function keyword and executed using the () operator.

  The code to execute by function is placed in a spiral bracket: {}

  Function Arguments are the values obtained by the function when it is called.

  The code to execute by function is placed in a spiral bracket: {}

<script>  
function demo(){  
window.alert("this is function");  
}  
</script>             

JavaScript Function Return Value

The JavaScript function may have an optional return statement. This is necessary if you want to return the value from the function.

  To specify the return value for a function, you use the return statement and then the expression or value

  Tasks often calculate the return value. The return value is given back to the caller.

  • In the following example you can see how the return value can be given.
<script>  
var demo = mymsg(4, 3);
document.write(demo);

function mymsg(a, b) {
  return a * b;
}
</script>             

JavaScript Function Methods

  Functions can be defined using the function keyword and executed using the () operator.

  Accessing a function without () will return the function object instead of the function result.


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

  • In this lecture you have learned about JavaScript function, hopefully you have understood the function from this lecture.