Functions in JavaScript
Tags: javascript, webdev, functions, beginners
Published: 2021-10-13 12:06:45

If you have been into programming for a while then you must have come across functions. So there might be a little possibility that you would be very well aware about functions. But i would like to share the knowledge that I have of Functions. So here it goes hear me out-

Well if you ask me about functions then I would say that functions is one of my favorite topics in programming because they not only help us in writing clean, and efficient
code but also because **Functions** are a piece of code that enable us to call that block of code anywhere in the program thus refraining to not write that block of code again in the same program.
If you did not understand what functions are then you just need to have some patience and keep reading.  
![Have Faith](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/te5ilozl43q5g8s9tj7n.gif)

<b>Declaration of functions in JavaScript</b>

<b>Functions without any argument</b>
The functions that do not accept any argument are functions without arguments.
```javascript
function learnJS() {
    console.log("Attention reader! You need to learn JavaScript now!");
}

//calling learnJS function
learnJS();
```
The above code gives output
```javascript
Attention reader! You need to learn JavaScript now!
```


<b>Functions with argument</b>
The functions in which we pass on some value that would be accepted by some parameter that is present in function declaration. See below for better context
```javascript
function square(x) {
    let sq = x * x;
    console.log(sq);
}

//calling function
square(4); 
```

Difference between <b> Arguments </b> and <b> Parameters </b>
*Argument* - These are the values that we pass while calling the function and these act as the actual value that the variable would contain that we have declared while declaring or defining the functions.

*Parameter* - These are the variables that are use to store values that we have passed as argument while calling the function. These variables are declared while declaring the function.
![Args vs params](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5olj6dayydawrf07nfq6.png)

2. What if a function accepts an argument but we do not pass an argument?
To understand that go through below example
```javascript
function sayHi(person) {
    console.log(`hi ${person}`);
}
//calling the function
sayHi();
```
Output of above code would be 
```javascript
hi undefined
```
In case of string argument.

<b>Methods in JavaScript</b>
Methods are same as functions in Javascript except that these are the type of function that are already defined and we can access those functions simply by calling them and passing the relevant argument if it is required to pass. 
For instance refer the following example
<b>array.push()</b> is a predefined method/function which accepts an integer argument. 

<b>Multiple arguments in JavaScript Functions</b>
```javascript
function greet(firstname, lastname) {
    console.log(`Hello there! ${firstname} ${lastname}`);
}

//calling function
greet('Shatakshi', 'Gupta');
```
Above code will produce the following output
```javascript
Hello there! Shatakshi Gupta
``` 
 * Order matters! Now if you call the above function in the following manner
```javascript
greet('Gupta', 'Shatakshi');
```
Then it would lead to following result
```javascript
Hello there! Gupta Shatakshi
```
And that simply implies that while dealing with multiple arguments order matters. 

<b>The Return Keyword</b>
  * It is use to store/save value so that we can use it in future.

  * When return keyword is encountered, function execution stops and the value is returned and no next line is ever executed.
Refer the following code
```javascript
function add(a,b) {
    return a+b;
}
let total = add(5,6);
console.log(total);
```
And that will print as 11!

<b>Functions Scope</b>
 * variables declared inside a function cannot be used outside a function.

```javascript
function printValue(a) {
    a = a+1;
    console.log(a);
}

printValue(4);
console.log(a);
```
This will give following output
```javascript
5
VM1082:7 Uncaught ReferenceError: a is not defined
```
Another example of variables that can not be used outside functions. 
```javascript
function printScore(value) {
    let totalScore = 0;
    totalScore += value; //short form of totalScore = totalScore + value
}

printScore();
console.log(totalScore);
```
Now that would produce the exact same error like before because variables like 'let' and 'const' are block scoped hence can not be used outside except its own function.

 
<b>Block Scoped Functions</b> 
* variables inside loops like it if, for, or while loop cannot be accessed outside that block
```javascript
let value = 8;
if (value > 5) {
    let  score = value;
    console.log(`my score is ${score}`);
    const yay = "im greater than 5";
}

console.log(yay);
```
And the result of that is
```javascript
my score is 8
VM1106:8 Uncaught ReferenceError: yay is not defined
    at <anonymous>:8:13
```

  > if we declare our variables with <b>`var`</b> keyword, we can access that variable outside of that block because var is a globally scoped keyword while <b>`let`</b> and <b>`const`</b> are block scoped keywords.

