30 Days Of JavaScript

Day 5: Functions Part 1

Lesson 1: What Are Functions?

As I said in the introduction, functions are block of code, wrapped up in a way to make them reusable. Here is a very simple example:

1function sayHello() {
2  console.log("Hello");

Now we have a function that we can call and it will print "Hello". You would call it like this:


Here's a few things to know about functions:

  1. You should be getting used to seeing code in between { } by now, and if you remember the lesson about 'let' vs 'var' then you should also remember that they create a new scope. Like creating a room in your house. This means that functions are portable and anything inside the function doesn't bleed out into the rest of your code.

  2. You can call them anywhere in your code, as many times as you like.

  3. You can import them from other files in your projects, in fact a well designed function can be used in any number of files and projects. They have everything in them that they need, in order to do what they need to do.

  4. Thanks to points 2 and 3 you have been using functions since the first lesson of this course and you didn't even realize it 😎

Really? Yep!

1console.log("This is calling a function");

That log() is a function and it takes what you put between the () and prints it to the screen. You don't need to know how it does it, however there is code that gets run to make sure that whatever you pass into log() appears in your logs.

In fact, the code that lives inside the log() function will call other functions, and those will call other functions as well. Programming is just functions all the way down 🤣

You'll have noticed that our function above is just sayHello() whereas console.log() has a . and then I just keep referring to log() when talking about it.

So the function is log() and it lives as a property on the console object. If you think back to learning about objects you will remember that we can create an object:

1const laptop = {
2  name: "MacBook Pro",
3  storage: "1TB",

And then access properties on that object with . like const ssd = laptop.storage.

Well, at the risk of jumping ahead you can indeed store functions in objects and call them in the same way.

We'll cover this in detail another day but for now here is an example to play with:

Which at this stage might break your brain a little bit. That's fine, that's why this is in an extras box 😉


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co