The functions are building blocks of the JavaScript programming. A function in JavaScript is a block of statements that may or may not take inputs and return a value. Therefore, it appears that JavaScript functions are no different from functions in other programming languages.
There are many difference between functions in other languages and JavaScript functions. The function are object in JavaScript that are created from the constructor Function(). JavaScript supports anonymous functions which are available many other languages.
Function Components
Any JavaScript function has few key components in syntax. Here is the list.
- The keyword function
- A function name
- A list of parameters.
- A block of statements to execute.
The following figure shows how these components are organized to write a function in JavaScript.
JavaScript Function Declaration
In other programming languages such as C/C++, you must explicitly declare you function type, its actual and formal parameters, and then write a separate definition for the function.
In JavaScript, function definition is also the function declaration. The structure of function also depends on what type of function it is.
Types of Functions in JavaScript
The JavaScript programming allows following type of functions.
- function with parameters, but no return value
- function with parameter and a return value
- function without parameter and no return
- function without parameter and a return value
- built-in JavaScript methods
- class methods
- anonymous functions
- constructors
We will discuss about each one of them in great detail in future lesssons.
Function Calls
The function calls in JavaScript is easiest in programming. You simply write the function name and supply the arguments. Either the function will return some value, or directly output a value to the browser.
There are three ways to call a JavaScript function.
- call function in the main program
- call function within another function
- call function from an HTML element such button, etc.
Whichever way you choose, once the function is called it will execute the statements within it.
Function Scope
There are three scope for the JavaScript functions.
Local Scope
It means that the variables that are defined inside the function can only be accessed by the function, not outside of it.
Parent Scope or Nested Scope
If a function is defined inside of another function, the parent function cannot access the variables of the child function. However, the child function can access variables within its own body and from the parent function.
Global Scope
A function defined within the JavaScript main program can access its own local variables and all the other global variables. However, the other global functions cannot access the local variables.