Functions
Functions in JavaScript are blocks of code that can be defined and executed to perform specific tasks. They allow you to encapsulate reusable code and execute it multiple times as needed. Here's an overview of functions in JavaScript:
- Built-in Functions: These functions are predefined in the libraries and users can directly call them in the program in order to serve the purpose. for example:
printf()
,sprintf()
,ucfirst()
,mail()
etc. - User-Defined Functions: These functions are defined by the user or the coder of the program according to the requirement of the program.
Creating a user_defined_function: A user-defined function can be created using the below syntax:
// syntax:
function function_name {
set of statements to execute ;
}
// A function name must start with a letter or an underscore (_).
Let's create a real-time user-defined function code example.
Above mentioned function is a function with no arguments
and no return
. The opening curly brace {
indicates the start of a function and the closing curly brace }
indicates the closing of a function. A function gets executed on a call. A call can be made any number of times after defining a function.
Function with arguments
and no return
Information can also be passed through arguments
which is further used in the function body in order to compute the desired results. arguments
are specified within the braces ()
after the function name. Multiple arguments
are separated by commas.
//syntax :
function function_name(argument1, argument2, arguments…..){
statements to execute ;
}
Function with return
and no arguments
To return a value from a function return
statement is used along with the parameters u want to return from the function.
// syntax:
function function_name(){
statements to execute;
return 0;
}
Function with return
and arguments
// syntax:
function function_name(argument1, argument2, arguments….){
statements to execute ;
return 0;
}
Return argument
with strict type
To declare a type of the return variable add a colon :
and the type right before the opening curly {
bracket while declaring a function.
Pass arguments
by reference
When arguments are passed by value, the copy of the variables is passed to the arguments. Therefore, the actual variable that was passed into the function isn't changed.
When a function argument is passed by a reference, changes to the argument also changes the actual variable that was passed in. ‘&’ operator is used to pass arguments by reference.