DEV Community

Cover image for JavaScript Functions
Jose Campos
Jose Campos

Posted on

JavaScript Functions

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

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

Abstract Code

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

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

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
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

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
Can also be written so

other function ex
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

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
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
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
With multiple lines of code in arrow functions, a return keyword is needed along with a set of { } after the =>
Example:

ArrFunc with {}

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
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

Top comments (0)