Jacob Paris
← Back to all content

Basic javascript functions

A function is a block of code that can be called and executed at will

1function setTitle() {
2 document.title = "Async, Await, and Promises"
3}
4

This gives us a function named setTitle. To execute it, call it by name with parentheses after, like setTitle()

Before: Alt Text

After: Alt Text

Arguments

Functions can also have arguments, which are variables you pass into a function when you call it.

1function setTitle(title) {
2 document.title = title
3}
4
5setTitle("Async, Await, and Promises")
6

This makes functions much more reusable, since you can call it with any value you want

1setTitle("Who me?")
2setTitle("Yes you.")
3setTitle("Couldn't be")
4setTitle("Then who?")
5

Callbacks

When you call a function, sometimes it can call back to another function

The setTimeout function accepts two arguments: a callback function, which it executes when it's finished waiting, and a delay, which is the number of milliseconds to wait

1function setTimeout(callback, delay)
2

We can use this to call our original setTitle function automatically after one second.

1function setTitle() {
2 document.title = "Async, Await, and Promises"
3}
4
5setTimeout(setTitle, 1000)
6

This works since we're setting the title explicitly, but if we try to pass it in as an argument it just clears the title, shown below

1function setTitle(title) {
2 document.title = title
3}
4
5setTimeout(setTitle, 1000)
6

What happened? Since the callback (setTitle) is executed by the function (setTimeout) we don't have control over what arguments setTitle is called with.

So instead of passing setTitle as our callback, we can make our callback a wrapper function instead

1// Pattern 1: Named Function
2function wrappedSetTitle() {
3 setTitle("Async, Await, and Promises")
4}
5setTimeout(wrappedSetTitle, 1000)
6
1// Pattern 2: Anonymous Function
2setTimeout(function () {
3 setTitle("Async, Await, and Promises")
4}, 1000)
5
1// Pattern 3: Arrow Function
2setTimeout(() => {
3 setTitle("Async, Await, and Promises")
4}, 1000)
5
1// Pattern 4: Inline Arrow function
2setTimeout(
3 () => setTitle("Async, Await, and Promises"),
4 1000,
5)
6

Now setTimeout will wait until 1000 milliseconds have passed, then invoke our wrapper function which calls setTitle with a title of our choice

Professional headshot

Hi, I'm Jacob

Hey there! I'm a developer, designer, and digital nomad with a background in lean manufacturing.

About once per month, I send an email with new guides, new blog posts, and sneak peeks of what's coming next.

Everyone who subscribes gets access to the source code for this website and every example project for all my tutorials.

Stay up to date with everything I'm working on by entering your email below.

Unsubscribe at any time.