JavaScript Functions
1. What are Functions?
Functions are fundamental building blocks in all programming. Functions are reusable block of code designed
to perform a particular task. Functions are executed when they are "called" or "invoked".
Example
JavaScript function to compute the product of two numbers
function product(a,b){
return a*b;
}
2. JavaScript function syntax.
In JavaScript functions are declared by function keyword, followed by the name of the function, followed
by open-close parenthesis () with optional parameters.
Example
function myFunction(p1,p2,…){
//code for execution
}
A function might return a value after it is called or invoked.
3. Importance of using functions.
(a) Function organizes better code reusability and optimization.
(b) One can use same code multiple times accordingly without writing the code each time.
(c) Different arguments could be passed in a same function which produce different result each time.
4. Function invocation.
A function is called or invoked when:
By a JavaScript code. Using () operator.
By occurrence of an event.
By the function itself. (self-invocation)
Example:
function kmToM(km){
return km*1000;
}
let m = kmToM(5);
5. Parameters vs Arguments
Parameters are the names which are declared in during the function declaration. These are the names of the
variables, in which the values are passed.
Example
function myFunction(a,b){
return a*b;
}
Here a, b are the parameters of the function myFunction.
Arguments are the values which the parameters receive. In short arguments are the values which are passed to
a function.
Example
function myFunction(a,b){
return a*b;
}
let x = myFunction(5,6);
Here 5, 6 are the values or arguments.
6. Functions as variable
Javascript functions can also be used as variables.
Example:
function myFunction(a,b){
return a*b;
}
[Link](“The result is: “+myFunction(5,6);
7. Parameters rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
8. Default parameters
If a function is called with missing arguments (less than declared), the missing values are set to undefined.
Example:
function myFunction(x,y){
[Link](“The value of x is: “ + x + “the value of y is: “ + y);
}
myFunction(5)
9. Default parameters values
Example:
function myFunction(x,y=10){
return x+y;
}
myFunction(5)