functions in Javascript helps to develope reuseable code
Meaning - Instead of writing the same code again and again we can use function to reuse the code as number of times required
Syntax:
function calcAdd(num1,num2){
let total = num1+num2;
return total;
}
- function is the keyword referring that we are writing a function
- calcAdd is the name given to the function
- num1 and num2 are the parameters passed inside the function to execute addition operation
- return is the keyword used to return the output once the function is called
Execution:
let output = caclAdd(20,35);
console.log(output)
- Once the function is called 20 and 35 are the arguments that takes the places of parameters num1 and num2
- perform addition operation and store the value 55 in the variable total
- As we have returned the value it will now be stored in the output variable
Points to remember:
- funtion can be declared with any number of parameters.
- unlike Java, Javascript executes even if the arguments are not passed or passed with incorrect number of arguments.
- return keyword should be used only at the end of the function before the closing parenthesis
- If return keyword were to be used in the middle of the function then the remaining code will simply be skipped
- If a variable is declared inside a function it can't be accessed outside the function for example in the syntax a variable total has been declared inside the function, it cannot be accessed outside if the total variable to be put in a console log outside the function output will be "ReferenceError: total is not defined" this makes return keyword handy to get the value from total variable to outerscope
TBD (number of Ways to declare a function and the purpose of doing so)
REFERRED IN MDN
Top comments (0)