Menu Home

function

Hi everyone! And welcome to another post of Boring JavaScript! Today, we tackle functions within JavaScript.

You can view the entire video here:

Functions, functions everywhere

Functions are a fundamental part of JavaScript. But what is a function? In the general sense, a function is a series of instructions executed together as a single routine in which data is passed into the function, the statements executed, and a final result is returned.

Confused? Let’s take a look at two examples:

const a = 1;
const b = 2;
const c = a + b;
console.log(c);    // prints 3

Take a look at the third line. The right side of the equals sign is, in the very strictest use of the term, a function. Two inputs – ‘a’ and ‘b’ – are passed to a function called “+”, which adds the two numbers together. The result of that is returned to the left side of the equals sign, which is then placed into the variable ‘c’. This is an example of a very basic function.

But wait! That’s an operator, not a function! Yes, it is – in the JavaScript language. But the example shows that even operators can be thought of as functions – inputs are received, some operations occur, and and output is sent back. It’s fundamentally important that you understand most everything in JavaScript is, at the brass tack level, a function.

Now that you’re confused, let’s a take a look at an actual JavaScript function:

function isEven(number) {
    if (number % 2 === 0) {
        return true;
    } else {
        return false;
    }
}

const isElelenEven = isEven(11);
const isTenEven = isEven(10);

console.log(`Is 11 even? ${isElevenEven}`);    //prints false
console.log(`Is 10 even? ${isTenEven}`);        // prints true

The above is an actual JavaScript function. It has five parts:

  • The function name ‘isEven’. Naming the function is important if we wish to reference it later (line 8 in our example).
  • The arguments passed to the function – ‘number’. Arguments are passed within parenthesis, and tells the function how many values to expect – in this case one argument or value. These arguments are converted to variables to be used within the function. They are only available within the function.
  • The curly-cue brackets – ‘{‘ and ‘}’. The JavaScript statements to be executed by this function are all located within these brackets.
  • The code to execute – this will be Lines 2 through 6 above. Regular old JavaScript statements that are run each time the function is called somewhere else in the code.
  • Finally, the value to return. This is accomplished by the ‘return’ statement in Lines 3 and 5. After the function finishes executing, the ‘return’ statement tells JavaScript the final value coming out of the function. Once a return statement is executed, all execution of the functions ceases at that point.

When you develop functions, you’re basically letting JavaScript build you a custom library of commands and routines. In fact, you can do just about anything in JavaScript using Functions. That’s why functions are a fundamental part of the JavaScript language – and why just about everything you see in JavaScript is a function.

I Shot an Arrow Into the Air

With a recent change to JavaScript, a different way to write functions was created, and those are called arrow functions.

Let’s take a look at the same code above, but written as an arrow function:

const isEven = (number) => {
    if (number % 2 === 0) {
        return true;
    } else {
        return false;
    }
}

const isElelenEven = isEven(11);
const isTenEven = isEven(10);

console.log(`Is 11 even? ${isElevenEven}`);    //prints false
console.log(`Is 10 even? ${isTenEven}`);        // prints true

Notice a slight change in Line 1. Instead of using the function verb, we now declare our ‘isEven’ function as a variable and make it equal to the arrow function.

The arrow function has all the same parts as a regular function – it’s just declares it a little different.

  1. There is no ‘name’ any more, which means you will need to assign it to a variable. Having no name makes arrow functions ideal for when anonymous functions are needed (such as callbacks).
  2. There is an ‘arrow’ expression – “=>”. This is what gives arrow functions their names.
  3. Otherwise, arguments, blocks, code, and return statements are all the same as a normal function.

When should you use arrow functions? Pretty much any place you would use a normal function. A great place they are used are in callbacks to events, like DOM events:

document.getElementById('myButton').addEventListener('click', (event) => {
    // do whatever you want with the event variable
});

Here we use an arrow function as the callback for a ‘click’ event on a DOM element.

But really – why even have arrow functions other than to get to use a different syntax? Because of one very, very, VERY important difference between arrow functions and regular functions.

This is This, and That is That.

There are some really important differences between arrows functions and normal functions. You can find the entire list on the Mozilla Developer Network, but I want to cover a critical one here.

And that’s how “this” is handled.

Let’s look at some code:

const animal = {
    head: true,

    born: function () {
        console.log('--------inside born');
        console.log(this);
    }

    walk: () => {
        console.log('--------inside walk');
        console.log(this);
    }
}

animal.born();
animal.walk();

If you run the code, you will get something like this:

--------inside born
{ head: true, born: [Function: born], walk: [Function: walk] }
--------inside walk
{}

What happened? You’ve hit upon a very important difference between an arrow function and a normal function – how ‘this’ is defined.

Within a ‘normal’ function, ‘this’ is defined (generally) as belonging to the parent of the function. With arrow functions, however, it is “generally” defined as the root object of the system, no matter how it was created.

(Caveat: ‘this’ definitions can be rather complicated. I suggest reading up on them to understand more. The above is a generic and typical use case definition).

Because of this, you should NOT use arrow functions as functions of objects (or methods on classes) unless you are certain you’ll never need to access this within the function. Which means the code above is not good code as an arrow function was used on the walk() function.

This lack of ‘this’ is an advantage, though. Since ‘this’ refers to the global object, the possibility of data leakage into your function is minimized – which in turn means your function can be guaranteed to behave the same time each time the same arguments are passed into it.

The Video

As always, you can see the above in our series of Boring JavaScript videos. A must-see if you need to fall asleep.

Shameless Plugs

Check us out all over the web!

Facebook

YouTube

Twitter

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: