March 2, 2015
•Last updated November 5, 2023
How to REALLY Learn JavaScript Series: Part 4 Functions
Functions are the core of any programming language. Think of functions as frozen fruit. You go to the store buy fruit knowing it has an expiration date quickly approaching. Rather than waste the fruit and allowing it to spoil you decide to freeze it. Doing this allows you to enjoy it whenever you please and not waste your purchase.
Ok, that example may seem stupid but if you want to think about what a function can do it is usually best to apply it to something we deal with on a day-to-day basis. This post is meant to give you a background on what functions are and why you should love them. Once you learn how to use them you'll understand why JavaScript is so powerful.
What is a Function?
Functions in terms of programming and not fruit are groups of statements that can be run anywhere and at any time. Functions are declared using the function
keyword within JavaScript. Following the keyword is a set of arguments and then the body of the function. The basic syntax is as follows:
function functionName(argument1, argument2) {
// statements
}
A quick real world example:
// Define the function
function greeting(name) {
document.write("Welcome, " + name);
}
// Fire the function
greeting(Andy); // Outputs "Welcome, Andy"
In my example I wrote a simple function I named greeting. When executed the function outputs the name provided by the argument. A function will not execute on its own. Only until you call the function will the function actually execute. This can be both aggravating and awesome at the same time.
In the past, while learning the basics I would write a simple function and just forget to call it. I troubleshot until I finally did a big ole’ head in the palm. Don’t be like me and forget something so simple.
Functions in JavaScript don’t have to specify whether they return a value. The return
statement is typically used to return a value within a function. An important thing to note is that once the return
statement is fired the function will exit so make sure it is last inline within your function body.
Example
function yearsUntilRetirement(age, retirementAge) {
return retirementAge - age;
document.write('Ah retirement'); // Never executes
}
document.write(yearsUntilRetirement(27, 67)); // 40
The function above is a tiny calculator that subtracts your current age from the expected retirement age. The return
statement holds the value of the two arguments but as I explained the statement following the return statement never executes.
“It’s recommended that a function either always have a return value or never return a value”. [1]
Arguments
In JavaScript, there is no limit to the number of arguments you can pass to a function. The data types passed can be of any type. Just because you write a function to only accept two arguments from the start doesn’t mean you can’t have more or less than two. Inside the language, an array
is being passed to the function in the form of these arguments. The function doesn’t care whether the array
is empty or full. This is a rather confusing concept but I just wanted to mention it in the event that you don’t want to provide explicit arguments to a function.
You can define a function using arrays. The arguments
object in JavaScript allows this to work. It acts as the array within the function which you can access with bracket notation like arguments[0]
or arguments[1]
. So in use would look like:
function helloWorld() {
document.write('Hello ' + arguments[0] + ', it is ' + arguments[1]);
}
helloWorld('Andy', 'Saturday');
/* Outputs
Hello Andy, it is Saturday
*/
So in short, you don’t always have to define an argument within a function. The ability to get the values passed is possible but it is just merely behind the scenes within an Array
. You can call them using the arguments
object and using the bracket notation. If you need a refresher on Arrays never fear, I covered them briefly on Part 2 of this series.
Considerations
Functions have unique names of which are determined by you. Ideally, you would never define the same name for a function within your application but because we are humans this sometimes happens. The cool thing about JavaScript is that the language is smart enough to know when something like this happens. If JavaScript spots two functions with the same name it will find the last function with the name and promote it to be the function to use.
function addSomething(num) {
return num + 50;
}
function addSomething(num) {
return num + 100;
}
var result = addSomething(100); // 200
Here the first function addSomething()
is overwritten by the second function of the same name and thus the resulting output is both functions combined. To avoid confusion and bad practice, it is recommended to always have unique names within anything in JavaScript. You don’t want to shoot yourself in the foot just because you named something the same value. We’ve all done it so don’t beat yourself up over it but it's worth noting.
Examples
You can call functions based on events triggered by the user. This is easily done by incorporating a function within your HTML document. There are shorthands was of writing this as well as ways that don’t involve modifying the HTML but for the demonstration's sake, I’ll show you a simple idea.
JavaScript
function changeUser() {
document.getElementById('username').innerHTML = 'Your username us: <strong>Chris Farley</strong>';
}
HTML
<html>
<body>
<p id="username">Your username us: <strong>Andy Leverenz</strong></p>
<button onClick="changeUser()">Change Username</button
</body>
</html>
By clicking on a button we can modify HTML based on what is supplied.
You can go one step further and modify the HTML with JavaScript based on a form input which looks like this:
JavaScript
function changeUser() {
var userInput = document.getElementById('userInput').value;
document.getElementById('user').innerHTML = userInput;
}
HTML
<html>
<body>
<p>Welcome to the site <strong id="user">pal</strong> </p>
<input type='text' id='userInput' placeholder='Enter Something' />
<button onclick='changeUser()'> Change Username</button>
</body>
</html>
For the sake of brevity, I've some examples of simple applications you can build that utilize functions to execute below. These ideas are something you can build as you learn the language. As with anything I'm a firm believer in learning by doing so I really can't stress enough the need to try coding new things. To learn, you are going to fail. There's no doubt about that but that's what makes you become better at what you do. Try your hand at working with the examples I created above or the examples linked below. Hack the code until you get it where you like it. You don't always have to start from scratch either. Some of the best applications out there started based off other people's work. It's not necessarily stealing but more or less adapting to quality standards already set in place.
Build a Calendar
See the Pen Event Calendar Widget by Paul Navasard (@peanav) on CodePen.
Build a Countdown Widget
See the Pen Countdown Clock by Adem ilter (@ademilter) on CodePen.
A Fluid Carousel
See the Pen Fluid Carousel by Brad Frost (@bradfrost) on CodePen.
Accordians
See the Pen CSS Responsive animated Accordion by Chris Wright (@chriswrightdesign) on CodePen.
Check out CodePen.io for many more examples of the latest in web design and development. I have found it to be a great learning resource at it allows you to dive into other people's concepts and ideas to see how they pulled it off without hours and hours of research.
Conclusion
Functions make JavaScript kick ass. Having the ability to store data to use over and over whenever you like inside your applications is what makes the language so great. There's virtually nothing you can't do so long as your code it concise and valid. It took me a while to get comfortable with the ideas of functions and how to properly use them in real-world settings. Starting small will help you get towards your goal of writing highly interactive applications on many future projects to come. Hang in there because it's going to be tough to grasp but luckily with the resources we have the answer is most likely out there you just have to be smart and do some digging.
References
[1] - Professional JavaScript for Web Developers
The Series So Far
Categories
Collection
Part of the Beginner JavaScript collection
Products and courses
-
Hello Hotwire
A course on Hotwire + Ruby on Rails.
-
Hello Rails
A course for newcomers to Ruby on Rails.
-
Rails UI
UI templates and components for Rails.