March 9th, 2020
Welcome back! This time around, we’ll be talking about functions. Before we start, feel free to check yesterday’s topic if you haven’t!
Javascript in 15 Days : Object Math
First of all, what are Functions and why do we need them? To say the least, functions are declarations of a block of code, that are first initialized, but never called, until specified. You might think, what does that mean? Let me show you.
Let’s say you want to greet people, in this case greeting maybe three people and printing them to the console. You might come up with a similar idea like this.
Here you can see that for every person I made, I had to make a variable. This seems fine for now, but what if I needed 100 people? This could cost me a lot of time and makes my code a total mess. This is where functions come in. From what you saw above, we can easily modify it to the one below.
This is just to give yourself an idea of the basic structure of a function. Now, if I ran the code above, the following output should be printed to the console.
Pretty easy right? Actually the concept of functions itself is not that complex. What makes functions complex is when you combine them with the past topics we’ve discussed. It can be combined with loops, conditionals, variables, etc.
Now, onto a more advanced approach. Let's say you want to make your function really flexible, so as to not serve one purpose, well there's the keyword return in Javascript that does it for us. For example, let's see the code below.
. Next, we make two functions, the formatName and a getFamilyName. getFamilyName is a function that gets the first letter after the space, and appends a "." at the back of it, and then return the result. Now, in formatName, we get the first name, and add a space, with the result of the previously stated getFamilyName. And as a result, after running our code, with the input "John Doe", we get the output "John D.", as expected.
This simulates the work of return and how we can use a function within another function. If you wanted to know what this term of splitting functions are, it's called modular functions, and we will be spending more time into the in-depth knowledge of modular functions in a later time. This is just to get you a quick preview on how to use the return keyword.
That’s the end of today’s lesson. Next up, Review Day! We’ll be reviewing our past topics, from Day 6 ~ 8. See you later, and if you have any questions, feel free to hit me up on LinkedIn or Twitter!