What are functions and why do we need them anyways? Functions are used to tell the machine to do a certain action, or sequence of actions. When you call the function in the code, it’ll do what you told it to do in the function.
Think of the function like training a dog to do a number of tricks in a row. sit, lie down, roll over, sit up, turn around. First you need to teach it what to do and in which order. But you’ll also teach the dog a command for this, maybe “hockey-pockey”.
The function writes out all the steps that needs to happen: sit, lie down, roll over, sit up, turn around. So that a later point you can just call the function by simply saying “hockey-pockey”.
Ok, let’s start with a simple trick ‘lie down’ :
function nowDo(commandOne) {
console.log(`OK computer, I want you to ${commandOne}`);
}
nowDo(‘lie down’);
This will write out “OK computer, I want you to lie down”. First, we told the computer what to execute (writing out the command in the console), and then we called it and defined what to execute the command with (lie down).
We can also define a default, so that the machine knows what to do if there is nothing else specified.
function nowDo(commandOne = ‘sit’)
This way it will use commandOne and if it can’t find it then it’ll use ‘sit’, so if we follow the above with:
nowDo(‘roll over’); // will write “OK computer, I want you to roll over”
nowDo( ); // will write “OK computer, I want you to sit”
So far so good. There are two more important things: the return function which forces the function to produce and output we can actually use (other than writing something directly into the console), and the fact that we can then store that output into a variable.
So we want to create a function (tell it to do something), then force it to return an output (the result of what we told it to do), and then save that result into a variable. Observe.
Let’s try and calculate the numbers of cells in a spreadsheet (because who doesn’t do that on a regular basis?)
function cellCount(rows,columns) {
return rows*columns;
}const numOfCells = cellCount(5,4);
console.log(numOfCells);
First we create a function that we call cellCount and we tell it that there are two parameters this function will be using: rows and columns. We then tell it to spit out the result (return) of multiplying the number of rows by the number of columns. Then we create a variable (that won’t be changing, so we use const) that we call numberOfCells. We define the value of the variable as the result of the cellCount function for 5 rows and 4 columns. So the value of numOfCells is 20 in this case. (The console.log is only there to check that we didn’t mess up).
So that’s it, the basis of funky functions in JavaScript.
