JavaScript Function

tutorial and example
tutorial and example

An important part of JavaScript is the ability to create new functions within <script>…..</script> tag. To declare a function in JavaScript using function keyword.

We call JavaScript function multiple times to reuse the code.

Advantages of JavaScript functions

  1. Code reusability: We call function multiple time to save time as well as coding also.
  2. Less coding: It make our program compressed. We don’t write many lines of code each time to perform common task.

Syntax

Example

Try Now

Output

Function with arguments

Call function by passing arguments.

Try Now

Output

Example

Try Now

Function with return value

Call function that return value and use it in program.

Try Now

Output

The Function() Constructor

function statement is not only the method to define new function, we can define function dynamically using Function() constructor along with new operator also.

Syntax

Example

Try Now

Function Literals

JavaScript 1.2 introduces the concept of function literals which is another method to define functions. It is an expression that defines an unnamed function.

The syntax for function literal is like function statement, except it is used as an expression rather than a statement and no function name is required.

Syntax

Example

Try Now