JavaScript Functions

Functions in JavaScript :

The JavaScript engine can execute JavaScript code in two different modes:

JS Modes of execution

The JavaScript code that we have seen until now is running in immediate mode. As soon as we load the page in the browser, the script gets executed line by line without any delay.

But in real-world application development, it is not possible to wait for sequential execution of the code written for huge applications. JavaScript provides a solution to this problem in the form of JavaScript functions.

Let us now learn JavaScript functions.


Note : Deferred mode of execution will be discussed further in the course.

Type of Functions :

JavaScript functions are block of statements designed to perform a particular task. This block becomes a reusable unit of code.

JavaScript has 2 types of functions:

JS Type of function

User-defined functions :

JavaScript allows us to write our own functions called as user defined functions. First, we declare the function and then we can invoke it from anywhere in the program.

Syntax for function declaration.

JS Function declaration definition syntax

The code written inside the function body will be executed only when it is invoked. Syntax for function invocation.

JS Function declaration invocation syntax

Example: Let us write the JavaScript code for Hello World, inside the function and invoke the function to see the expected output.

inside the function and invoke the function

We can modify the same code to learn to pass parameters to the function and to return the value from within the function.

Parameters Passing :

Let us now see how can we handle parameters and return value in the function declaration.

Example: Declare a function that takes the parameter as name and returns the message “Hello” followed by the name passed as parameter.

JS Function example

When we invoke this function, we should declare a variable that will store the value which the function will return.

JS invocation Function example 01

When the function is invoked, the value returned will be stored in the variable 'msg'.

JS invocation Function example 01 output
#javascript_function #Functions_in_JavaScript #Type_of_Functions_in_javascript #User-defined_functions_in_javascipt #in_built_function_in_javascript #function_Parameters_Passing_in_javascript

(New page will open, for Comment)

Not yet commented...