DEV Community

Martin Himmel
Martin Himmel

Posted on

JavaScript (ES5) Functions - Part 1

This was originally posted on my site at https://martyhimmel.me on January 2, 2017. Like a number of others on dev.to, I've decided to move my technical blog posts to this site.

A function is a contained block of code that performs a task. Generally, functions are created to be reusable pieces of code. Reusability means you don't have to write the same code over and over in every place you need it, which means you're writing less code and the program as a whole is much easier to maintain. With functions, you can create the function once and call it as many times as you need.

If you've been following this series, you've already seen a few examples of functions. console.log() - console is actually a global object in JavaScript, and .log() is a function (or a "method") of that object.

A quick side note about "function" versus "method." A method is a function inside of an object. That's it. If a function isn't attached to an object (e.g. in the global space), it's a function. If a function is attached to an object, it's a method.

Back to some functions/methods you've already seen. .pop(), .push(), .shift(), .unshift() are all array methods. All of the DOM selectors (e.g., .getElementById()) are methods of the document object.

Creating Functions

There are two ways to create functions in JavaScript - as a function expression and as a function declaration.

Function Expression

A function expression is similar to creating a variable. Use the var keyword, followed by the name of the variable, then set it equal to function() {};. Doing it this way creates an "anonymous" function. Optionally, you can give the function a name (this is different from the variable name) by adding a name between the function keyword and the parentheses (e.g. function myFunction() {}).

The code to be executed goes inside the curly braces. And because a "function expression" is set to a variable, it must be terminated with a semicolon. Here are examples both anonymous and named functions:

// anonymous function
var myFunction = function() {
  // do something
};

// named function
// var myReferenceVariable = function myFunction() {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

The named function expression can be useful for debugging. If a function is anonymous and an error occurs, the console will only say "anonymous function" as part of the stack trace. If a function is named and an error occurs, the name will be displayed in the stack trace.

Function Declaration

A function declaration starts with the function keyword, followed by the name of the function, then the opening and closing sets of parentheses and curly braces. Function declarations don't need a terminating semicolon - they're similar to loops and conditionals in that way. Here's an example:

function myOtherFunction() {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

What's the Difference?

There's one significant difference between the two ways of creating functions, and that's when you can call (use) the function. With a function expression, the function has to be created before the function is used in the file. With a function declaration, the function can be called anytime, before or after the function is created.

In this example, both functions are created before they're called and everything works as expected.

var myFunction = function() {
  console.log('inside myFunction');
};
myFunction(); // inside myFunction

function myOtherFunction() {
  console.log('inside myOtherFunction');
}
myOtherFunction(); // inside myOtherFunction
Enter fullscreen mode Exit fullscreen mode

Now, let's look at what happens in each if you call the function before it's created.

myFunction(); // Uncaught TypeError: myFunction is not a function
var myFunction = function() {
  console.log('inside myFunction');
};
Enter fullscreen mode Exit fullscreen mode
myOtherFunction(); // inside myOtherFunction
function myOtherFunction() {
  console.log('inside myOtherFunction');
}
Enter fullscreen mode Exit fullscreen mode

In the expression example, calling myFunction() before it is created breaks the script. On the other hand, in the "declaration" example, myOtherFunction() works perfectly fine. The reason behind this is because of the way JavaScript handles variables and functions, but I'll save the details of that for another tutorial.

In the meantime, which one should you use? It's mostly a matter of preference. There are certain cases where you'll need an expression rather than a declaration, but most of the time, you're free to use either one. Just keep in mind an expression can't be called before it's created.

Function Parameters and Arguments

Let's get the terminology out of the way. With functions, a parameter is a local variable that acts as a placeholder for expected data. Parameters are used when creating functions. On the other hand, when callling a function, you're passing arguments to the function. An argument is the actual data being passed. Really, this is similar to the function/method naming. They're the same thing, but developers use the different names to distinguish when they're being used - parameters in the function definition and arguments when passing data to the function.

When a function is created, you can set a list of parameters - the data expected to be passed in to the function when it's called. A function can have as many parameters as you want, though, for readability and maintainability's sake, you should keep the list as small as possible.

Consider this example:

function add(num1, num2) {
  return num1 + num2;
}
var value = add(4, 9);
console.log(value); // 13
Enter fullscreen mode Exit fullscreen mode

num1 and num2 are the parameters. Whatever num1 and num2 are, they will be added together, then the value will be returned.

The return statement in a function is the result of evaluating the function. In this case, the function evaluates to the total of two numbers. Not every function will have a return statement. Imagine you're displaying a string on a page as an HTML paragraph. The function may display the string and that's it - it does an action without needing to return anything.

Back to our example. In the var value = add(4, 9); line, 4 and 9 are the arguments (the actual data) being passed to the function. The function evaluates the code and assigns the returned value to the variable value. Afterwards, the value gets logged to the console.

Wrapping Up

Functions are incredibly powerful constructs in programming. Using the last example, we can see the reusability of functions.

console.log(add(13, 12)); // 25
console.log(add(100, 34)); // 134
console.log(add(0, 1)); // 1
console.log(add(5, 72)); // 77
Enter fullscreen mode Exit fullscreen mode

Without the function, you'd have to manually add the numbers each time. For a simple addition problem, that's no big deal, and is less code to just add the numbers. But let's say you have type checking in place.

function add(num1, num2) {
  var result = parseInt(num1) + parseInt(num2);
  if (isNaN(result)) {
    return false;
  }
  return value;
}
console.log(add(3, 4)); // 7
console.log(add(5, '8')); // 13
console.log(add(12, 'a')); // false
Enter fullscreen mode Exit fullscreen mode

Now our add function is more useful. First, it converts the passed arguments to numbers, then adds them. If either of the arguments can't be converted, then parseInt() returns NaN (not a number). Adding NaN to anything results in NaN, so our function returns false. Otherwise, it returns the value. Having to type all that every time you want to add two numbers is highly prone to errors, not to mention unnecessarily repetitive.

Hopefully this gives you a good grasp of using, creating, and the power of functions. In the next tutorial, we'll dive deeper into functions and really tap into their power and usefulness.

Top comments (0)