A function is a block of code that performs a specific task.
In simple word function is a set of statements that perform some task on input which we provide and return an output.
Benefits of Using a Function
- Function makes the code reusable. You can declare it once and use it multiple times.
- Function makes the program easier as each small task is divided into a function. Dividing a complex problem into smaller chunks makes your program easy to understand and reusable.
- Function increases readability.
Declaring a Function
The syntax to declare a function is:
function functionName () {
// function body
}
A function is declared using the function keyword.
The basic rules of naming a function are similar to naming a variable. The body of function is written within {}.
Example-1
function welcome(userName) {
console.log("Welcome",userName);
}
Calling a Function
In the above program, we have declared a function named welcome(). To use that function, we need to call it.
//calling function
welcome("Ashwini");
Here we are calling function by their name i.e. welcome
Example-2
A program to add two numbers and return the addition.
function add(a, b){
return a + b;
}
//calling function
add(3,5);
In above program the add function is used to sum of two numbers.
The function is declared with two parameters a and b.
The function is called using its name and passing two arguments 3 and 5.
We can call a function as many times as we want. We can write one function and then call it multiple times with different arguments.
Function Return
The return statement can be used to return the value to a function call.
The return statement denotes that the function has ended. Any code after return is not executed.
If nothing is returned, the function returns an undefined value.
Function Expressions
Such a function can be anonymous; it does not have a name.
let sum = function(a, b){
return a + b;
};
console.log(sum(3,5));
Function expressions in JavaScript are not hoisted, unlike function declarations. We can't use function expressions before We create them. When a function is created at the same time it is called. Function expressions are invoked to avoid polluting the global scope.
console.log(sum); // undefined
// even though the variable name is hoisted, the definition isn't. so it's undefined.
sum(); // TypeError: sum is not a function
var sum = function () {
console.log('bar');
};
Top comments (1)
If you add language direct after start of codeblock (The tre backtics) you get syntax highlight to.
Like this
Great article by the way like many code examples.