Organizing Your JavaScript Code with Functions

John Au-Yeung
The Startup
Published in
9 min readOct 14, 2019

--

Photo by Shahadat Shemul on Unsplash

Functions are small blocks of code that takes in some inputs and may return some output or have side effects, which means that if modifies some variables outside the function. We need functions to organize code into small blocks that are reusable. Without functions, if we want to re-run a piece of code, we have to copy it in different places. Functions are critical to any JavaScript program.

Defining Functions

To define a function, we can do the following:

function add(a, b){
return a + b;
}

The function above adds 2 numbers together and return the sum. a and b are parameters, which lets us pass in arguments into the function to compute and combine them. add is the name of the function, which is optional in JavaScript. The return statement lets the result of the function be sent to another variable or as an argument of another function. This is not the only way to define a function. Another way is to write it as an arrow function:

const add = (a, b) => a + b;

The 2 are equivalent. However, if we have to manipulate this in the function, then the 2 aren’t the same since the arrow function will not change the value of this inside the function, like the function defined with the function keyword does. We can assign the function…

--

--