JavaScript Functions
Tags: functions, coding, softwareengineering, basics
Published: 2023-01-23 17:35:29

## What is a _function_, how to **define** it?
A function is an object that contains a sequence of JavaScript statements. We can execute or call it multiple times. A function's purpose is to group bits of JavaScript code and help improve, read, and debug. This is used on non-abstract code, single tasks if you will. (Remember ' ; ' is optional)
![non-Abstract Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8efzto4xgh923vnlwc02.png)

Now we 'abstract' the code and create a collective name for it.

![Abstract Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xp6oumnyh9abhujemupg.png)

## How to **Call** a function?
In JavaScript, to execute the code of a function you simply add a set '( )' after its name. Note this only works for a function we defined or nothing will be called and receive an error. The '( )' tells JavaScript to invoke a function because of this, it is an invocation operator.
![call function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wsstk06srovtjwy0bfg9.png)

## Generalize a function
In coding, we want to make everything easier and generalizing functions is the way to accomplish that. Let's say we had some code about a vet clinic giving employee-specific instructions to care for each different cat and breed. Rather than hard-coding each cat/ breed in multiple objects, refer to them as variables in the function using string interpolation in one single function. That would be simpler and easier, only the variables would need to define.

![generalize parameters and arguments](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hnfpujgv4i91pd575a7g.png)

## what we learned so far
how to grab a list of operations and gather them into abstract code to create a function, then generalize that function to simplify code and its execution.
## Function Return Values
When we call a function, it is sometimes helpful to return something. Some may call them a description/summary of what is going on in the code. We would like the function to 'make a purchase' to return 'product(purchased)'. Javascript functions can return things as well.
Example:
![return value](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pibrm38dcjr5fmo9dw9g.png)
The _return_ statement tells Javascript to return whatever value to the right of it, the value can be an expression/string/ or a number. In the code when the return is reached, the return will be executed despite any code afterward. The code following after will not be executed(returned). From the example code if _hoursOfOperation === 'Closed'_ returns true. Hence the only code returned was `${catName} the ${catBreed} cat didn't get anything done today`. These return values can also be used as inputs in other functions or saved as variables. The basic syntax of the Function is like so: 
![basic function syntax](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hfycfgpl2blo2vzmzbe.png)

##Function Expression 
We gathered how to declare a function or function declaration but there are more ways to write out the function. There's another expression called arrow functions.
Example of a function declaration:


![function expression ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8xdav04tdpb21ozrdgl6.png)
Can also be written so

![other function ex](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iz499kpo846xaecdf4x3.png)
The _function expression_ is everything to the right of the assignment operator (_=_) of the function() {..}.
If it is not making any sense yet, a good analogy can help understand.
 
![funxtion expression](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wb07991o9cetddw110qy.png)

The  _expression_  would be that  _9 - 2_  returning  _7_  and assign a variable to  _expressionDiff_, the same would go for    _2 + 5_ returning 7.The variable would also be assigned to _expressionSum_.

Back to our expression  _function() { return 'burgers, fries, pizza, wings' }_ assigning a variable to  _food_ by returning a thing that can be called.
The function expression (everything after the =) is known as an  _anonymous function_. Unlike a function expression, an anonymous function doesn't have a name. You can however assign it to a variable that refers to a callable thing. Invoking _food()_ will call this anonymous function. _Food()_ is now the name for that anonymous function. Function declarations and function expressions have some differences but give the same output. It is up to the user to use either or, in JavaScript the user will learn over time when to use which method.

## Arrow Functions
Arrow Functions allow function declarations to use the arrow syntax of the function expression, ultimately not utilizing the keyword  _function_. It is best to get used to using this method, not only does it clean up the code for the user but also makes it simpler to follow along for other users. Debugging code would especially be easier to complete.
Example:

![Arrow Function Ex](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ts5rxpecufjjphflj8t0.png)
Back to saying Arrow functions make code look a lot better, they do not need any curly braces '{ }', making them **implicit returns**. Only returning the result of the last expression, Can also see the body of the function is in a single expression. No  _return_ keyword is required since it's not an explicit return, **only instance in JavaScript** where this occurs.

![noting arr function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28humpsc5738bwqqj7tw.png)
The parameters are to the left of the  _=>_, like a function declaration listed parameters are separated by commas inside a set of '( )'.

Arrow functions do not necessarily always use 2 parameters, they can use one. If that is the case the set of '( )' is not mandatory. Most coders won't use it.
Example:

![( ) arrow function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z77x4stnk1g1z9yh93eo.png)
With multiple lines of code in arrow functions, a  _return_ keyword is needed along with a set of _{ }_ after the  _=>_ 
Example:

![ArrFunc with {}](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5i0tva6hoyjyek0bo73n.png)

## Know when to utilize Arrow Functions
It's best to utilize Arrow Functions when you have to deal with a group of data one at a time, AKA  JavaScript _iterator_  methods.
For example, you had a set of projects submitted but the Teacher has to grade them separately.

Many methods utilize Arrow Functions, .map()/.filter().forEach(). For now, let's see an example of .map():


![.map() arr Func](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0y6amhh299n4f4nq1lhl.png)
In each iteration through the _sqaureNums_ array, _map_ passes the value of the element to the arrow function, which is the argument being passed and assigned to parameter x. A new array is stored 
of squared values. That new array is then returned when _map_ iterated through all the elements. (link for .map at the bottom)


##Conclusion
The above material should give you a better grasp on functions, functions expressions, function declarations, and arrow functions.
To know what they are, what they are used for, and when is the best time to utilize them in JavaScript. Did I already mention functions? 













## Study Links on Content

- (MDN) https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions
- (MDN) https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values
- (MDN)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
- (MDN)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
- (MDN)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map