JavaScript Functions - Java Script

What are JavaScript Functions?

Quite often, we may come across some situations where we want to execute a block of code at different places. Then we will make use of functions.

Functions are small packages of JavaScript code that can be called anywhere in your program. All you need to do is you have to put your code in a block and name it. Functions enables a programmer to partition a big program into a number of small and manageable functions.

Similar to other programing languages, JavaScript also provides all the features that are required to write modular code using functions. The alert() and write() which we have seen in earlier chapter is nothing but a function. But these functions are written in core JavaScript.

In addition to this JavaScript permits us to write our own own functions as well. This section illustrates how to write our own functions in JavaScript.

What is Function Definition?

Before we are going to use a function, we have to define it. We can define a function in JavaScript by using the keyword Function followed by a distinct function name, parameters list (that might be empty), and a code block enclosed by curly braces.

Syntax:

The basic syntax of function is shown below.


Example

Try the below example. It defines a function namedsayHello that accepts no parameters −

How to Call a JavaScript Function?

To call a function somewhere later in the program, one have to write the name of the function as shown in the below example:

What are JavaScript Function Parameters?

So far, we have discussed about functions without parameters. But we can also pass different arguments at the time of calling a function. These passed arguments can be captured inside the function and any operations are performed those arguments. We can also pass multiple arguments to a function separated by comma.

Example:

Try the below example. Here we have improvised our say Hello function and it takes two arguments.

What is JavaScript Return Statement?

A JavaScript function can have adefault return statement. The return statement isneeded if you want to return a value from a function. This statement should be the last statement in a function.

For instance, you can pass two arguments in a function and then you can assume the function to return their multiplication in your calling program.

Example:

Here is an example which defines a function that takes two arguments and concatenates them before returning the resultant in the calling program.

Output:

There is a lot more to learn about JavaScript functions, anyhow we have covered the most important concepts in this tutorial.

  • JavaScript Nested Functions
  • JavaScript Function( ) Constructor
  • JavaScript Function Literals


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics