JavaScript Functions
Functions in JavaScript :
The JavaScript engine can execute JavaScript code in two different modes:
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:
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.
The code written inside the function body will be executed only when it is invoked. Syntax for function invocation.
Example: Let us write the JavaScript code for Hello World, inside the function and invoke the function to see the expected output.
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.
When we invoke this function, we should declare a variable that will store the value which the function will return.
When the function is invoked, the value returned will be stored in the variable 'msg'.