<b>Lexical Scoped Functions</b>
 * function inside another function or nested functions
```javascript
function lexicalScope() {
    const randomNums = [34, 78, 88, 25]
    function anotherFunc() {
        for (let nums of randomNums) {
            console.log(`Numbers in the array are: ${nums}`);
        }
    }
    anotherFunc();
}

lexicalScope();
```
Which would give output as
```javascript
Numbers in the array are: 34
Numbers in the array are: 78
Numbers in the array are: 88
Numbers in the array are: 25
```


<b>FUNCTION EXPRESSION</b>
* In this variables store functions
* Functions act as value that are assigned to variables

* Function expression without any argument
```javascript
let JsIsAwesome = function() {
    console.log("JavaScript is awesome. Indeed!");
}

//calling the function 
JsIsAwesome();
```
The output of above expression would be
```javascript
JavaScript is awesome. Indeed!
```

* Function Expression with Argument

```javascript
let add = function (x,y) {
 console.log(x+y);
}

//calling the function
add(5,6)
```
The output of above expression would be
```javascript
11
```

<b>FUNCTION STATEMENT / FUNCTION DECLARATION</b>
```javascript
function sayHi() {
 console.log("hello there!");
}
```
<b>ANONYMOUS FUNCTIONS</b>
 * These are the functions used in function expressions.
 * These basically have no name.
![Anonymous funcs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twm0byb5ba1psf7vpvbk.png)

<b>FIRST CLASS FUNCTIONS</b>
The ability to use functions as values, pass functions as arguments & return function as a value are known as first class 
functions.

<b>HIGHER ORDER FUNCTIONS</b>
* The functions in which we can pass function as argument
```javascript
function basicJavascript(func) {
 func();
 console.log("But first I should clear my basics of JavaScript");
}

function learnJavascript() {
 console.log("I need to learn JavaScript");
}

basicJavascript(learnJavascript);
```
OUTPUT
```javascript
I need to learn JavaScript
But first I should clear my basics of JavaScript
```

* The ones in which we can return function as value
```javascript
function func() {
    let random = Math.random();
        if (random < 0.5) {
        return function() {
        console.log("thats too low!");
        }
    } else {
        return function() {
        console.log("thats too high!");
        }
    }
}
func();
```

<b>ARROW FUNCTIONS</b> 
* These are type of functions that are syntactically alternative to a regular <i>function expression</i>
* In this we remove `function` keyword and use an arrow to show that there is an function ahead
```javascript
const add = (x, y) => {
 return x + y;
} 
```

now how would you call this function in the following way
```javascript
add(1,7)
```
that would print out to be 8!

<b>Arrow functions with no arguments</b>
```javascript
const print = () => {
 console.log("This function says me to only print");
}

// calling above function
print();
```
OUTPUT:
This function says me to only print

<b>Arrow functions implicit return</b>
if you have a single statement inside arrow functions that needs to be evaluated like printing or a simple calculation then u can do that in the following way:
```javascript
let add = (x, y) => x+y
```
now above statement is the same as you just wrote the one with curly braces!

<b>CALLBACK FUNCTIONS</b>
* Function that is passed into another function or the function that is passed as an argument to another is called a callback function.

* These are the type of functions that execute only when a certain function or statement has finished executing.
Refer below code
```javascript
console.log("Hellooo..");

setTimeout(() => {
    console.log("well this got printed after 5sec and that is an example of CallBack concept!");
}, 5000);

console.log("Do you know CallBacks help us play with the async nature of js?");
```
And that gives us the output
```javascript
Hellooo..
Do you know CallBack helps us play with the async nature of js?
undefined
well this got printed after 5sec and that follows CallBack concept!
```
<b>CONCLUSION</b>
Okay so that was a lot to grasp. But no worries you can go through this article whenever you feel like referring. If you have come this far then Congrats 🎉 you just learned some really important topics in JavaScript. 
I'm so proud of you and wish you nothing but the best in your life as you keep learning and growing.
![congrats](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d78b1nglowc8w4agn4lp.gif)


Thanks for reading and hope you have great day! :)
You can connect with me on [Twitter](https://twitter.com/shatakshiigupta)