Functions - Built-in

Beginner JavaScript

Enjoy these notes? Want to Slam Dunk JavaScript?

These are notes based on my Beginner JavaScript Video Course. It's a fun, exercise heavy approach to learning Modern JavaScript from scratch.

Use the code BEGINNERJS for an extra $10 off.

BeginnerJavaScript.com

These videos are going to be about functions. We will get a good primer on what functions are, the core concepts, and an overview of the types of functions that you can write.

It will not be exhaustive, because there is so much more we need to learn in order to take advantage of functions. The rest of the course is going to be using functions, since they are like types, a fundamental building block of JavaScript and we will get good at functions because we will be writing them throughout this entire course.

So, functions, what are they?

They allow us to group together sets of statements.

As a refresher from previous videos, these are all statements πŸ‘‡

refresher using bunch of statements

If you wanted to group all those statements together (generally they are related to each other and generally they produce some sort of output), you could group them together inside of a function.

Functions can take in data, those are known as arguments (we will discuss the difference between arguments and parameters shortly). When you pass data to a function, it is known as an argument.

Functions perform some work (a statement), and sometimes they also return a value.

Let's look at an example in the console using Math.max() (this is actually a method, and we will explain the difference between a function and a method shortly, it is not much).

If you run it in the console, it returns negative infinity.

math max functions returning negative infinity

What we want to do is pass it some data, and it should return to us the maximum value.

For example, let's pass two numbers, 10 and 12. It will return to us the highest number (which is 12).

math max function returns highest as 12 between two numbers 10 and 12

Now what is going on there?

Math.max(10, 12) is a JavaScript statement. The values 10 and 12 that we are passing into the function are called arguments.

If you are passing multiple values to a function, you need to separate each value with a comma and it's best practice to include a space between each.

To repeat, the data that you pass to a function, the data that you give to a function in order for it to run is called an argument.

Sometimes, functions will return to you some data that is generally the answer or the computed output based on what you passed in.

For example, Math.floor(2.4444) will return 2.

Here we are passing one argument of 2.4444 and it returns to us the floor of that value which is 2.

math floor returning 2 as output corresponding to 2.4444

Built-in Functions

There are a whole bunch of built-in functions in JavaScript, whether you are using it in the browser or with Node.js.

JavaScript comes with all of these built in functions, and we have already been using them because there is no way around it. The one that we have used the most so far is console.log().

For example if you console.log('hey'), it will return hey.

Interestingly enough, it also returns undefined.

console logging a string hey

That is because the console.log function logs to the console, it does not return a value. Not all functions are meant to return a value, sometimes they just go off and do things without returning a value.

Tip: You can tell in the console if something is a return or a statement by the > and <. arrows next to the line in the console. > indicates that it's a statement and <. indicates that it's the response to the statement.

console log returns undefined after logging hey at the end

Some other built in functions we can use are πŸ‘‡

parseFloat() which takes in a string and returns a number, it switches the type. For example πŸ‘‡

parseFloat("20.34543543");

parseFloat takes 20.34543543 as string and returns 20.34543543 as number

parseInt() takes in a string and returns a number without a decimal. For example πŸ‘‡

parseInt("20.3243423");

parseInt takes 20.3243423 as string and returning 20 as number without decimal

We looked at Math.round(), Math.floor(), Math.ceil() already in previous lesson.

If you type Date.now() in the console it will return something like the following πŸ‘‡

date now function returns number of milliseconds passed since january 1 1970

Date.now() is a function that does not take in any arguments. What it returns to us is the number of milliseconds since January 1, 1970.

If you go to https://epoch.now.sh, it's a tool that you can use to convert the millisecond value to a datetime. You can also do the opposite -- pick some date and time in the future and then it will return the millisecond value.

converting millisecond to datetime value using epoch converter

We will go deeper into dates in future videos.

We also have functions that will work with something called the DOM, which are the HTML elements that are on the page.

Create a new file called functions.html, and use the html base snippet.

Add a paragraph tag inside of the body that says "hey, how ya doin?" and then add an empty script tag below.

Open that up in the browser. πŸ‘‡

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>Functions!!</title>
    <link rel="stylesheet" href="../base.css" />
  </head>

  <body>
    <p>Hey How ya doin?</p>
    <script></script>
  </body>
</html>

In the script section of functions.html, add the following code. that will run a function called document.querySelector(), to which we are passing a selector p. This built in function will find something that matches that selector and puts it into a variable, and we will log that variable.

<script>
  const p = document.querySelector("p");
  console.log(p);
</script>

selecting an element using querySelector

There are a lot of other functions built in, some are mobile specific like navigator.vibrate().

navigator vibrate returning error as it requires an argument to be passed telling duration to vibrate in milliseconds

Another useful thing is if you are not sure what arguments a function should take, you can refer to the Mozilla developer docs, in order to see what is going on.

In google, type "Navigator.vibrate()". Usually you will need to look for the Mozilla Developer website (a tip is to include mdn at the end of your search so the Mozilla docs float to the top).

The docs should explain what the method is, how it can be used, and what it returns.

mozilla developer website to see the documentation for Navigator vibrate method

Let's look at a couple of more.

Clear the console.

In functions.html, add a lot of text, such as a few paragraphs of Lorem Ipsum.

(Wes is using the Emmet extension for VS Code which allows him to type lorem500 and hit tab to expand 500 words of lorem ipsum. You can manually search for a Lorem Ipsum generator online if do not have the Emmet extension.)

Now if you refresh functions.html you will see a lot of text on the page.

generate random words by typing lorem400 and hitting tab to have 400 words of lorem ipsum

Add enough text so you can scroll on functions.html.

Now you should be able to type in the console window.scrollTo(0, 600), and that should cause your window to scroll down 600 pixels.

If we search for scrollTo on Mozilla docs, it says it accepts arguments of a x and y coordinate, or you can pass it an options object.

The docs say that

options is a ScrollToOptions dictionary

Dictionary is a word we use in JavaScript to represent an object, it's an object that has a number of set properties on it.

use window scroll to function to scroll down the window by passing x and y coordinates

Example #1 πŸ‘‡

window.scrollTo(0, 1000);

Example #2 πŸ‘‡

window.scrollTo({
  top: 100,
  left: 100,
  behavior: "smooth",
});

In the first example, we are passing two numbers but it's also an option to pass an object which has properties inside of it like top, left, and behavior.

Try typing into the console the following πŸ‘‡

scrollTo({ top: 500, left: 0, behavior: 'smooth' })

That page should cause the page to scroll down 500 pixels.

passing an object to window scrollTo function to specify properties like top left and behavior

scrollTo is an example of a function that does not return anything, instead it just goes off and does some work for us.

Find an issue with this post? Think you could clarify, update or add something?

All my posts are available to edit on Github. Any fix, little or small, is appreciated!

Edit on Github

Syntax Podcast

Hold on β€” I'm grabbin' the last one.

Listen Now β†’
Syntax Podcast

@wesbos Instant Grams

Master Gatsby

Master Gatsby

Building modern websites is tough. Preloading, routing, compression, critical CSS, caching, scaling and bundlers all make for blazing fast websites, but extra development and tooling get in the way.

Gatsby is a React.js framework that does it all for you. This course will teach you how to build your websites and let Gatsby take care of all the Hard Stuffβ„’.

MasterGatsby.com
I post videos on and code on

Wes Bos Β© 1999 β€” 2021