Function in JavaScript

All of us know that a function is a collection of statements executed when it is called at some point in a program. A function performs a specific task within a program independent of the other code in the program. We can call the function from anywhere within a program. We can also define the parameters to be passed to the function when the function is called. The parameters in a function are used to exchange information between a calling statement and the function. We can define a function by using the function keyword.

Syntax for a function

Function1.jpg

The above syntax has the name of the function and the parameters of the function.

JavaScript functions are divided into two categories:

Function2.jpg

Function without Parameters

Does not contain parameters. The code in these functions are static, implying that the values of the members of these functions cannot be changed at runtime.

Function with parameters

Contains parameters in the parenthesis, such as integer and string. Unlike functions without parameters, the values of members of these function can be changed at run time by passing different values of their parameters.

Now let's understand JavaScript functions using a simple example:

Function3.jpg

We have created a function named simple under the head section.

The simple() function shows an alert message with "Thank you".

The onload event handler under the BODY element calls the simple() function when the document is loaded in the browser.

Output :
Function4.jpg


Up Next
    Ebook Download
    View all
    Learn
    View all
    Foreantech - A complete online solution company.