JavaScript Functions
In this JavaScript tutorial, you will learn about JavaScript functions and how to create them.
What is a function?
Function is a block of code that can be reused as and when needed at various places. The function executes whenever it is called.
JavaScript Functions:
How does a programmer define, create and handle functions in JavaScript?
In JavaScript, the programmer must learn the following broad classifications to fully understand the concept of functions.
- Idea of JavaScript functions
- Creating a function in JavaScript
- Passing values to function
- Returning values from a function
Idea of JavaScript Functions:
As mentioned above, a function is a piece of code that is reusable by the programmer as and when needed. The function executes when it is called and this calling can be done either by an event or by a calling program. Functions in JavaScript are defined at the beginning of the page and are placed in the section. The functions placed in JavaScript can be called from anywhere.
Creating a Function in JavaScript:
General syntax for creating a function in JavaScript is as follows:
|
In the above syntax, argument1, argument2,…argument3 are optional. They are only placed if some values or data needs to be passed to the function. If the function does not have any values to be passed, then the syntax of function in JavaScript would be as follows:
|
In the above syntax, the first word function represents a keyword, followed by the name of the function and then the block of code which is to be placed within the braces { and }.
JavaScript is case-sensitive, care must be taken to write the keywords with lower case only as specified above.
For example, if a programmer wants to create a function exforsys with no data passed to function it is written in JavaScript as follows:
|