Functions in Javascript
Tags: javascript, webdev, beginners, tutorial
Published: 2021-12-03 13:30:29

Hello Guys today i am going to discuss functions in javascript

Lets get started....

JavaScript Functions - 

* A JavaScript function is a block of code designed to perform a particular task.

* A JavaScript function is executed when "something" invokes it (calls it).

Why Functions?
* You can reuse code: Define the code once, and use it many times.

* You can use the same code many times with different arguments, to produce different results.

JavaScript Function Syntax
* A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

* Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

* The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)

* The code to be executed, by the function, is placed inside curly brackets: {}

* function name(parameter1, parameter2, parameter3) {
  // code to be executed
}
* Function parameters are listed inside the parentheses () in the function definition.

* Function arguments are the values received by the function when it is invoked.

* Inside the function, the arguments (the parameters) behave as local variables.

Normal Functions - 
```javascript
function message(){
  let greet = "hello Mysterio"; // greet variable can be used here
  return greet;
}

console.log(message());
```
OUTPUT - 
```
Hello Mysterio
```

Parameterised functions - 
* Parameters are the names that are listed in the definition of the function. They are the mechanism of passing the values to functions.

* The values of the parameters are passed to the function during invocation. Unless it is specified explicitly, the number of values passed to a function must match with the defined number of parameters.

Syntax

The syntax for defining a parameterized function is:

function function_name( parameter1,parameter2 ,…..parameterN) {     
     //body of the function  
}  
Example - 
```javascript
function myFunction(p1, p2) {
  return p1 * p2;   // The function returns the product of p1 and p2
}
console.log(myFunction(10,7));
```
OUTPUT - 

```
70
```

Default Function Parameters - 
* In ES6, the function allows the initialization of parameters with default values if the parameter is undefined or no value is passed to it.

```javascript
function message(name = "Mysterio"){
  let greet = "hello "+name; // greet variable can be used here
  return greet;
}

console.log(message());
console.log(message("Stark));
```
OUTPUT - 
```
hello Mysterio
hello Stark
```
EXPLAINATION - 
* As you can see if you dont pass any argument to the function call then it will use the default parameter value and if you pass the argument with some value then it will use that value instead of default parameter value.


Function Return - 
* When JavaScript reaches a return statement, the function will stop executing.

* If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

* Functions often compute a return value. The return value is "returned" back to the "caller":

Example - 
``` javascript
function mySum() {
  let array = [1,2,3,4,5,6,7,8,9,10];
  let sum = 0;
  for(i = 0;i<=array.length;i++){
    sum = sum + i;
  }
  return sum;
}
console.log(mySum())
```

OUTPUT - 
```
55
```

EXPLAINATION - 
* We have created an array and it has 10 numbers from 1-10 inside it 
* Then we created a variable called sum and initialize it with value 0
* Then we iterate over the array using for loop and sum up all the value of elements inside array.
* finally we have return the sum using "return" keyword

Functions Used as Variable Values - 
```javascript
function message(){
  return "Hello ";
}

let x = message();
let greet = x + " Mysterio";
console.log(greet);
```

OUTPUT - 
```
Hello Mysterio
```

Local Variables
* Variables declared within a JavaScript function, become LOCAL to the function.

* Local variables can only be accessed from within the function.

```javascript
//greet variable cant be used here it is local and have scope inside the function only

function message(){
  let greet = "hello Mysterio"; // greet variable can be used here
  return greet;
}

// greet variable cant be used here it is local and have scope 
inside the function only
```

* Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

* Local variables are created when a function starts, and deleted when the function is completed.


Rest Parameters - 
Rest parameters do not restrict you to pass the number of values in a function, but all the passed values must be of the same type. We can also say that rest parameters act as the placeholders for multiple arguments of the same type.

For declaring the rest parameter, the name of the parameter should be prefixed with the spread operator that has three periods (not more than three or not less than three).

Example - 
```javascript
function heroes(...name){
  for (var i = 0; i < name.length; i++) {
    return name[i];
  }
}
const names = ["Stark","Captain","Thor","Hawkeye","Black Widow","Banner"];
console.log(heroes(names));
```

OUTPUT - 
```
[ 'Stark', 'Captain', 'Thor', 'Hawkeye', 'Black Widow', 'Banner' ]
```

EXPLAINATION  - 
* We created a function called heroes and passed a parameter name using spread operator then call the function with an array containing super heroes names and then displayed then names using for loop.

NOTE - There are more topics like Arrow function , Generators etc but they are little advance and are a part of ES6 So we wont cover those in this post.

THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE SUGGESTION PLEASE MENTION IT IN THE COMMENT SECTION.