πŸ•·οΈ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 63 (from laksa008)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

πŸ“„
INDEXABLE
βœ…
CRAWLED
3 days ago
πŸ€–
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.1 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://wesbos.com/javascript/02-functions/different-ways-to-declare-functions
Last Crawled2026-04-16 14:10:12 (3 days ago)
First Indexed2021-06-09 11:12:17 (4 years ago)
HTTP Status Code200
Meta TitleDifferent Ways to Declare Functions - Wes Bos
Meta DescriptionOne thing you will hear often when getting into JavaScript is that functions are "first-class citizens".
Meta Canonicalnull
Boilerpipe Text
One thing you will hear often when getting into JavaScript is that functions are "first-class citizens" . JavaScript functions are values in themselves, and they can be stored in variables and passed into other functions. What is a value in JavaScript? We know that in the examples below πŸ‘‡ that true and 100 are values. const age = 100 ; const cool = true ; Those are values that are numbers, or strings or booleans. What is cool about JavaScript is that functions can be: passed into other functions. stored in variables, moved around like any other piece of data in JavaScript That is not true for every other programming language. Let's start by looking at how you can put a function into a variable, and then look at the different ways to declare functions. Create a new file ways-to-make-a-function.js in the /custom-functions directory. < script src = " ./ways-to-make-a-function.js " ></ script > Add a log of "it works!" and go back to the index.html file and change the path in the script source attribute as shown above πŸ‘† and refresh the browser to ensure it works. We already know one way to declare a function and that is using the function keyword, like so πŸ‘‡ function doctorize ( firstName ) { return `Dr. ${ firstName } ` ; } Anonymous Functions Let's look at some other options we have when declaring functions, starting with an anonymous function , which is a function without a name. To make doctorize an anonymous function, you would modify it like this πŸ‘‡ function ( firstName ) { return `Dr. ${ firstName } ` ; } However, that is not valid JavaScript. If you try running it in the console you will see an error that says πŸ‘‡ SyntaxError: Function statements require a function name Anonymous functions are only valid in some use cases, such as using them in callbacks (we will learn more about that later) as well as in an IIFE (immediately invoked function expression) . This example was not a valid use case. Why would you ever want an anonymous function? Function Expressions The next way we will cover to declare a function will help explain that, which is as a function expression . Add a comment above that function specifying that it is an anonymous function, then copy the function and comment it out. Paste the copied code below the commented-out function. The next way to declare a function is a function expression . A function expression is when you store a function as a value in a variable. πŸ‘‡ // function expression const doctorize = function ( firstName ) { return `Dr. ${ firstName } ` ; }; In the code above πŸ‘†, we have taken the anonymous function and stuck it in a variable. If you refresh the page, you will see that in the console, we have doctorize() available to us, and we can call it like we did in previous videos. Having the ability to store a function in a variable is what leads people to say functions are "first-class citizens" . You may come across developers who say to not use function expressions because they used to give unhelpful errors. Previously, anonymous function errors would just tell you that they occurred in an anonymous function, without giving you any clue where the error is happening. However, now the dev tool errors are better. Here is an example that demonstrates what they mean by that πŸ‘‡ // function expression const doctorize = function ( firstName ) { doesntExist (); return `Dr. ${ firstName } ` ; }; In our case, it does now tell you it happens inside of doctorize on line 12. Although the function is technically an anonymous function without a name, the browsers will now infer the name of the function from the variable name and use that in the errors. What is the difference between a function declaration and a function expression? What is the difference between doing a function declaration and a function expression? Why would you want to use one over the other? Hoisting There is only one real difference which is how they operate in something called hoisting . We will go over this in detail in a future video but for now we will just quickly cover the concept. Duplicate the doctorize function and name it doctorize2 , like πŸ‘‡ const doctorize = function ( firstName ) { return `Dr. ${ firstName } ` ; }; function doctorize2 ( firstName ) { return `Dr. ${ firstName } ` ; } Let's say right before the first doctorize function, we called doctorize and passed it the value of "wes", as shown below πŸ‘‡, do you think the code will run? If you run a function before you define it, does it work? Refresh the page and look at the console to test it doctorize ( " wes " ); const doctorize = function ( firstName ) { return `Dr. ${ firstName } ` ; }; function doctorize2 ( firstName ) { return `Dr. ${ firstName } ` ; } Did it work? Nope! You get an error like: Uncaught ReferenceError: Cannot access 'doctorize' before initialization at ways-to-make-a-function.js:78 (anonymous) @ ways-to-make-a-function.js:78 What about doctorize2 ? console. log ( doctorize2 ( " wes " )); const doctorize = function ( firstName ) { return `Dr. ${ firstName } ` ; }; function doctorize2 ( firstName ) { return `Dr. ${ firstName } ` ; } It does work! Why does a function declaration work if you call it before you define it, but a function expression does not, especially when we created the exact same function in both cases? Functions that are declared with the function keyword are called hoisted . JavaScript will take all functions with the function keyword and hoist them up, up, up and says "you're a function, you belong at the top of the file". That means anywhere you call the function, it will be available to you. JavaScript does not hoist variable functions. When is that useful? Very rarely, Wes has never used that in his entire career except for tiny use cases. Hoisting is more of an interview question that you may be asked. Essentially it means that JavaScript will take functions and bring them up to the top of the code before they are called. This gives us the ability to run a function before it is defined. Remove the doctorize2 function from the JavaScript file which should leave just the function expression. Arrow Functions The next way to make a function is using an arrow function . Arrow functions themselves have a few different ways of being declared. They are a newer addition to JavaScript, and were added in the last couple of years. They have a few benefits: concise syntax and tend to be shorter allow for writing one line functions do not have their own scope in reference to the this keyword (we will cover the this keyword in a future video) Arrow functions are also anonymous functions , which means there is no way to declare an arrow function the way we do a function declaration function doctorize() {..} . You always have to stick it into a variable. To illustrate this, we will begin by writing a regular function. πŸ‘‡ function inchToCM ( inches ) { const cm = inches * 2 . 54 ; return cm; } This function will take in inches and return centimeters. Let's try it out in the browser. This is a pretty simple function, but it still takes up 4 lines of code. We can make it a bit shorter by instead of creating a variable and then returning a variable, we can just return the calculation directly. function inchToCM ( inches ) { return inches * 2 . 54 ; } Note: You may notice in the above πŸ‘† screenshot that the line of code with return cm; is now greyed out. That is because that code will never be reached, since we are returning in the line of code above it. When you return from a function, the function stops running. Now we can convert it to an anonymous function as a step on the way to making it an arrow function. const inchToCM = function ( inches ) { return inches * 2 . 54 ; }; Refresh the page to check that it still works, which it should. All we have done is turned it into an anonymous function and stored it in a variable. Different Ways to Write Arrow Functions Let's convert it to an arrow function now, which we can do a few different ways. Instead of writing the word function, we will delete it like so πŸ‘‡ const inchToCM = (inches) { return inches * 2 . 54 ; } Now we will go to the right of the parenthesis and add what is called a fat arrow => . In programming, -> is referred to as a skinny arrow and => is referred to as a fat arrow . const inchToCM = ( inches ) => { return inches * 2 . 54 ; }; When you save, you might notice that Prettier modified the function for you and removes the parenthesis, which is not what we want because we are trying to change it to an arrow function in steps.To disable that, add /* eslint-disable */ right above the function. The spaces between the parenthesis and the arrow in the following code πŸ‘‰ (inches) => { does not have to be there, this is the same code with different whitespace and πŸ‘‰ (inches)=>{ still works, but it's more readable with spaces. If you refresh the page and run it in the console, you will see that it still works. Implicit and Explicit Returns The next thing we will do is what is called an implicit return . An explicit return is when you type the return keyword before returning a value such as πŸ‘‡ return inches * 2 . 54 ; That is an explicit return meaning that we explicitly return the value there . An implicit return is returning it without actually having to type the keyword return . Arrow functions allow us to use implicit returns. Let's start by putting the function on one line, like so πŸ‘‡ const inchToCM = ( inches ) => { return inches * 2 . 54 ; }; To get rid of the explicit return: first put the function on one line then delete the curly brackets { } finally, delete the return keyword const inchToCM = ( inches ) => inches * 2 . 54 ; Your code should look like the above πŸ‘† What we did there is: we made an arrow function inchToCM which takes in one parameter, inches modified the function to implicitly return the value. The way we can tell this is an implicit return is that: it's all on one line there is no return keyword there are no curly brackets If you refresh the browser, you will see that it still works. To recap: what we did there is we removed the function block, modified the code to be on one line, and removed the explicit return. Finally, and this is more of a stylistic choice, if there is only ever one parameter for your function, you can actually get rid of the parenthesis around the parameter as well, like soπŸ‘‡ const inchToCM = inches => inches * 2 . 54 ; If there is only one parameter in your arrow function, you can remove them no problem. It is still a valid arrow function. Let's do another example! Make a function called add , that takes in two parameters a and b , with the default value of b being 3. We will then make a temporary variable called total which we return. function add ( a, b = 3 ) { const total = a + b; return total; } Pause here, try to convert it to an arrow function yourself and then come back once you have tried it. Let's first see if it works as it originally was. Save the code from above πŸ‘† and refresh index.html in the browser. Open the console and test the function. You might notice that dev tools is giving us an annotation ?b in Ζ’(a,?b) as shown above. That little question mark in front of b is telling us that the argument is optional. b is optional because there is a default value to fall back on. Stick the function in a variable add and remove the function name, like so πŸ‘‡ const add => function ( a, b = 3 ) {} Next, convert it to an arrow function. Get rid of the keyword function and add a fat arrow to the right of the parenthesis, as shown below. const add = ( a, b = 3 ) => { const total = a + b; return total; }; Modify the code to return a + b and get rid of the total variable. πŸ‘‡ const add = ( a, b = 3 ) => { return a + b; }; Put the function on one line. const add = ( a,b = 3 ) => { return a + b; } Get rid of the function block and the return keyword like so πŸ‘‡ const add = ( a, b = 3 ) => a + b; Now we have a short arrow function! You may have noticed that we did not get rid of the parentheses, and that is because there is more than one parameter. Arrow Function Gotcha's There are a couple of other gotchas with arrow functions that we need to know about. Let's go over them now. Returning an object Let's make a function makeABaby() , which will accept a first and last name for the baby. Inside of the function, create an object baby with a name and age property. πŸ‘‡ function makeABaby ( first, last ) { const baby = { name : ` ${ first } ${ last } ` , age : 0 , }; return baby; } It works! How could you convert this to an arrow function? Stick it in a variable and convert it to an arrow function like so πŸ‘‡ const makeABaby = ( first, last ) => { const baby = { name : ` ${ first } ${ last } ` , age : 0 , }; return baby; }; If your function needs to do some stuff inside of the block, you can leave it as is. This is a perfectly valid arrow function. If the only thing you're using the arrow for is the ability to type less as well as some of the benefits of not scoping this, this is totally valid. However, we can take it a bit further. Instead of declaring the baby variable, we will just return the object directly. πŸ‘‡ const makeABaby = ( first, last ) => { return { name : ` ${ first } ${ last } ` , age : 0 , }; }; Now the question is... how would we do the implicit return? We can put it on one line, no problem (objects can be put on one line) . But how would we return it? Let's try it the way we know. Put it on one line. const makeABaby = ( first, last ) => { return { name : ` ${ first } ${ last } ` , age : 0 }; }; To make it an implicit return, get rid of the curly brackets and the return keyword. πŸ‘‡ const makeABaby = ( first, last ) => { name : ` ${ first } ${ last } ` , age : 0 }; However, you will see the above πŸ‘† error if you try to run the code like that. What's happening there is it thinks that the curly bracket from the baby object is actually the curly bracket from the block of the function. Curly brackets in JavaScript can be the creation of an object, or a block of code. What are your options to implicitly return an object then? If you want to implicitly return an object in JavaScript, you just pop a set of parentheses around the thing that you are returning and then the code will know that it's not the block to the function. Try it by modifying your code like so πŸ‘‡ const makeABaby = ( first, last ) => ({ name : ` ${ first } ${ last } ` , age : 0 }); If you try it in the code, it still works. Now... is there a benefit of having the function this way or how we did it originally? Wes doesn't think so. You're not really getting much benefit, in fact the way we had it originally was a bit more readable. There is nothing wrong with doing a regular function, because you want to think about your future self. Let's say you come back to the code in 6 months, what will be easier for you to read? Don't always go to making an arrow function by default, and hopefully throughout this course it will become more clear when you should reach for an arrow function (specifically with arrays and doing maps, reduce and filters). IIFE The next way to create a function is using an IIFE (pronounced iffy ). That is an immediately invoked function expression . We will do an example to demonstrate what an IIFE is. Comment out all the other JavaScript code, add the code below and then refresh index.html . πŸ‘‡ function () { console. log ( ' Running the Anon function ' ); return `You are cool` ; } Nothing happens when you refresh index.html because it's not allowed to run. We talked about how you can stick a function in a variable and that is okay. Another way to run this function is what is called an immediately invoked functional expression. What you can do is wrap that function in a parentheses, (parentheses always run first in JavaScript) , and what that will do is return a function value and you can immediately run that function by putting parentheses on the end like so πŸ‘‡ ( function () { console. log ( " Running the Anon function " ); return `Your are cool` ; })(); Now, if you refresh the page, you will see the log in the console which means our function expression was immediately invoked. It was immediately run. What is the benefit of doing something like that? It used to be very popular before we had modules and block scope. When we get into scoping, you will learn that a function declares its own scope, and it's often handy to even declare functions of them, and it will provide us a sheltered space where the variables can't leak inside. We will go over that later in the course. For now, just know that it's an immediately invoked function. One last thing is what if the function took an age? You would pass it like so πŸ‘‡ ( function ( age ) { console. log ( " Running the Anon function " ); return `Your are cool and ${ age } ` ; })(age); That isn't something you will be using that often, but it does come up when you need to create something like a closure (which will be explained in future video). Methods The next type of functions we will learn about are referred to as methods . A method is simply a function that lives inside of an object. (Wes has so far sort of been saying that methods and functions are the same thing and we have a video coming up that focused entirely on creating your own methods that will make that clearer). So far Wes has been telling us that console.log() is a function. If we take a look at the function console.log in the browser, we will see that he has been lying to us. log() is actually the function that lives inside of console , and console is actually an object. If you type console into the console and expand it, you will see that there are all kinds of things within it. πŸ‘‡ Scroll down to log, and the little Ζ’ you see means that it's actually a function πŸ‘‰ So console is the object and log() , count() or any of the other functions listed under the console object are the functions. We have a special word to describe functions that live inside of an object and we call those methods . So you can actually do something like this.. πŸ‘‡ const wes = { name : " Wes Bos " , sayHi : function () { console. log ( " Hey wes! " ); return " Hey Wes! " ; }, }; Try it in the browser. First, type wes and hit Enter. Next, type wes.sayHi() and hit Enter. You should see the following πŸ‘‡ wes.sayHi() is a method . You make it a property on your object and you set it to a function. Those functions can also have names, for example sometimes you will see something like this πŸ‘‡ const wes = { name : " Wes Bos " , sayHi : function sayHi () { console. log ( " Hey wes! " ); return " Hey Wes! " ; }, }; Wes doesn't see the point of doing that, but it is technically allowed. There is also a new shorthand method. πŸ‘‡ const wes = { name : " Wes Bos " , // Method! sayHi : function sayHi () { console. log ( " Hey Wes! " ); return " Hey Wes! " ; }, //Short hand Method yellHi () { console. log ( " HEY WESSSSS " ); }, }; If you refresh the browser and type wes.yellHi() , it will work. What we did here is instead of writing sayHi: function() (which does work) , we can get rid of the function keyword and the : . That makes it into a property, yellHi() , which is set to the function yellHi . It's just a shorthand way to write methods inside of an object. There is another way, which is an arrow function. πŸ‘‡ const wes = { name : ' Wes Bos ' , // Method! sayHi : function sayHi () { console. log ( ' Hey Wes! ' ); return ' Hey Wes! ' ; }, // Short hand Method yellHi () { console. log ( ' HEY WESSSSS ' ); }, // Arrow function whisperHi : () => { console. log ( ' hiii wess im a mouse ' ); } }; whisperHi() is an arrow function that doesn't take any arguments, but it could take in arguments if you wanted. Those are 3 different ways to do methods and the shorthand is the most common way. Preview of this The only reason you would do an arrow function is because you don't want to access this . We will go over that in detail when we get to objects but really quickly Wes will show us. Modify the sayHi() method to add console.log(this); and run it in the browser πŸ‘‡ sayHi : function sayHi () { console. log ( this ); You will see that on the line in our code that we logged, like 50 , the value of this has been returned. (( this )) is equal to the object that it was called against. That is cool because you could actually do something like this πŸ‘‡ const wes = { name : ' Westopher Bos ' , // Method! sayHi : function sayHi () { console. log ( `Hey ${ this .name } ` ); console. log ( ' Hey Wes! ' ); return ' Hey Wes! ' ; } You would see it immediately fills the value of the name property. πŸ‘‡ That will not work in an arrow function because they take the parent scope of this . We will explain that in the future. Callback Functions The final thing Wes wants to talk to us about is something called callback functions . So a callback function is just a regular function, but we use that name for something that will happen after something is done. The easiest way to define a callback function is either when someone clicks something, run this. Or when this amount of time has passed, run this. Let's look at both of those examples. Click Callback We will do a click callback. Go into index.html and add a button with a class of clickMe and text of "Click Me!" πŸ‘‡ <! DOCTYPE html > < html lang = " en " > < head > < meta charset = " UTF-8 " /> < meta name = " viewport " content = " width=device-width,initial-scale=1.0 " /> < title ></ title > < link rel = " stylesheet " href = " ../../base.css " /> </ head > < body > < button class = " clickMe " > Click Me! </ button > < script src = " ./ways-to-make-a-function.js " ></ script > </ body > </ html > Back in the JavaScript file, let's select the element like so πŸ‘‡ (we will cover the DOM in more depth later) const button = document. querySelector ( " .clickMe " ); console. log (button); Refresh the page and open the console to see that it works. Next, listen for a click on that button as shown below const button = document. querySelector ( " .clickMe " ); button. addEventListener ( " click " , wes.sayHi); When that click happens, we can pass it to any function that we want. in this case, we chose sayHi() from our wes object from a previous example. Now, every time you click it, it will say "HEY WESSSS" πŸ‘‡ What is happening there is that .addEventListener() is an event listener that we are listening for a click on, and the callback function is wes.sayHi() . It's a function that we give it access to. Notice that we are not running it there, we are just saying here is the function, when someone clicks the button, please call it. That is what is referred to as a callback function. Callback functions can be declared outside of the handler, like so πŸ‘‡ function handleClick () { console. log ( " Great clicking!! " ); } button. addEventListener ( " click " , handleClick); That tells the browser that when the element with a class of .clickMe is pressed, run the handleClick function. The other option, which is half as common, is to define the function outside and then pass in the reference to the function. Another thing you can do is just pass it an anonymous function, as shown below. button. addEventListener ( " click " , function () { console. log ( " nice Job! " ); }); And it works just fine when you press it. What we have done there is we have passed it an anonymous function as a value directly, and the browser will know to call this function itself. (There are upsides and downsides of doing it that way which we will get into another time.) What you need to know is that a callback function is a function that gets passed into another function and then it is called by the browser at a later point in time. Timer Callback The other example we have is a timer callback. There are a couple of ways to do timers (we will go over all of them in the future) but the simplest is setTimeout() . setTimeout (); It takes two things: a function to call after a certain amount of time a duration in milliseconds (after how long should I run this) So let's do 1000 milliseconds which is one second later. setTimeout (wes.yellHi, 1000 ); If we refresh the page, after one second, it will log HEY WES. You can also pass it an anonymous function. setTimeout ( function () { console. log ( " DONE TIME TO EAT " ); }, 1000 ); After a second that will log "DONE TIME TO EAT". You can pass those as arrow functions as well. setTimeout ( () => { console. log ( " DONE TIME TO EAT " ); }, 1000 ); That will work the same! 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
Markdown
[![Wes Bos](https://wesbos.com/assets/logo-BnGr5bbv.png)](https://wesbos.com/) - [Coursesfree + premium](https://wesbos.com/courses) - [Syntax podcast](https://syntax.fm/) - [Aboutme](https://wesbos.com/about) - [Blogit's good](https://wesbos.com/blog) - [TipsπŸ”₯ Real Hot](https://wesbos.com/tips) - [JavaScriptNotes](https://wesbos.com/javascript) - [Speaking and training IRL](https://wesbos.com/speaking-and-training) - [/uses Font?! Theme!?](https://wesbos.com/uses) - [Contactme](https://wesbos.com/contact) ##### Module 1 - The Basics - [WelcomePart 1](https://wesbos.com/javascript/01-the-basics/welcome) 1. [House Keeping](https://wesbos.com/javascript/01-the-basics/welcome#house-keeping) - [Starter Files](https://wesbos.com/javascript/01-the-basics/welcome#starter-files) - [Slack Channel](https://wesbos.com/javascript/01-the-basics/welcome#slack-channel) - [Structure of Starter files](https://wesbos.com/javascript/01-the-basics/welcome#structure-of-starter-files) - [How to Do the Course](https://wesbos.com/javascript/01-the-basics/welcome#how-to-do-the-course) - [Browser, Editor and Terminal SetupPart 2](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup) 1. [The browser](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#the-browser) - [Shortcuts](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#shortcuts) 2. [Node.js](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#nodejs) - [Checking if Node.js is installed](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#checking-if-nodejs-is-installed) - [Which Terminal to Use](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#which-terminal-to-use) - [Checking if you have npm installed](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#checking-if-you-have-npm-installed) 3. [Command Line Basics](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#command-line-basics) 4. [Check that Node.js is working](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#check-that-nodejs-is-working) 5. [Code Editor](https://wesbos.com/javascript/01-the-basics/browser-editor-and-terminal-setup#code-editor) - [Running and Loading JavaScriptPart 3](https://wesbos.com/javascript/01-the-basics/running-and-loading-js) 1. [Run scripts before closing body tag](https://wesbos.com/javascript/01-the-basics/running-and-loading-js#run-scripts-before-closing-body-tag) 2. [External JavaScript Files](https://wesbos.com/javascript/01-the-basics/running-and-loading-js#external-javascript-files) 3. [Running it in Node.js](https://wesbos.com/javascript/01-the-basics/running-and-loading-js#running-it-in-nodejs) - [Variables and StatementsPart 4](https://wesbos.com/javascript/01-the-basics/variables-and-statements) 1. [var](https://wesbos.com/javascript/01-the-basics/variables-and-statements#var) 2. [let](https://wesbos.com/javascript/01-the-basics/variables-and-statements#let) 3. [const](https://wesbos.com/javascript/01-the-basics/variables-and-statements#const) 4. [Statements and Semi-Colons in JavaScript](https://wesbos.com/javascript/01-the-basics/variables-and-statements#statements-and-semi-colons-in-javascript) 5. [Code Blocks](https://wesbos.com/javascript/01-the-basics/variables-and-statements#code-blocks) 6. [Differences between var, let & const](https://wesbos.com/javascript/01-the-basics/variables-and-statements#differences-between-var-let--const) - [Strict Mode](https://wesbos.com/javascript/01-the-basics/variables-and-statements#strict-mode) - [Scoping](https://wesbos.com/javascript/01-the-basics/variables-and-statements#scoping) 7. [Naming Conventions](https://wesbos.com/javascript/01-the-basics/variables-and-statements#naming-conventions) - [Camel Casing](https://wesbos.com/javascript/01-the-basics/variables-and-statements#camel-casing) - [Snake Case](https://wesbos.com/javascript/01-the-basics/variables-and-statements#snake-case) - [Kebab Case - Not Allowed](https://wesbos.com/javascript/01-the-basics/variables-and-statements#kebab-case---not-allowed) - [Code Quality Tooling with Prettier and ESLintPart 5](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint) 1. [ESLint & Prettier](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint#eslint--prettier) - [ESLint](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint#eslint) - [Prettier](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint#prettier) 2. [Installing ESLint & Prettier](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint#installing-eslint--prettier) 3. [Installing npm packages locally](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint#installing-npm-packages-locally) 4. [Creating the package.json file](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint#creating-the-packagejson-file) 5. [Configuring ESLint and Prettier with VS Code](https://wesbos.com/javascript/01-the-basics/code-quality-tooling-with-prettier-and-eslint#configuring-eslint-and-prettier-with-vs-code) - [Types - IntroductionPart 6](https://wesbos.com/javascript/01-the-basics/types-introduction) - [Types - StringsPart 7](https://wesbos.com/javascript/01-the-basics/types-strings) 1. [JavaScript Comments](https://wesbos.com/javascript/01-the-basics/types-strings#javascript-comments) 2. [Difference between Single Quotes, Double Quotes and Backticks](https://wesbos.com/javascript/01-the-basics/types-strings#difference-between-single-quotes-double-quotes-and-backticks) - [Putting String on Multiple Lines](https://wesbos.com/javascript/01-the-basics/types-strings#putting-string-on-multiple-lines) 3. [Concatenation and Interpolation](https://wesbos.com/javascript/01-the-basics/types-strings#concatenation-and-interpolation) 4. [Backticks](https://wesbos.com/javascript/01-the-basics/types-strings#backticks) - [Types - NumbersPart 8](https://wesbos.com/javascript/01-the-basics/types-numbers) 1. [Numbers in JavaScript](https://wesbos.com/javascript/01-the-basics/types-numbers#numbers-in-javascript) 2. [Helper Methods](https://wesbos.com/javascript/01-the-basics/types-numbers#helper-methods) 3. [Modulo and Power Operators](https://wesbos.com/javascript/01-the-basics/types-numbers#modulo-and-power-operators) 4. [Things to know about Math in JavaScript](https://wesbos.com/javascript/01-the-basics/types-numbers#things-to-know-about-math-in-javascript) - [Infinity and Negative Infinity](https://wesbos.com/javascript/01-the-basics/types-numbers#infinity-and-negative-infinity) - [Not a Number](https://wesbos.com/javascript/01-the-basics/types-numbers#not-a-number) - [Types - ObjectsPart 9](https://wesbos.com/javascript/01-the-basics/types-objects) - [Types - Null and UndefinedPart 10](https://wesbos.com/javascript/01-the-basics/types-null-and-undefined) 1. [undefined](https://wesbos.com/javascript/01-the-basics/types-null-and-undefined#undefined) 2. [null](https://wesbos.com/javascript/01-the-basics/types-null-and-undefined#null) - [Types - Booleans and EqualityPart 11](https://wesbos.com/javascript/01-the-basics/types-booleans-and-equality) 1. [Equality (equal sign, double equal sign, triple equal sign)](https://wesbos.com/javascript/01-the-basics/types-booleans-and-equality#equality-equal-sign-double-equal-sign-triple-equal-sign) ##### Module 2 - Functions - [Functions - Built-inPart 12](https://wesbos.com/javascript/02-functions/functions-built-in) 1. [Built-in Functions](https://wesbos.com/javascript/02-functions/functions-built-in#built-in-functions) - [Example \#1 πŸ‘‡](https://wesbos.com/javascript/02-functions/functions-built-in#example-1-) - [Example \#2 πŸ‘‡](https://wesbos.com/javascript/02-functions/functions-built-in#example-2-) - [Functions - CustomPart 13](https://wesbos.com/javascript/02-functions/functions-custom) 1. [Defining a Function](https://wesbos.com/javascript/02-functions/functions-custom#defining-a-function) 2. [Returning Values](https://wesbos.com/javascript/02-functions/functions-custom#returning-values) 3. [Storing a Value Returned from A Function](https://wesbos.com/javascript/02-functions/functions-custom#storing-a-value-returned-from-a-function) - [Functions - Parameters and ArgumentsPart 14](https://wesbos.com/javascript/02-functions/functions-parameters-and-arguments) 1. [Another Example](https://wesbos.com/javascript/02-functions/functions-parameters-and-arguments#another-example) 2. [Even More Examples](https://wesbos.com/javascript/02-functions/functions-parameters-and-arguments#even-more-examples) 3. [How to Fall Back on Default for Only One Parameter](https://wesbos.com/javascript/02-functions/functions-parameters-and-arguments#how-to-fall-back-on-default-for-only-one-parameter) - [Different Ways to Declare FunctionsPart 15](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions) 1. [Anonymous Functions](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#anonymous-functions) 2. [Function Expressions](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#function-expressions) - [What is the difference between a function declaration and a function expression?](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#what-is-the-difference-between-a-function-declaration-and-a-function-expression) 3. [Hoisting](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#hoisting) 4. [Arrow Functions](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#arrow-functions) - [Different Ways to Write Arrow Functions](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#different-ways-to-write-arrow-functions) - [Implicit and Explicit Returns](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#implicit-and-explicit-returns) - [Arrow Function Gotcha's](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#arrow-function-gotchas) - [Returning an object](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#returning-an-object) 5. [IIFE](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#iife) 6. [Methods](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#methods) 7. [Preview of this](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#preview-of-this) 8. [Callback Functions](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#callback-functions) - [Click Callback](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#click-callback) - [Timer Callback](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions#timer-callback) - [Debugging ToolsPart 16](https://wesbos.com/javascript/02-functions/debugging-tools) 1. [Console Debugging](https://wesbos.com/javascript/02-functions/debugging-tools#console-debugging) 2. [The Call Stack and Stack Trace](https://wesbos.com/javascript/02-functions/debugging-tools#the-call-stack-and-stack-trace) 3. [Grabbing Elements](https://wesbos.com/javascript/02-functions/debugging-tools#grabbing-elements) 4. [Breakpoints](https://wesbos.com/javascript/02-functions/debugging-tools#breakpoints) 5. [Network Request](https://wesbos.com/javascript/02-functions/debugging-tools#network-request) 6. [Break On Attribute](https://wesbos.com/javascript/02-functions/debugging-tools#break-on-attribute) ##### Module 3 - The Tricky Bits - [ScopePart 17](https://wesbos.com/javascript/03-the-tricky-bits/scope) 1. [Global Variables](https://wesbos.com/javascript/03-the-tricky-bits/scope#global-variables) 2. [Function Scoping](https://wesbos.com/javascript/03-the-tricky-bits/scope#function-scoping) 3. [Block Scoping](https://wesbos.com/javascript/03-the-tricky-bits/scope#block-scoping) 4. [Lexical and Static Scoping](https://wesbos.com/javascript/03-the-tricky-bits/scope#lexical-and-static-scoping) - [HoistingPart 18](https://wesbos.com/javascript/03-the-tricky-bits/hoisting) 1. [Hoisting Function Declarations](https://wesbos.com/javascript/03-the-tricky-bits/hoisting#hoisting-function-declarations) 2. [Variable Hoisting](https://wesbos.com/javascript/03-the-tricky-bits/hoisting#variable-hoisting) - [ClosuresPart 19](https://wesbos.com/javascript/03-the-tricky-bits/closures) 1. [Examples of Closures](https://wesbos.com/javascript/03-the-tricky-bits/closures#examples-of-closures) 2. [Private Variables](https://wesbos.com/javascript/03-the-tricky-bits/closures#private-variables) ##### Module 4 - The DOM - [Introduction to the DOMPart 20](https://wesbos.com/javascript/04-the-dom/introduction-to-the-dom) 1. [Window Object Refresher](https://wesbos.com/javascript/04-the-dom/introduction-to-the-dom#window-object-refresher) - [The Document Object Introduction](https://wesbos.com/javascript/04-the-dom/introduction-to-the-dom#the-document-object-introduction) 2. [The Navigator Object](https://wesbos.com/javascript/04-the-dom/introduction-to-the-dom#the-navigator-object) - [Selecting ElementsPart 21](https://wesbos.com/javascript/04-the-dom/selecting-elements) 1. [Setup](https://wesbos.com/javascript/04-the-dom/selecting-elements#setup) - [Where to Load JavaScript When Selecting Elements](https://wesbos.com/javascript/04-the-dom/selecting-elements#where-to-load-javascript-when-selecting-elements) 2. [Selecting DOM Elements](https://wesbos.com/javascript/04-the-dom/selecting-elements#selecting-dom-elements) - [Searching Inside Already Selected Elements](https://wesbos.com/javascript/04-the-dom/selecting-elements#searching-inside-already-selected-elements) - [Element Properties and MethodsPart 22](https://wesbos.com/javascript/04-the-dom/element-properties-and-methods) 1. [Getters and Setters](https://wesbos.com/javascript/04-the-dom/element-properties-and-methods#getters-and-setters) - [textContent and innerText](https://wesbos.com/javascript/04-the-dom/element-properties-and-methods#textcontent-and-innertext) 2. [Exercise](https://wesbos.com/javascript/04-the-dom/element-properties-and-methods#exercise) 3. [insertAdjacentText and insertAdjacentElement](https://wesbos.com/javascript/04-the-dom/element-properties-and-methods#insertadjacenttext-and-insertadjacentelement) - [Working with ClassesPart 23](https://wesbos.com/javascript/04-the-dom/working-with-classes) 1. [Adding a class](https://wesbos.com/javascript/04-the-dom/working-with-classes#adding-a-class) 2. [Removing a class](https://wesbos.com/javascript/04-the-dom/working-with-classes#removing-a-class) 3. [Toggling a class](https://wesbos.com/javascript/04-the-dom/working-with-classes#toggling-a-class) 4. [The contains method](https://wesbos.com/javascript/04-the-dom/working-with-classes#the-contains-method) - [Built-in and Custom Data AttributesPart 24](https://wesbos.com/javascript/04-the-dom/built-in-and-custom-data-attributes) 1. [Data Attributes](https://wesbos.com/javascript/04-the-dom/built-in-and-custom-data-attributes#data-attributes) - [Creating HTMLPart 25](https://wesbos.com/javascript/04-the-dom/creating-html) 1. [append method](https://wesbos.com/javascript/04-the-dom/creating-html#append-method) 2. [insertAdjacentElement method](https://wesbos.com/javascript/04-the-dom/creating-html#insertadjacentelement-method) 3. [Generating An Unordered List](https://wesbos.com/javascript/04-the-dom/creating-html#generating-an-unordered-list) - [HTML from Strings and XSSPart 26](https://wesbos.com/javascript/04-the-dom/html-from-strings-and-xss) 1. [document.createRange() and document.createFragment()](https://wesbos.com/javascript/04-the-dom/html-from-strings-and-xss#documentcreaterange-and-documentcreatefragment) 2. [Security and Sanitization](https://wesbos.com/javascript/04-the-dom/html-from-strings-and-xss#security-and-sanitization) 3. [XSS (Cross Site Scripting)](https://wesbos.com/javascript/04-the-dom/html-from-strings-and-xss#xss-cross-site-scripting) - [Traversing and Removing NodesPart 27](https://wesbos.com/javascript/04-the-dom/traversing-and-removing-nodes) 1. [The difference between a Node and an Element](https://wesbos.com/javascript/04-the-dom/traversing-and-removing-nodes#the-difference-between-a-node-and-an-element) 2. [Properties to work with Nodes and Elements](https://wesbos.com/javascript/04-the-dom/traversing-and-removing-nodes#properties-to-work-with-nodes-and-elements) 3. [Removing Elements](https://wesbos.com/javascript/04-the-dom/traversing-and-removing-nodes#removing-elements) - [CardioPart 28](https://wesbos.com/javascript/04-the-dom/cardio) 1. [closest method](https://wesbos.com/javascript/04-the-dom/cardio#closest-method) ##### Module 5 - Events - [Event ListenerPart 29](https://wesbos.com/javascript/05-events/event-listener) 1. [Removing an Event Listener](https://wesbos.com/javascript/05-events/event-listener#removing-an-event-listener) 2. [Listening to events on multiple elements](https://wesbos.com/javascript/05-events/event-listener#listening-to-events-on-multiple-elements) 3. [forEach method](https://wesbos.com/javascript/05-events/event-listener#foreach-method) - [Targets, Bubbling, Propagation and CapturePart 30](https://wesbos.com/javascript/05-events/targets-bubbling-propagation-and-capture) 1. [Propagation](https://wesbos.com/javascript/05-events/targets-bubbling-propagation-and-capture#propagation) 2. [this keyword](https://wesbos.com/javascript/05-events/targets-bubbling-propagation-and-capture#this-keyword) - [Prevent Default and Form EventsPart 31](https://wesbos.com/javascript/05-events/prevent-default-and-form-events) 1. [preventDefault method](https://wesbos.com/javascript/05-events/prevent-default-and-form-events#preventdefault-method) 2. [Other Types of Events with Form Inputs](https://wesbos.com/javascript/05-events/prevent-default-and-form-events#other-types-of-events-with-form-inputs) - [Accessibility Gotchas and Keyboard CodesPart 32](https://wesbos.com/javascript/05-events/accessibility-gotchas-and-keyboard-codes) 1. [Difference between Buttons and Links](https://wesbos.com/javascript/05-events/accessibility-gotchas-and-keyboard-codes#difference-between-buttons-and-links) 2. [Keyboard Accessibility](https://wesbos.com/javascript/05-events/accessibility-gotchas-and-keyboard-codes#keyboard-accessibility) ##### Module 6 - Serious Practice Exercises - [Etch-a-SketchPart 33](https://wesbos.com/javascript/06-serious-practice-exercises/etch-a-sketch) 1. [Shaking / Clearing the Canvas](https://wesbos.com/javascript/06-serious-practice-exercises/etch-a-sketch#shaking--clearing-the-canvas) 2. [Event listener "once" option](https://wesbos.com/javascript/06-serious-practice-exercises/etch-a-sketch#event-listener-once-option) - [Click Outside ModalPart 34](https://wesbos.com/javascript/06-serious-practice-exercises/click-outside-modal) 1. [closest method](https://wesbos.com/javascript/06-serious-practice-exercises/click-outside-modal#closest-method) - [Scroll Events and Intersection ObserverPart 35](https://wesbos.com/javascript/06-serious-practice-exercises/scroll-events-and-intersection-observer) 1. [Intersection Observer](https://wesbos.com/javascript/06-serious-practice-exercises/scroll-events-and-intersection-observer#intersection-observer) - [TabsPart 36](https://wesbos.com/javascript/06-serious-practice-exercises/tabs) 1. [Converting a NodeList to an Array](https://wesbos.com/javascript/06-serious-practice-exercises/tabs#converting-a-nodelist-to-an-array) ##### Module 7 - Logic and Flow Control - [BEDMASPart 37](https://wesbos.com/javascript/07-logic-and-flow-control/bedmas) - [If Statements, Function Returns, Truthy and FalsyPart 38](https://wesbos.com/javascript/07-logic-and-flow-control/if-statements-function-returns-truthy-falsy) 1. [Operators](https://wesbos.com/javascript/07-logic-and-flow-control/if-statements-function-returns-truthy-falsy#operators) 2. [Truthy or Falsy](https://wesbos.com/javascript/07-logic-and-flow-control/if-statements-function-returns-truthy-falsy#truthy-or-falsy) - [Truthy or Falsy values](https://wesbos.com/javascript/07-logic-and-flow-control/if-statements-function-returns-truthy-falsy#truthy-or-falsy-values) - [Coercion, Ternaries and Conditional AbusePart 39](https://wesbos.com/javascript/07-logic-and-flow-control/coercion-ternaries-and-conditional-abuse) 1. [Ternary](https://wesbos.com/javascript/07-logic-and-flow-control/coercion-ternaries-and-conditional-abuse#ternary) 2. [Blockless If Statements](https://wesbos.com/javascript/07-logic-and-flow-control/coercion-ternaries-and-conditional-abuse#blockless-if-statements) - [Case Switch and Animating a Turtle with CSS VariablesPart 40](https://wesbos.com/javascript/07-logic-and-flow-control/case-switch-and-animating-a-turtle-with-css-variables) - [Intervals and TimersPart 41](https://wesbos.com/javascript/07-logic-and-flow-control/intervals-and-timers) 1. [Intervals](https://wesbos.com/javascript/07-logic-and-flow-control/intervals-and-timers#intervals) 2. [Clearing Timeouts and Intervals](https://wesbos.com/javascript/07-logic-and-flow-control/intervals-and-timers#clearing-timeouts-and-intervals) ##### Module 8 - Data Types - [ObjectsPart 42](https://wesbos.com/javascript/08-data-types/objects) 1. [Creating an Object](https://wesbos.com/javascript/08-data-types/objects#creating-an-object) - [Accessing Properties](https://wesbos.com/javascript/08-data-types/objects#accessing-properties) - [Deleting a Property from an Object](https://wesbos.com/javascript/08-data-types/objects#deleting-a-property-from-an-object) - [Methods](https://wesbos.com/javascript/08-data-types/objects#methods) - [Object References vs ValuesPart 43](https://wesbos.com/javascript/08-data-types/object-references-vs-values) 1. [Spread Operator](https://wesbos.com/javascript/08-data-types/object-references-vs-values#spread-operator) 2. [Lodash](https://wesbos.com/javascript/08-data-types/object-references-vs-values#lodash) - [MapsPart 44](https://wesbos.com/javascript/08-data-types/maps) 1. [Set](https://wesbos.com/javascript/08-data-types/maps#set) - [JSON](https://wesbos.com/javascript/08-data-types/maps#json) - [ArraysPart 45](https://wesbos.com/javascript/08-data-types/arrays) 1. [Array Methods](https://wesbos.com/javascript/08-data-types/arrays#array-methods) - [Array Cardio - Static MethodsPart 46](https://wesbos.com/javascript/08-data-types/46-array-cardio-static-methods) 1. [Object Static Methods](https://wesbos.com/javascript/08-data-types/46-array-cardio-static-methods#object-static-methods) - [Array Cardio - Instance MethodsPart 47](https://wesbos.com/javascript/08-data-types/47-array-cardio-instance-methods) 1. [join method](https://wesbos.com/javascript/08-data-types/47-array-cardio-instance-methods#join-method) 2. [split method](https://wesbos.com/javascript/08-data-types/47-array-cardio-instance-methods#split-method) 3. [pop method](https://wesbos.com/javascript/08-data-types/47-array-cardio-instance-methods#pop-method) 4. [shift and unshift methods](https://wesbos.com/javascript/08-data-types/47-array-cardio-instance-methods#shift-and-unshift-methods) - [Array Cardio - Callback Methods and Function GenerationPart 48](https://wesbos.com/javascript/08-data-types/48-array-cardio-callback-methods-and-function-generation) ##### Module 9 - Loops - [Looping and Iterating - Array forEachPart 49](https://wesbos.com/javascript/09-gettin-loopy/49-looping-and-iterating-array-foreach) - [Looping and Iterating - MappingPart 50](https://wesbos.com/javascript/09-gettin-loopy/50-looping-and-iterating-mapping) - [Looping and Iterating - Filter, Find and Higher-Order FunctionsPart 51](https://wesbos.com/javascript/09-gettin-loopy/51-looping-and-iterating-filter-find-and-higher-order-functions) - [Looping and Iterating - ReducePart 52](https://wesbos.com/javascript/09-gettin-loopy/52-looping-and-iterating-reduce) - [Looping and Iterating - Reduce ExercisePart 53](https://wesbos.com/javascript/09-gettin-loopy/53-looping-and-iterating-reduce-exercise) 1. [Regular Expression](https://wesbos.com/javascript/09-gettin-loopy/53-looping-and-iterating-reduce-exercise#regular-expression) - [Looping and Iterating - for, for in, for of, and while LoopsPart 54](https://wesbos.com/javascript/09-gettin-loopy/54-looping-and-iterating-for-for-in-for-off-and-while-loops) 1. [The for loop](https://wesbos.com/javascript/09-gettin-loopy/54-looping-and-iterating-for-for-in-for-off-and-while-loops#the-for-loop) 2. [for of Loop](https://wesbos.com/javascript/09-gettin-loopy/54-looping-and-iterating-for-for-in-for-off-and-while-loops#for-of-loop) 3. [for in loop](https://wesbos.com/javascript/09-gettin-loopy/54-looping-and-iterating-for-for-in-for-off-and-while-loops#for-in-loop) 4. [while and do while loops](https://wesbos.com/javascript/09-gettin-loopy/54-looping-and-iterating-for-for-in-for-off-and-while-loops#while-and-do-while-loops) ##### Module 10 - Harder Practice Exercises - [Face Detection and CensorshipPart 55](https://wesbos.com/javascript/10-harder-practice-exercises/55-face-detection-and-censorship) - [Sarcastic Text GeneratorPart 56](https://wesbos.com/javascript/10-harder-practice-exercises/56-sarcastic-text-generator) 1. [The modulo operator](https://wesbos.com/javascript/10-harder-practice-exercises/56-sarcastic-text-generator#the-modulo-operator) - [Shopping Form with Custom Events, Delegation and LocalstoragePart 57](https://wesbos.com/javascript/10-harder-practice-exercises/57-shopping-form-with-custom-events-delegation-and-localstorage) 1. [LocalStorage](https://wesbos.com/javascript/10-harder-practice-exercises/57-shopping-form-with-custom-events-delegation-and-localstorage#localstorage) 2. [Event Delegation](https://wesbos.com/javascript/10-harder-practice-exercises/57-shopping-form-with-custom-events-delegation-and-localstorage#event-delegation) - [Building a GalleryPart 58](https://wesbos.com/javascript/10-harder-practice-exercises/58-building-a-gallery) 1. [Closures](https://wesbos.com/javascript/10-harder-practice-exercises/58-building-a-gallery#closures) 2. [Tab-Index](https://wesbos.com/javascript/10-harder-practice-exercises/58-building-a-gallery#tab-index) - [Building a SliderPart 59](https://wesbos.com/javascript/10-harder-practice-exercises/59-building-a-slider) ##### Module 11 - Prototypes, this, new and Inheritance - [The New KeywordPart 60](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/60-the-new-keyword) - [The This KeywordPart 61](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/61-the-this-keyword) - [Prototype Refactor of Gallery ExercisePart 62](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/62-prototype-refactor-of-gallery-exercise) 1. [bind method](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/62-prototype-refactor-of-gallery-exercise#bind-method) - [Prototypes and Prototypal InheritancePart 63](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/63-prototypes-and-prototypal-inheritance) - [Prototype Refactor of the Slider ExercisePart 64](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/64-prototype-refactor-of-the-slider-exercise) - [Bind, Call and ApplyPart 65](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/65-bind-call-and-apply) 1. [Bind method](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/65-bind-call-and-apply#bind-method) 2. [Call and Apply methods](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/65-bind-call-and-apply#call-and-apply-methods) - [Call method](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/65-bind-call-and-apply#call-method) - [Apply method](https://wesbos.com/javascript/11-prototypes-this-new-and-inheritance/65-bind-call-and-apply#apply-method) ##### Module 12 - Advanced Flow Control - [The Event Loop and Callback HellPart 66](https://wesbos.com/javascript/12-advanced-flow-control/66-the-event-loop-and-callback-hell) - [PromisesPart 67](https://wesbos.com/javascript/12-advanced-flow-control/67-promises) 1. [.then() method](https://wesbos.com/javascript/12-advanced-flow-control/67-promises#then-method) 2. [Promise.all()](https://wesbos.com/javascript/12-advanced-flow-control/67-promises#promiseall) 3. [Promise.race()](https://wesbos.com/javascript/12-advanced-flow-control/67-promises#promiserace) - [Promises - Error HandlingPart 68](https://wesbos.com/javascript/12-advanced-flow-control/68-promises-error-handling) 1. [Promise.allSettled()](https://wesbos.com/javascript/12-advanced-flow-control/68-promises-error-handling#promiseallsettled) - [Refactoring Callback Hell to Promise LandPart 69](https://wesbos.com/javascript/12-advanced-flow-control/69-refactoring-callback-hell-to-promise-land) - [Async/AwaitPart 70](https://wesbos.com/javascript/12-advanced-flow-control/70-async-await) - [Async/Await Error HandlingPart 71](https://wesbos.com/javascript/12-advanced-flow-control/71-async-await-error-handling) 1. [Handling Errors with Higher Order Functions](https://wesbos.com/javascript/12-advanced-flow-control/71-async-await-error-handling#handling-errors-with-higher-order-functions) - [Async/Await Prompt UIPart 72](https://wesbos.com/javascript/12-advanced-flow-control/72-async-await-prompt-ui) 1. [Running an Event Listener Only Once](https://wesbos.com/javascript/12-advanced-flow-control/72-async-await-prompt-ui#running-an-event-listener-only-once) - [Async Typer UI - Two WaysPart 73](https://wesbos.com/javascript/12-advanced-flow-control/73-async-typer-ui-two-ways) ##### Module 13 - Ajax and Fetching Data - [AJAX and APIsPart 74](https://wesbos.com/javascript/13-ajax-and-fetching-data/74-ajax-and-apis) 1. [What is an API?](https://wesbos.com/javascript/13-ajax-and-fetching-data/74-ajax-and-apis#what-is-an-api) 2. [JSON](https://wesbos.com/javascript/13-ajax-and-fetching-data/74-ajax-and-apis#json) 3. [AJAX](https://wesbos.com/javascript/13-ajax-and-fetching-data/74-ajax-and-apis#ajax) 4. [Public API list](https://wesbos.com/javascript/13-ajax-and-fetching-data/74-ajax-and-apis#public-api-list) - [CORS and RecipesPart 75](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes) 1. [Query Parameters](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes#query-parameters) 2. [CORS](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes#cors) - [What is CORS?](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes#what-is-cors) - [CORS policy](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes#cors-policy) 3. [Babel](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes#babel) 4. [Browserlist](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes#browserlist) 5. [Proxy](https://wesbos.com/javascript/13-ajax-and-fetching-data/75-cors-and-recipes#proxy) - [Dad JokesPart 76](https://wesbos.com/javascript/13-ajax-and-fetching-data/76-dad-jokes) 1. [Headers](https://wesbos.com/javascript/13-ajax-and-fetching-data/76-dad-jokes#headers) 2. [Getting a Random Index](https://wesbos.com/javascript/13-ajax-and-fetching-data/76-dad-jokes#getting-a-random-index) 3. [Loading State & CSS Loader](https://wesbos.com/javascript/13-ajax-and-fetching-data/76-dad-jokes#loading-state--css-loader) - [Currency ConverterPart 77](https://wesbos.com/javascript/13-ajax-and-fetching-data/77-currency-converter) 1. [Caching the Rates](https://wesbos.com/javascript/13-ajax-and-fetching-data/77-currency-converter#caching-the-rates) 2. [Converting](https://wesbos.com/javascript/13-ajax-and-fetching-data/77-currency-converter#converting) 3. [Hooking Up The UI](https://wesbos.com/javascript/13-ajax-and-fetching-data/77-currency-converter#hooking-up-the-ui) - [Input Event on a Form](https://wesbos.com/javascript/13-ajax-and-fetching-data/77-currency-converter#input-event-on-a-form) - [Wiring up Handlers](https://wesbos.com/javascript/13-ajax-and-fetching-data/77-currency-converter#wiring-up-handlers) - [Formatting Currency using Number Format API](https://wesbos.com/javascript/13-ajax-and-fetching-data/77-currency-converter#formatting-currency-using-number-format-api) ##### Module 14 - ES Modules and Structuring Larger Apps - [ModulesPart 78](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules) 1. [What are Modules?](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#what-are-modules) 2. [Use Cases](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#use-cases) - [Modules in the Browser](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#modules-in-the-browser) - [In the Past - Sharing JavaScript Code between Files](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#in-the-past---sharing-javascript-code-between-files) - [In the Present - Sharing JavaScript Code between Files](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#in-the-present---sharing-javascript-code-between-files) 3. [Setting up Server](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#setting-up-server) 4. [Importing and Exporting Modules](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#importing-and-exporting-modules) 5. [Things we need to know about Modules](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#things-we-need-to-know-about-modules) - [Scope](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#scope) - [Difference between Default and Named Exports](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#difference-between-default-and-named-exports) 6. [Renaming Modules](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#renaming-modules) 7. [More Ways to Import](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#more-ways-to-import) 8. [Loading JavaScript On Demand](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#loading-javascript-on-demand) - [async](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/78-modules#async) - [Currency Module RefactorPart 79](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/79-currency-module-refactor) 1. [Bootstrap / App Init Functions](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/79-currency-module-refactor#bootstrap--app-init-functions) - [Dad Jokes Modules RefactorPart 80](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/80-dad-jokes-modules-refactor) 1. [Refactoring into Modules](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/80-dad-jokes-modules-refactor#refactoring-into-modules) 2. [Fixing Refactoring Errors](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/80-dad-jokes-modules-refactor#fixing-refactoring-errors) 3. [Recap](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/80-dad-jokes-modules-refactor#recap) - [Bundling and Building with ParcelPart 81](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel) 1. [Benefits of Bundlers](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel#benefits-of-bundlers) - [Bundler Options / Alternatives](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel#bundler-options--alternatives) - [Using Parcel](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel#using-parcel) 2. [Dad Jokes Module](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel#dad-jokes-module) - [Installing Parcel](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel#installing-parcel) - [Adding an NPM Script to package.json](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel#adding-an-npm-script-to-packagejson) - [Building with Parcel](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/81-bundling-and-building-with-parcel#building-with-parcel) - [Using Open-Source npm packagesPart 82](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages) 1. [node-modules folder](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#node-modules-folder) 2. [Using Third Party Packages](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#using-third-party-packages) 3. [Third Party Node Modules](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#third-party-node-modules) - [waait npm package](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#waait-npm-package) - [faker npm package](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#faker-npm-package) 4. [CommonJS Syntax vs ECMA Script Modules import](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#commonjs-syntax-vs-ecma-script-modules-import) - [date-fns npm package](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#date-fns-npm-package) - [axios npm package](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#axios-npm-package) - [lodash npm package](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#lodash-npm-package) - [await-to-js](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/82-using-open-source-npm-packages#await-to-js) - [SecurityPart 83](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/83-security) 1. [JavaScript is public](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/83-security#javascript-is-public) 2. [XSS and Sanitizing your Inputs](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/83-security#xss-and-sanitizing-your-inputs) 3. [FarceBook](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/83-security#farcebook) - [Image Event Hijacking](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/83-security#image-event-hijacking) - [Sanitizing User Data with DOMPurify.](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/83-security#sanitizing-user-data-with-dompurify) - [HTTPS Origin](https://wesbos.com/javascript/14-es-modules-and-structuring-larger-apps/83-security#https-origin) ##### Module 15 - Final Round of Exercises - [Web Speech Colours GamePart 84](https://wesbos.com/javascript/15-final-round-of-exercise/84-web-speech-colours-game) 1. [Web Speech](https://wesbos.com/javascript/15-final-round-of-exercise/84-web-speech-colours-game#web-speech) 2. [Colour Layout](https://wesbos.com/javascript/15-final-round-of-exercise/84-web-speech-colours-game#colour-layout) - [Combining Speech and Words](https://wesbos.com/javascript/15-final-round-of-exercise/84-web-speech-colours-game#combining-speech-and-words) - [Audio VisualizationPart 85](https://wesbos.com/javascript/15-final-round-of-exercise/85-audio-visualization) 1. [Audio](https://wesbos.com/javascript/15-final-round-of-exercise/85-audio-visualization#audio) 2. [Time Data Visualization](https://wesbos.com/javascript/15-final-round-of-exercise/85-audio-visualization#time-data-visualization) - [Frequency Visualization](https://wesbos.com/javascript/15-final-round-of-exercise/85-audio-visualization#frequency-visualization) # Different Ways to Declare Functions ![Beginner JavaScript](https://images.wesbos.com/upload/w_700,q_auto,f_auto/v1621453897/wesbos.com/bjs.png) Enjoy these notes? Want to Slam Dunk JavaScript? These are notes based on my [Beginner JavaScript](https://beginnerjavascript.com/) 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](https://beginnerjavascript.com/) JavaScript, Functions [Edit Post](https://github.com/wesbos/wesbos/tree/master/src/content/javascript/02-functions/15-different-ways-to-declare-functions/15-different-ways-to-declare-functions.mdx) One thing you will hear often when getting into JavaScript is that functions are *"first-class citizens"*. JavaScript functions are values in themselves, and they can be stored in variables and passed into other functions. What *is* a **value** in JavaScript? We know that in the examples below πŸ‘‡ that `true` and `100` are values. ``` const age = 100; const cool = true; ``` Those are values that are numbers, or strings or booleans. What is cool about JavaScript is that functions can be: - passed into other functions. - stored in variables, - moved around like any other piece of data in JavaScript That is not true for every other programming language. Let's start by looking at how you can put a function into a variable, and then look at the different ways to declare functions. Create a new file `ways-to-make-a-function.js` in the `/custom-functions` directory. ``` <script src="./ways-to-make-a-function.js"></script> ``` Add a log of "it works!" and go back to the `index.html` file and change the path in the script source attribute as shown above πŸ‘† and refresh the browser to ensure it works. We already know one way to declare a function and that is using the function keyword, like so πŸ‘‡ ``` function doctorize(firstName) { return `Dr. ${firstName}`; } ``` ## Anonymous Functions Let's look at some other options we have when declaring functions, starting with an **anonymous function**, which is a function without a name. To make `doctorize` an anonymous function, you would modify it like this πŸ‘‡ ``` function(firstName) { return `Dr. ${firstName}`; } ``` However, that is not valid JavaScript. If you try running it in the console you will see an error that says πŸ‘‡ > SyntaxError: Function statements require a function name ![declare function without name throws error](https://wesbos.com/assets/function-requires-function-name-error-B1wi3Lk3.webp) Anonymous functions are only valid in some use cases, such as using them in **callbacks** (we will learn more about that later) as well as in an **IIFE (immediately invoked function expression)**. This example was not a valid use case. Why would you ever want an anonymous function? ## Function Expressions The next way we will cover to declare a function will help explain that, which is as a **function expression**. Add a comment above that function specifying that it is an anonymous function, then copy the function and comment it out. Paste the copied code below the commented-out function. The next way to declare a function is a **function expression**. A function expression is when you store a function as a value in a variable. πŸ‘‡ ``` // function expression const doctorize = function (firstName) { return `Dr. ${firstName}`; }; ``` In the code above πŸ‘†, we have taken the anonymous function and stuck it in a variable. If you refresh the page, you will see that in the console, we have `doctorize()` available to us, and we can call it like we did in previous videos. ![assigning function to a variable makes function as anonymous](https://wesbos.com/assets/assigning-function-to-a-variable-pfsPaEtJ.webp) Having the ability to store a function in a variable is what leads people to say functions are *"first-class citizens"*. You may come across developers who say to not use function expressions because they used to give unhelpful errors. Previously, anonymous function errors would just tell you that they occurred in an anonymous function, without giving you any clue where the error is happening. However, now the dev tool errors are better. Here is an example that demonstrates what they mean by that πŸ‘‡ ``` // function expression const doctorize = function (firstName) { doesntExist(); return `Dr. ${firstName}`; }; ``` ![does not exists function call error](https://wesbos.com/assets/does-not-exist-not-defined-error-in-console-MgqW5vXU.webp) In our case, it does now tell you it happens inside of doctorize on line 12. Although the function is technically an anonymous function without a name, the browsers will now infer the name of the function from the variable name and use that in the errors. ### What is the difference between a function declaration and a function expression? What is the difference between doing a function declaration and a function expression? Why would you want to use one over the other? ## Hoisting There is only one real difference which is how they operate in something called **hoisting**. We will go over this in detail in a future video but for now we will just quickly cover the concept. Duplicate the `doctorize` function and name it `doctorize2`, like πŸ‘‡ ``` const doctorize = function (firstName) { return `Dr. ${firstName}`; }; function doctorize2 (firstName) { return `Dr. ${firstName}`; } ``` Let's say right before the first `doctorize` function, we called `doctorize` and passed it the value of "wes", as shown below πŸ‘‡, do you think the code will run? If you run a function before you define it, does it work? Refresh the page and look at the console to test it ``` doctorize("wes"); const doctorize = function (firstName) { return `Dr. ${firstName}`; }; function doctorize2 (firstName) { return `Dr. ${firstName}`; } ``` Did it work? Nope! You get an error like: > Uncaught ReferenceError: Cannot access 'doctorize' before initialization at ways-to-make-a-function.js:78 (anonymous) @ ways-to-make-a-function.js:78 What about `doctorize2`? ``` console.log(doctorize2("wes")); const doctorize = function (firstName) { return `Dr. ${firstName}`; }; function doctorize2 (firstName) { return `Dr. ${firstName}`; } ``` It does work\! Why does a function declaration work if you call it before you define it, but a function expression does not, especially when we created the exact same function in both cases? Functions that are declared with the **function** keyword are called **hoisted**. JavaScript will take all functions with the function keyword and hoist them up, up, up and says "you're a function, you belong at the top of the file". That means anywhere you call the function, it will be available to you. JavaScript does **not** hoist variable functions. When is that useful? Very rarely, Wes has never used that in his entire career except for tiny use cases. **Hoisting** is more of an interview question that you may be asked. Essentially it means that JavaScript will take functions and bring them up to the top of the code before they are called. This gives us the ability to run a function before it is defined. Remove the `doctorize2` function from the JavaScript file which should leave just the function expression. ## Arrow Functions The next way to make a function is using an **arrow function**. Arrow functions themselves have a few different ways of being declared. They are a newer addition to JavaScript, and were added in the last couple of years. They have a few benefits: - concise syntax and tend to be shorter - allow for writing one line functions - do not have their own scope in reference to the `this` keyword *(we will cover the `this` keyword in a future video)* Arrow functions are also **anonymous functions**, which means there is no way to declare an arrow function the way we do a function declaration `function doctorize() {..}`. You always have to stick it into a variable. To illustrate this, we will begin by writing a regular function. πŸ‘‡ ``` function inchToCM(inches) { const cm = inches * 2.54; return cm; } ``` This function will take in inches and return centimeters. Let's try it out in the browser. ![regular function named inchToCM with inches as parameters and return value](https://wesbos.com/assets/regular-function-definiation-with-calling-YPEdmeDY.webp) This is a pretty simple function, but it still takes up 4 lines of code. We can make it a bit shorter by instead of creating a variable and then returning a variable, we can just return the calculation directly. ``` function inchToCM(inches) { return inches * 2.54; } ``` ![regular function with direct return value](https://wesbos.com/assets/regular-function-with-direct-return-value-37YRyWWW.webp) *Note: You may notice in the above πŸ‘† screenshot that the line of code with `return cm;` is now greyed out. That is because that code will never be reached, since we are returning in the line of code above it. When you return from a function, the function stops running.* Now we can convert it to an anonymous function as a step on the way to making it an arrow function. ``` const inchToCM = function (inches) { return inches * 2.54; }; ``` Refresh the page to check that it still works, which it should. All we have done is turned it into an anonymous function and stored it in a variable. ### Different Ways to Write Arrow Functions Let's convert it to an arrow function now, which we can do a few different ways. Instead of writing the word function, we will delete it like so πŸ‘‡ ``` const inchToCM = (inches) { return inches * 2.54; } ``` Now we will go to the right of the parenthesis and add what is called a **fat arrow** `=>`. In programming, `->` is referred to as a **skinny arrow** and `=>` is referred to as a **fat arrow**. ``` const inchToCM = (inches) => { return inches * 2.54; }; ``` When you save, you might notice that Prettier modified the function for you and removes the parenthesis, which is not what we want because we are trying to change it to an arrow function in steps.To disable that, add `/* eslint-disable */` right above the function. *The spaces between the parenthesis and the arrow in the following code πŸ‘‰ `(inches) => {` does not have to be there, this is the same code with different whitespace and πŸ‘‰ `(inches)=>{` still works, but it's more readable with spaces.* If you refresh the page and run it in the console, you will see that it still works. ### Implicit and Explicit Returns The next thing we will do is what is called an **implicit return**. An **explicit return** is when you type the `return` keyword before returning a value such as πŸ‘‡ ``` return inches * 2.54; ``` That is an explicit return meaning that *we explicitly return the value there*. An **implicit return** is returning it without actually having to type the keyword `return`. Arrow functions allow us to use implicit returns. Let's start by putting the function on one line, like so πŸ‘‡ ``` const inchToCM = (inches) => { return inches * 2.54; }; ``` To get rid of the **explicit** return: - first put the function on one line - then delete the curly brackets`{` `}` - finally, delete the `return` keyword ``` const inchToCM = (inches) => inches * 2.54; ``` Your code should look like the above πŸ‘† What we did there is: - we made an arrow function `inchToCM` which takes in one parameter, `inches` - modified the function to implicitly return the value. The way we can tell this is an implicit return is that: 1. it's all on one line 2. there is no return keyword 3. there are no curly brackets If you refresh the browser, you will see that it still works. *To recap: what we did there is we removed the function block, modified the code to be on one line, and removed the explicit return.* Finally, and this is more of a stylistic choice, if there is only ever one parameter for your function, you can actually get rid of the parenthesis around the parameter as well, like soπŸ‘‡ ``` const inchToCM = inches => inches * 2.54; ``` If there is only one parameter in your arrow function, you can remove them no problem. It is still a valid arrow function. Let's do another example\! Make a function called `add`, that takes in two parameters `a` and `b`, with the default value of `b` being 3. We will then make a temporary variable called `total` which we return. ``` function add(a, b = 3) { const total = a + b; return total; } ``` Pause here, try to convert it to an arrow function yourself and then come back once you have tried it. Let's first see if it works as it originally was. Save the code from above πŸ‘† and refresh `index.html` in the browser. Open the console and test the function. ![add function with optional b argument](data:image/webp;base64,UklGRsgLAABXRUJQVlA4ILwLAACQQQCdASr6AKgAPpFCm0olo6MhppQLiLASCWdu3WAqvHL0B9nAeJz0gPMB4AHuU84DqAPQA6Tr9uvSx1Wzy1/Pvxx8Jf8t4j+PD2nm4Z4+ujNF9s/y35meyn+Z8KfhRqBeqf8lv/oAvyj+mf7TwXv9T0F+xnsAfzf+r/7vj9PPfYE/oX+U9CrPb9Vf+X3EP19/6fYk9GMtSAqZBlirQ0Byr4IaXe98DAZnrbDJx/LUcgRW9YSCPIlZTIOq6GzYRchf9iX/IgDtjCXYv4tErHZPhZuICmivoYX1fV79NZYI8hRmEZYfG1Qjd7/ZwYQW2RUtWOHO9Nz+z1BtP2GZHmRAIfN9pjSqFw+EtlDUAwjdGwBqmWW4E7Ffradcrijs8M6w++hbT8PjtoCFpRJsW72IUelRTfTGCtmIPbsksEZAYEidMguum9IMn5+m/7AgWpPUUCYeUV/kuggpJa7arP5YDDk3EW1PjBkovTDqsA1YhYNoDsDhNAmo3FlckkqsFVNCIFXJwNYkNMD2i3YIy+ISW/byF4c91/9TEP8PkeLjYpE1elNggh/APGN/rikE7ULXiRxRd0k+YWvbJErHLNHPPRYZgAJqhqYlFwfCIYMLGomBcxgHVvjDt7xB42ub/h6NILHQyPpJuRIv1PP4v4SER9y4eNZTkeZCsuKZZExjE/q5PooRVZTkeZEENbSfhQbyJF+ugAD+ZKBoxfBu348kyApGEiaE9uNt3T4Lub1n3fJaXj/4y2kl6IfsS4furvq4v3h6NCS1zazaCH7u7dY7CmLetrCBOI24WQqp6a5HwpDfCJ2BvKEfxhcig4iBxPHPrmtbgDWCqJY/tmWF1O3UqTBhUSBwD0WEnfEKRU0yjm7AOII1KTgXdZDsCipHf3w2lmrCmp7j3KsraxX3zllociT/NVX4aVsFlJ29AsKHBfOqWosU2zQrfc45LjqLs7miISvq1IOX3XVTCvwGp+9bQP9i9tXmczKsusONyXnDlEiCeyeGkl6xo946uwhub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u2AYBxKCdBd2Vm7sgaNWVUbzO/5BXB0HX6/tmJDZTD3kv7lonL4U9YnCBMvM5+aQLUi+qAt86syRXf/hb/Wu9lPw/xToyv1p1FEax7Hzb6TG5P9tmuSVqYcBdvvfMADHcXi/IBj3hA2/6hF1tu28vic638+6Qa7ek6ywTJ4WAPC4z14vti/jfKmnmeBARewpgwLNmGdeaWjN11MsmD4cg04MR7gEugXo5le/7Oazd/5sqdD6D9Vy0u1AYo85h89XPtEMVn3XGZ9NFtJgUfV9pSc9DKfq+31CR8kwcMOepaTQ2C15avIhEQp2jOM+ah2jiF4d5UJuNh9DemFXkLm2Zb4mmPpqtV9ZYNB242buEtmSnebP2SsWeA/wstVn4e5F2BCki1eQpwfcRbUiLkU2z39CMRsxZPMAo8qstb/18WfEdfrb5hY0+Pc5jMweLkSUexLC5QtlSgwCOecfsD0Kg+JeAcZzhjo1iJoZb0VFVVPR/JcFIe2EZ8gt6gcrYz3DQ/WvG1hVotCWOhOCmcdxeXG/33O1tLcRKRMpG3vSBcwNVLrH229mqkN/Y5qj2sbkGitgrOxNLXWGGRhNMtNZEInk7LVBervF03oHQtp6bw45HykKSAMyqd/am5TXgPvPzHZFZDffec2beO18Q1ue3ttVsAFaXXHmQNP/bBQa3zCAs0bs1V+Cv++gLwAEI9Pe9HMoi3F8B21nTTEMz0sO14+br75CHsZlZGC6wy6ri/kWTWA0GkY1J+Z1Ck+4qr96Z/YsPUDV6jOXdsPm0lFZ/z1Ubdb7V7LMea6kFF/220hQNiAAAAAA) You might notice that dev tools is giving us an annotation `?b` in `Ζ’(a,?b)` as shown above. That little question mark in front of `b` is telling us that the argument is optional. `b` is optional because there is a default value to fall back on. Stick the function in a variable `add` and remove the function name, like so πŸ‘‡ ``` const add => function (a, b = 3) {} ``` Next, convert it to an arrow function. Get rid of the keyword function and add a fat arrow to the right of the parenthesis, as shown below. ``` const add = (a, b = 3) => { const total = a + b; return total; }; ``` Modify the code to return `a + b` and get rid of the total variable. πŸ‘‡ ``` const add = (a, b = 3) => { return a + b; }; ``` Put the function on one line. ``` const add = (a,b = 3) => { return a + b; } ``` Get rid of the function block and the `return` keyword like so πŸ‘‡ ``` const add = (a, b = 3) => a + b; ``` Now we have a short arrow function\! You may have noticed that we did not get rid of the parentheses, and that is because there is more than one parameter. ### Arrow Function Gotcha's There are a couple of other gotchas with arrow functions that we need to know about. Let's go over them now. #### Returning an object Let's make a function `makeABaby()`, which will accept a first and last name for the baby. Inside of the function, create an object `baby` with a `name` and `age` property. πŸ‘‡ ``` function makeABaby(first, last) { const baby = { name: `${first} ${last}`, age: 0, }; return baby; } ``` It works\! ![makeABaby accepting first and last name and returning a baby object having name and age properties](https://wesbos.com/assets/function-accepting-first-last-name-with-returning-object-CEiKRYQ0.webp) How could you convert this to an arrow function? Stick it in a variable and convert it to an arrow function like so πŸ‘‡ ``` const makeABaby = (first, last) => { const baby = { name: `${first} ${last}`, age: 0, }; return baby; }; ``` If your function needs to do some stuff inside of the block, you can leave it as is. This is a perfectly valid arrow function. If the only thing you're using the arrow for is the ability to type less as well as some of the benefits of not scoping this, this is totally valid. However, we can take it a bit further. Instead of declaring the `baby` variable, we will just return the object directly. πŸ‘‡ ``` const makeABaby = (first, last) => { return { name: `${first} ${last}`, age: 0, }; }; ``` Now the question is... how would we do the implicit return? We can put it on one line, no problem *(objects can be put on one line)*. But how would we return it? Let's try it the way we know. Put it on one line. ``` const makeABaby = (first, last) => { return { name: `${first} ${last}`, age: 0 }; }; ``` To make it an implicit return, get rid of the curly brackets and the `return` keyword. πŸ‘‡ ``` const makeABaby = (first, last) => { name: `${first} ${last}`, age: 0}; ``` ![error in making implicit return and removing curly brackets](https://wesbos.com/assets/implicit-return-error-in-console-DWv6NWuM.webp) However, you will see the above πŸ‘† error if you try to run the code like that. What's happening there is it thinks that the curly bracket from the baby object is actually the curly bracket from the block of the function. Curly brackets in JavaScript can be the creation of an object, or a block of code. What are your options to implicitly return an object then? If you want to implicitly return an object in JavaScript, you just pop a set of parentheses around the thing that you are returning and then the code will know that it's not the block to the function. Try it by modifying your code like so πŸ‘‡ ``` const makeABaby = (first, last) => ({ name: `${first} ${last}`, age: 0 }); ``` If you try it in the code, it still works. Now... is there a benefit of having the function this way or how we did it originally? Wes doesn't think so. You're not really getting much benefit, in fact the way we had it originally was a bit more readable. There is nothing wrong with doing a regular function, because you want to think about your future self. Let's say you come back to the code in 6 months, what will be easier for you to read? Don't always go to making an arrow function by default, and hopefully throughout this course it will become more clear when you should reach for an arrow function (specifically with arrays and doing maps, reduce and filters). ## IIFE The next way to create a function is using an **IIFE** (pronounced **iffy**). That is an **immediately invoked function expression**. We will do an example to demonstrate what an IIFE is. Comment out all the other JavaScript code, add the code below and then refresh `index.html`. πŸ‘‡ ``` function(){ console.log('Running the Anon function'); return `You are cool`; } ``` Nothing happens when you refresh `index.html` because it's not allowed to run. We talked about how you can stick a function in a variable and that is okay. Another way to run this function is what is called an **immediately invoked functional expression.** What you can do is wrap that function in a parentheses, *(parentheses always run first in JavaScript)*, and what that will do is return a function value and you can immediately run that function by putting parentheses on the end like so πŸ‘‡ ``` (function () { console.log("Running the Anon function"); return `Your are cool`; })(); ``` Now, if you refresh the page, you will see the log in the console which means our function expression was immediately invoked. It was immediately run. What is the benefit of doing something like that? It used to be very popular before we had modules and block scope. When we get into scoping, you will learn that a function declares its own scope, and it's often handy to even declare functions of them, and it will provide us a sheltered space where the variables can't leak inside. We will go over that later in the course. For now, just know that it's an immediately invoked function. One last thing is what if the function took an age? You would pass it like so πŸ‘‡ ``` (function (age) { console.log("Running the Anon function"); return `Your are cool and ${age}`; })(age); ``` That isn't something you will be using that often, but it does come up when you need to create something like a **closure** *(which will be explained in future video).* ## Methods The next type of functions we will learn about are referred to as **methods**. A method is simply a function that lives inside of an object. *(Wes has so far sort of been saying that methods and functions are the same thing and we have a video coming up that focused entirely on creating your own methods that will make that clearer).* So far Wes has been telling us that `console.log()` is a function. If we take a look at the function `console.log` in the browser, we will see that he has been lying to us. `log()` is actually the function that lives inside of `console`, and `console` is actually an object. If you type `console` into the console and expand it, you will see that there are all kinds of things within it. πŸ‘‡ ![printing console word includes many methods along with it](https://wesbos.com/assets/printing-console-in-console-BHOpMAnn.webp) Scroll down to log, and the little Ζ’ you see means that it's actually a function πŸ‘‰ So `console` is the object and `log()`, `count()` or any of the other functions listed under the console object are the functions. We have a special word to describe functions that live inside of an object and we call those **methods**. So you can actually do something like this.. πŸ‘‡ ``` const wes = { name: "Wes Bos", sayHi: function () { console.log("Hey wes!"); return "Hey Wes!"; }, }; ``` Try it in the browser. First, type `wes` and hit Enter. Next, type `wes.sayHi()` and hit Enter. You should see the following πŸ‘‡ ![wes is an object here and sayHi method it has which gets called](https://wesbos.com/assets/calling-a-method-of-object-in-console-DqtOjvSP.webp) `wes.sayHi()` is a **method**. You make it a property on your object and you set it to a function. Those functions can also have names, for example sometimes you will see something like this πŸ‘‡ ``` const wes = { name: "Wes Bos", sayHi: function sayHi() { console.log("Hey wes!"); return "Hey Wes!"; }, }; ``` Wes doesn't see the point of doing that, but it is technically allowed. There is also a new shorthand method. πŸ‘‡ ``` const wes = { name: "Wes Bos", // Method! sayHi: function sayHi() { console.log("Hey Wes!"); return "Hey Wes!"; }, //Short hand Method yellHi() { console.log("HEY WESSSSS"); }, }; ``` If you refresh the browser and type `wes.yellHi()`, it will work. What we did here is instead of writing `sayHi: function()` *(which does work)*, we can get rid of the `function` keyword and the `:`. That makes it into a property, `yellHi()`, which is set to the function `yellHi`. It's just a shorthand way to write methods inside of an object. There is another way, which is an arrow function. πŸ‘‡ ``` const wes = { name: 'Wes Bos', // Method! sayHi: function sayHi() { console.log('Hey Wes!'); return 'Hey Wes!'; }, // Short hand Method yellHi() { console.log('HEY WESSSSS'); }, // Arrow function whisperHi: () => { console.log('hiii wess im a mouse'); } }; ``` `whisperHi()` is an arrow function that doesn't take any arguments, but it could take in arguments if you wanted. Those are 3 different ways to do methods and the shorthand is the most common way. ## Preview of this The only reason you would do an arrow function is because you don't want to access `this`. We will go over that in detail when we get to objects but really quickly Wes will show us. Modify the `sayHi()` method to add `console.log(this);` and run it in the browser πŸ‘‡ ``` sayHi: function sayHi() { console.log(this); ``` You will see that on the line in our code that we logged, like `50`, the value of `this` has been returned. ![sayHi method logs the whole object, as this points to the whole object here](https://wesbos.com/assets/this-keyword-in-method-Bdml_BuM.webp) ((`this`)) is equal to the object that it was called against. That is cool because you could actually do something like this πŸ‘‡ ``` const wes = { name: 'Westopher Bos', // Method! sayHi: function sayHi() { console.log(`Hey ${this.name}`); console.log('Hey Wes!'); return 'Hey Wes!'; } ``` You would see it immediately fills the value of the name property. πŸ‘‡ ![access the individual properties of object using this operator](data:image/webp;base64,UklGRsgNAABXRUJQVlA4ILwNAADwSgCdASooAZ4APpFAnEuloyKhpFFKwLASCWdu8SAB0GW7oKjcwjdstuE95J9ADpN/KV1XPzt/Zfw88Cv7Z+N3nP4T/Ofsz6lf8B5Fuiv856Gfxn7E/ev6z+0Xs//p/CX4t/zf5O/AF6u/wW+B6z+w3qBevv0X/dfmB5hX836EfV7/ff1H9qvoA/jX89/znGYeaewH/MP7R/5/8t7sf9l/5fLF9Q/+D/N/Af/NP67/0/8D2oR/pMjeISiWjRy74/R+LFq4l1+GiEdYZGMeFMVh1ndv5bUW8cxdgP6qPfXXZwGkGFbvmyWmi5/4Virn6IkqTz8jClmaCZ0MCz6Am6w2rwS55fQA36nmj9FThSzHfjDhT1bwmYpEGxuNmIBFR7ubfOGkgnMD9lbTVExxb6UKjcEodbomwHf1lh86znxz6chD/sRYxSXJ5/vXQ5kD6x7gHV7p2krdFjK7PgvRJt7K2m4E4i1xLbhlpi6OtdlIo37wLMmmSQb6+4v4jb4ixkB+siv6zpQqvMEPXwQWWTgJFYJDtdjuKEjzRA8R5MJ1i9FaJr5KgkkyGGaBiYJDR0iYgmFbVMQ/+hel5sB9tUINolefa/1oWm5m9zCDs4kOqZA7+BXhhpbyvwim0abpY8u169prCxUw81tX67eawa52R0umdnLJVpkiEhEDlwUwYzppJwOM5RV3/v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Gb5R4XQQk8+JtF/wgO00hSatdyT9jaa46FTQ8v33Op3YYhDzBa2lym2BDuFZ03DfeBdrisCxG87wsXN/4P58LXl0axRIGm6ZoY4+c9YXOLlXybWkq/zTOfuqZ2o8FuIg+LIDbj3TF8mWInIQBgmS+N8dijnHYSHerJWB9DPlGhD/hT0REfFxKQde+rdLAQK7FXM88K6jBorlq0nvg9wH0gZ2b36dgkjJ4kiqudQgk+rqb7b1ocJxoSacBjeQiLvlWoxA9sFV3KToghZp/FBwodDg2INp1y17emCXi9VLqlUAFRIzcmEGheh2gHYFNh/UO2MxOQtG5+5RYLHKS5p9/YohbEPwaQmWd7l4njX2sIXsAD+1i3Q9GcocKDDhvgqkqijSbWMak075e5vXvECaw/1TwaP3SDtg+MJmzoNm8pD7PtKWIqdwkWLWEOq4itucOQBE91zh7euYIBW/pyz8StJQ9pGoP6/mRtC06aVkFjZ6IXdrPB5tqI7+p3hzwAF4ydXWY0fQBAAArGQc+7k+SkcNjfBOrO5/GW9RNQmToAH+FQ1Tp8VZnCC6Q6lGNtJRcgwJboA/3lWOEDlx2W1ka5C8BgMXsPbmjz/q017GRFnky/nTfsv/2h0u3TfU/pE363lgiOHc8U7o+Ifnyjw1vA/VXo9zDAAAAsqOwzE6Z8LccR8z7RjckasXcU6vYX2DzY9z/zPhnLYebGM/H8GtBVPB0nA/XT8dGIUQTEu4YAAAAA=) That will not work in an arrow function because they take the parent scope of `this`. We will explain that in the future. ## Callback Functions The final thing Wes wants to talk to us about is something called **callback functions**. So a callback function is just a regular function, but we use that name for something that will happen after something is done. The easiest way to define a callback function is either when someone clicks something, run this. Or when this amount of time has passed, run this. Let's look at both of those examples. ### Click Callback We will do a click callback. Go into `index.html` and add a button with a class of `clickMe` and text of "Click Me!" πŸ‘‡ ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width,initial-scale=1.0" /> <title></title> <link rel="stylesheet" href="../../base.css" /> </head> <body> <button class="clickMe">Click Me!</button> <script src="./ways-to-make-a-function.js"></script> </body> </html> ``` Back in the JavaScript file, let's select the element like so πŸ‘‡ *(we will cover the DOM in more depth later)* ``` const button = document.querySelector(".clickMe"); console.log(button); ``` Refresh the page and open the console to see that it works. ![selecting a button element using querySelector and printing in console](https://wesbos.com/assets/html-button-element-in-console-r3wwjQwT.webp) Next, listen for a click on that button as shown below ``` const button = document.querySelector(".clickMe"); button.addEventListener("click", wes.sayHi); ``` When that click happens, we can pass it to any function that we want. in this case, we chose `sayHi()` from our `wes` object from a previous example. Now, every time you click it, it will say "HEY WESSSS" πŸ‘‡ ![using object method as click handler in console](https://wesbos.com/assets/object-method-as-click-handler-in-console-BSbaSYbH.webp) What is happening there is that `.addEventListener()` is an **event listener** that we are listening for a click on, and the callback function is `wes.sayHi()`. It's a function that we give it access to. Notice that we are not running it there, we are just saying here is the function, when someone clicks the button, please call it. That is what is referred to as a callback function. Callback functions can be declared outside of the handler, like so πŸ‘‡ ``` function handleClick() { console.log("Great clicking!!"); } button.addEventListener("click", handleClick); ``` That tells the browser that when the element with a class of `.clickMe` is pressed, run the `handleClick` function. The other option, which is half as common, is to define the function outside and then pass in the reference to the function. Another thing you can do is just pass it an anonymous function, as shown below. ``` button.addEventListener("click", function () { console.log("nice Job!"); }); ``` ![passing anonymous function as callback function in button click listener](data:image/webp;base64,UklGRkAGAABXRUJQVlA4IDQGAADwIwCdASqcAFgAPpE+mksloyIho1K9eLASCWcAV+Z2n9Rv6h2y/5blhZbTcXfp/ivXv2r8AL1N/nd+E5h/SP9lxndyNxq1AD+Zf270LdAj1j7CP64f9DsHlxzKW3KA5McdMiEmoqX5JayDWPzbjdBniFOyIPPUe5v5knqS2RxDplgx0qMuhsE8DJ1mHl64npYfqUnz1RgiDE7+sSGMH4qx9Xy9hzRMJkB1O9KDItntghOz4HSxEtBKWKlEOouFrbWoX8DSHjNCswf4J2Jfeqvlgyihzi+x62pLjS3E0dcWRb4FFZwE6hPur261PnN69wjsxN1w00JOP4hrdFHi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e0pVZHQvgYQOEUPHRz0nydCbtkLsdFyC+TX0myafoeLiLyO0avSEBV2GoaBjj/hmWtufGDYdtn2zb6PtiI6WgNayqsNMrd22I2vqThzDgRnEL47lGXL4Q5dhLqYZgRco3uoZ91b8RqRiIoedms/Xf8+EszZiyNbyhkZPsR9FSFY0Aby8A5i8xXw9n6dGe6GGqAamF/bN9/mugatdKjtFji9lPvBy4kX9ThniAurmiVaqGhOV1uw5UDkuHC8tk6qvfmUg4mz33s94DbQqnimTh8ezHWGXC8F+ss254Z1yjZkEdeqBneSQ/9YHfx1MwiSfH+S3XhXtEMy7tPdFFLr/+kp7TDEFPb/Z3dNl44Esxk8HSSkrYvSciHArH9xuT9VeqOihtbPypEJu8QwHtAafFMxvO6gKZHtSUm4WRjo7buJ6qmJVEdA0J7T8Gvk6rLaVLtlMz23TaF2+g60Ksui6kM/vxSnbeYwGIQwey3rB0yI5H4PyCaA/+Us3jZw/e0OncuIZIjlnhAJu2fHc5P/mCIEU1uw73jdbBEd+qpXitmjCwFT/ac1ke4G255podCbhBUHEa0gXZFVl+EBzk3tNwCrUdYSjorl6THaosF4DfGsO4pcfCRBYZLXvl79hrbR9d2fy1ahNysPE1D3TPombOdCBGniP6IU7eF3y1p3u21v7/F2N1shFNx33r+jIIACXq7VYQAAAAA) And it works just fine when you press it. What we have done there is we have passed it an anonymous function as a value directly, and the browser will know to call this function itself. *(There are upsides and downsides of doing it that way which we will get into another time.)* What you need to know is that a **callback function is a function that gets passed into another function and then it is called by the browser at a later point in time.** ### Timer Callback The other example we have is a timer callback. There are a couple of ways to do timers *(we will go over all of them in the future)* but the simplest is `setTimeout()`. ``` setTimeout(); ``` It takes two things: 1. a function to call after a certain amount of time 2. a duration in milliseconds (after how long should I run this) So let's do `1000` milliseconds which is one second later. ``` setTimeout(wes.yellHi, 1000); ``` If we refresh the page, after one second, it will log HEY WES. You can also pass it an anonymous function. ``` setTimeout(function () { console.log("DONE TIME TO EAT"); }, 1000); ``` After a second that will log "DONE TIME TO EAT". You can pass those as arrow functions as well. ``` setTimeout(() => { console.log("DONE TIME TO EAT"); }, 1000); ``` That will work the same\! 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](https://github.com/wesbos/wesbos/tree/master/src/content/javascript/02-functions/15-different-ways-to-declare-functions/15-different-ways-to-declare-functions.mdx) [**← Prev**Functions - Parameters and Arguments](https://wesbos.com/javascript/02-functions/functions-parameters-and-arguments) [**Next β†’**Debugging Tools](https://wesbos.com/javascript/02-functions/debugging-tools) Loading... Loading... ### Beginner JavaScript ![Beginner JavaScript](https://res.cloudinary.com/wesbos/image/fetch/w_400,q_auto,f_auto/https://courses.wesbos.com/images/BJS/BJS-Social-Share.png) A fun, exercise heavy approach to learning Modern JavaScript from scratch. This is a course for absolute beginners or anyone looking to brush up on their fundamentals. Start here if you are new to JS or programming in general\! [BeginnerJavaScript.com](https://beginnerjavascript.com/) I post videos on [YouTube](https://youtube.com/wesbos?sub_confirmation=1) and code on [GitHub](https://github.com/wesbos) Wes Bos Β© [1999](https://web.archive.org/web/20040615000000*/wesbos.com) β€” 2026 [Terms](https://wesbos.com/terms) Γ— [Privacy Policy](https://wesbos.com/privacy) Commit [9e12f58](https://github.com/wesbos/wesbos/commit/9e12f58) ### Syntax Podcast: \#996 ![Syntax Podcast](https://wesbos.com/assets/syntax-artwork-DCJhtFxR.jpeg) April 15th, 2026 10 New CSS and HTML APIs [Listen Now β†’](https://syntax.fm/996/10-new-css-and-html-apis) ### 𝕏 [@wesbos](https://x.com/wesbos) Tweets 17 hours 0 135 8,874 [If you like this post the heart animates the grok log](https://x.com/wesbos/status/2044523569086931191) 18 hours 6 253 18,805 [slop is now called grokamole](https://x.com/wesbos/status/2044507855915544635) 20 hours 2 172 15,037 [blueish dark mode \> brownish dark mode](https://x.com/wesbos/status/2044482246074142977) 2 days 39 931 71,446 [![](https:///wsrv.nl/?url=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FHF31pikXUAAtKVn.jpg%3Fname%3Dthumb%26format%3Djpg&w=150&h=150&fit=cover)"the infrastructure I vibed together with gum and shoe strings cost me time and money"](https://x.com/wesbos/status/2044060210503778319)
Readable Markdown
One thing you will hear often when getting into JavaScript is that functions are *"first-class citizens"*. JavaScript functions are values in themselves, and they can be stored in variables and passed into other functions. What *is* a **value** in JavaScript? We know that in the examples below πŸ‘‡ that `true` and `100` are values. ``` const age = 100; const cool = true; ``` Those are values that are numbers, or strings or booleans. What is cool about JavaScript is that functions can be: - passed into other functions. - stored in variables, - moved around like any other piece of data in JavaScript That is not true for every other programming language. Let's start by looking at how you can put a function into a variable, and then look at the different ways to declare functions. Create a new file `ways-to-make-a-function.js` in the `/custom-functions` directory. ``` <script src="./ways-to-make-a-function.js"></script> ``` Add a log of "it works!" and go back to the `index.html` file and change the path in the script source attribute as shown above πŸ‘† and refresh the browser to ensure it works. We already know one way to declare a function and that is using the function keyword, like so πŸ‘‡ ``` function doctorize(firstName) { return `Dr. ${firstName}`; } ``` ## Anonymous Functions Let's look at some other options we have when declaring functions, starting with an **anonymous function**, which is a function without a name. To make `doctorize` an anonymous function, you would modify it like this πŸ‘‡ ``` function(firstName) { return `Dr. ${firstName}`; } ``` However, that is not valid JavaScript. If you try running it in the console you will see an error that says πŸ‘‡ > SyntaxError: Function statements require a function name ![declare function without name throws error](https://wesbos.com/assets/function-requires-function-name-error-B1wi3Lk3.webp) Anonymous functions are only valid in some use cases, such as using them in **callbacks** (we will learn more about that later) as well as in an **IIFE (immediately invoked function expression)**. This example was not a valid use case. Why would you ever want an anonymous function? ## Function Expressions The next way we will cover to declare a function will help explain that, which is as a **function expression**. Add a comment above that function specifying that it is an anonymous function, then copy the function and comment it out. Paste the copied code below the commented-out function. The next way to declare a function is a **function expression**. A function expression is when you store a function as a value in a variable. πŸ‘‡ ``` // function expression const doctorize = function (firstName) { return `Dr. ${firstName}`; }; ``` In the code above πŸ‘†, we have taken the anonymous function and stuck it in a variable. If you refresh the page, you will see that in the console, we have `doctorize()` available to us, and we can call it like we did in previous videos. ![assigning function to a variable makes function as anonymous](https://wesbos.com/assets/assigning-function-to-a-variable-pfsPaEtJ.webp) Having the ability to store a function in a variable is what leads people to say functions are *"first-class citizens"*. You may come across developers who say to not use function expressions because they used to give unhelpful errors. Previously, anonymous function errors would just tell you that they occurred in an anonymous function, without giving you any clue where the error is happening. However, now the dev tool errors are better. Here is an example that demonstrates what they mean by that πŸ‘‡ ``` // function expression const doctorize = function (firstName) { doesntExist(); return `Dr. ${firstName}`; }; ``` ![does not exists function call error](https://wesbos.com/assets/does-not-exist-not-defined-error-in-console-MgqW5vXU.webp) In our case, it does now tell you it happens inside of doctorize on line 12. Although the function is technically an anonymous function without a name, the browsers will now infer the name of the function from the variable name and use that in the errors. ### What is the difference between a function declaration and a function expression? What is the difference between doing a function declaration and a function expression? Why would you want to use one over the other? ## Hoisting There is only one real difference which is how they operate in something called **hoisting**. We will go over this in detail in a future video but for now we will just quickly cover the concept. Duplicate the `doctorize` function and name it `doctorize2`, like πŸ‘‡ ``` const doctorize = function (firstName) { return `Dr. ${firstName}`; }; function doctorize2 (firstName) { return `Dr. ${firstName}`; } ``` Let's say right before the first `doctorize` function, we called `doctorize` and passed it the value of "wes", as shown below πŸ‘‡, do you think the code will run? If you run a function before you define it, does it work? Refresh the page and look at the console to test it ``` doctorize("wes"); const doctorize = function (firstName) { return `Dr. ${firstName}`; }; function doctorize2 (firstName) { return `Dr. ${firstName}`; } ``` Did it work? Nope! You get an error like: > Uncaught ReferenceError: Cannot access 'doctorize' before initialization at ways-to-make-a-function.js:78 (anonymous) @ ways-to-make-a-function.js:78 What about `doctorize2`? ``` console.log(doctorize2("wes")); const doctorize = function (firstName) { return `Dr. ${firstName}`; }; function doctorize2 (firstName) { return `Dr. ${firstName}`; } ``` It does work\! Why does a function declaration work if you call it before you define it, but a function expression does not, especially when we created the exact same function in both cases? Functions that are declared with the **function** keyword are called **hoisted**. JavaScript will take all functions with the function keyword and hoist them up, up, up and says "you're a function, you belong at the top of the file". That means anywhere you call the function, it will be available to you. JavaScript does **not** hoist variable functions. When is that useful? Very rarely, Wes has never used that in his entire career except for tiny use cases. **Hoisting** is more of an interview question that you may be asked. Essentially it means that JavaScript will take functions and bring them up to the top of the code before they are called. This gives us the ability to run a function before it is defined. Remove the `doctorize2` function from the JavaScript file which should leave just the function expression. ## Arrow Functions The next way to make a function is using an **arrow function**. Arrow functions themselves have a few different ways of being declared. They are a newer addition to JavaScript, and were added in the last couple of years. They have a few benefits: - concise syntax and tend to be shorter - allow for writing one line functions - do not have their own scope in reference to the `this` keyword *(we will cover the `this` keyword in a future video)* Arrow functions are also **anonymous functions**, which means there is no way to declare an arrow function the way we do a function declaration `function doctorize() {..}`. You always have to stick it into a variable. To illustrate this, we will begin by writing a regular function. πŸ‘‡ ``` function inchToCM(inches) { const cm = inches * 2.54; return cm; } ``` This function will take in inches and return centimeters. Let's try it out in the browser. ![regular function named inchToCM with inches as parameters and return value](https://wesbos.com/assets/regular-function-definiation-with-calling-YPEdmeDY.webp) This is a pretty simple function, but it still takes up 4 lines of code. We can make it a bit shorter by instead of creating a variable and then returning a variable, we can just return the calculation directly. ``` function inchToCM(inches) { return inches * 2.54; } ``` ![regular function with direct return value](https://wesbos.com/assets/regular-function-with-direct-return-value-37YRyWWW.webp) *Note: You may notice in the above πŸ‘† screenshot that the line of code with `return cm;` is now greyed out. That is because that code will never be reached, since we are returning in the line of code above it. When you return from a function, the function stops running.* Now we can convert it to an anonymous function as a step on the way to making it an arrow function. ``` const inchToCM = function (inches) { return inches * 2.54; }; ``` Refresh the page to check that it still works, which it should. All we have done is turned it into an anonymous function and stored it in a variable. ### Different Ways to Write Arrow Functions Let's convert it to an arrow function now, which we can do a few different ways. Instead of writing the word function, we will delete it like so πŸ‘‡ ``` const inchToCM = (inches) { return inches * 2.54; } ``` Now we will go to the right of the parenthesis and add what is called a **fat arrow** `=>`. In programming, `->` is referred to as a **skinny arrow** and `=>` is referred to as a **fat arrow**. ``` const inchToCM = (inches) => { return inches * 2.54; }; ``` When you save, you might notice that Prettier modified the function for you and removes the parenthesis, which is not what we want because we are trying to change it to an arrow function in steps.To disable that, add `/* eslint-disable */` right above the function. *The spaces between the parenthesis and the arrow in the following code πŸ‘‰ `(inches) => {` does not have to be there, this is the same code with different whitespace and πŸ‘‰ `(inches)=>{` still works, but it's more readable with spaces.* If you refresh the page and run it in the console, you will see that it still works. ### Implicit and Explicit Returns The next thing we will do is what is called an **implicit return**. An **explicit return** is when you type the `return` keyword before returning a value such as πŸ‘‡ ``` return inches * 2.54; ``` That is an explicit return meaning that *we explicitly return the value there*. An **implicit return** is returning it without actually having to type the keyword `return`. Arrow functions allow us to use implicit returns. Let's start by putting the function on one line, like so πŸ‘‡ ``` const inchToCM = (inches) => { return inches * 2.54; }; ``` To get rid of the **explicit** return: - first put the function on one line - then delete the curly brackets`{` `}` - finally, delete the `return` keyword ``` const inchToCM = (inches) => inches * 2.54; ``` Your code should look like the above πŸ‘† What we did there is: - we made an arrow function `inchToCM` which takes in one parameter, `inches` - modified the function to implicitly return the value. The way we can tell this is an implicit return is that: 1. it's all on one line 2. there is no return keyword 3. there are no curly brackets If you refresh the browser, you will see that it still works. *To recap: what we did there is we removed the function block, modified the code to be on one line, and removed the explicit return.* Finally, and this is more of a stylistic choice, if there is only ever one parameter for your function, you can actually get rid of the parenthesis around the parameter as well, like soπŸ‘‡ ``` const inchToCM = inches => inches * 2.54; ``` If there is only one parameter in your arrow function, you can remove them no problem. It is still a valid arrow function. Let's do another example\! Make a function called `add`, that takes in two parameters `a` and `b`, with the default value of `b` being 3. We will then make a temporary variable called `total` which we return. ``` function add(a, b = 3) { const total = a + b; return total; } ``` Pause here, try to convert it to an arrow function yourself and then come back once you have tried it. Let's first see if it works as it originally was. Save the code from above πŸ‘† and refresh `index.html` in the browser. Open the console and test the function. ![add function with optional b argument](data:image/webp;base64,UklGRsgLAABXRUJQVlA4ILwLAACQQQCdASr6AKgAPpFCm0olo6MhppQLiLASCW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/xToyv1p1FEax7Hzb6TG5P9tmuSVqYcBdvvfMADHcXi/IBj3hA2/6hF1tu28vic638+6Qa7ek6ywTJ4WAPC4z14vti/jfKmnmeBARewpgwLNmGdeaWjN11MsmD4cg04MR7gEugXo5le/7Oazd/5sqdD6D9Vy0u1AYo85h89XPtEMVn3XGZ9NFtJgUfV9pSc9DKfq+31CR8kwcMOepaTQ2C15avIhEQp2jOM+ah2jiF4d5UJuNh9DemFXkLm2Zb4mmPpqtV9ZYNB242buEtmSnebP2SsWeA/wstVn4e5F2BCki1eQpwfcRbUiLkU2z39CMRsxZPMAo8qstb/18WfEdfrb5hY0+Pc5jMweLkSUexLC5QtlSgwCOecfsD0Kg+JeAcZzhjo1iJoZb0VFVVPR/JcFIe2EZ8gt6gcrYz3DQ/WvG1hVotCWOhOCmcdxeXG/33O1tLcRKRMpG3vSBcwNVLrH229mqkN/Y5qj2sbkGitgrOxNLXWGGRhNMtNZEInk7LVBervF03oHQtp6bw45HykKSAMyqd/am5TXgPvPzHZFZDffec2beO18Q1ue3ttVsAFaXXHmQNP/bBQa3zCAs0bs1V+Cv++gLwAEI9Pe9HMoi3F8B21nTTEMz0sO14+br75CHsZlZGC6wy6ri/kWTWA0GkY1J+Z1Ck+4qr96Z/YsPUDV6jOXdsPm0lFZ/z1Ubdb7V7LMea6kFF/220hQNiAAAAAA) You might notice that dev tools is giving us an annotation `?b` in `Ζ’(a,?b)` as shown above. That little question mark in front of `b` is telling us that the argument is optional. `b` is optional because there is a default value to fall back on. Stick the function in a variable `add` and remove the function name, like so πŸ‘‡ ``` const add => function (a, b = 3) {} ``` Next, convert it to an arrow function. Get rid of the keyword function and add a fat arrow to the right of the parenthesis, as shown below. ``` const add = (a, b = 3) => { const total = a + b; return total; }; ``` Modify the code to return `a + b` and get rid of the total variable. πŸ‘‡ ``` const add = (a, b = 3) => { return a + b; }; ``` Put the function on one line. ``` const add = (a,b = 3) => { return a + b; } ``` Get rid of the function block and the `return` keyword like so πŸ‘‡ ``` const add = (a, b = 3) => a + b; ``` Now we have a short arrow function\! You may have noticed that we did not get rid of the parentheses, and that is because there is more than one parameter. ### Arrow Function Gotcha's There are a couple of other gotchas with arrow functions that we need to know about. Let's go over them now. #### Returning an object Let's make a function `makeABaby()`, which will accept a first and last name for the baby. Inside of the function, create an object `baby` with a `name` and `age` property. πŸ‘‡ ``` function makeABaby(first, last) { const baby = { name: `${first} ${last}`, age: 0, }; return baby; } ``` It works\! ![makeABaby accepting first and last name and returning a baby object having name and age properties](https://wesbos.com/assets/function-accepting-first-last-name-with-returning-object-CEiKRYQ0.webp) How could you convert this to an arrow function? Stick it in a variable and convert it to an arrow function like so πŸ‘‡ ``` const makeABaby = (first, last) => { const baby = { name: `${first} ${last}`, age: 0, }; return baby; }; ``` If your function needs to do some stuff inside of the block, you can leave it as is. This is a perfectly valid arrow function. If the only thing you're using the arrow for is the ability to type less as well as some of the benefits of not scoping this, this is totally valid. However, we can take it a bit further. Instead of declaring the `baby` variable, we will just return the object directly. πŸ‘‡ ``` const makeABaby = (first, last) => { return { name: `${first} ${last}`, age: 0, }; }; ``` Now the question is... how would we do the implicit return? We can put it on one line, no problem *(objects can be put on one line)*. But how would we return it? Let's try it the way we know. Put it on one line. ``` const makeABaby = (first, last) => { return { name: `${first} ${last}`, age: 0 }; }; ``` To make it an implicit return, get rid of the curly brackets and the `return` keyword. πŸ‘‡ ``` const makeABaby = (first, last) => { name: `${first} ${last}`, age: 0}; ``` ![error in making implicit return and removing curly brackets](https://wesbos.com/assets/implicit-return-error-in-console-DWv6NWuM.webp) However, you will see the above πŸ‘† error if you try to run the code like that. What's happening there is it thinks that the curly bracket from the baby object is actually the curly bracket from the block of the function. Curly brackets in JavaScript can be the creation of an object, or a block of code. What are your options to implicitly return an object then? If you want to implicitly return an object in JavaScript, you just pop a set of parentheses around the thing that you are returning and then the code will know that it's not the block to the function. Try it by modifying your code like so πŸ‘‡ ``` const makeABaby = (first, last) => ({ name: `${first} ${last}`, age: 0 }); ``` If you try it in the code, it still works. Now... is there a benefit of having the function this way or how we did it originally? Wes doesn't think so. You're not really getting much benefit, in fact the way we had it originally was a bit more readable. There is nothing wrong with doing a regular function, because you want to think about your future self. Let's say you come back to the code in 6 months, what will be easier for you to read? Don't always go to making an arrow function by default, and hopefully throughout this course it will become more clear when you should reach for an arrow function (specifically with arrays and doing maps, reduce and filters). ## IIFE The next way to create a function is using an **IIFE** (pronounced **iffy**). That is an **immediately invoked function expression**. We will do an example to demonstrate what an IIFE is. Comment out all the other JavaScript code, add the code below and then refresh `index.html`. πŸ‘‡ ``` function(){ console.log('Running the Anon function'); return `You are cool`; } ``` Nothing happens when you refresh `index.html` because it's not allowed to run. We talked about how you can stick a function in a variable and that is okay. Another way to run this function is what is called an **immediately invoked functional expression.** What you can do is wrap that function in a parentheses, *(parentheses always run first in JavaScript)*, and what that will do is return a function value and you can immediately run that function by putting parentheses on the end like so πŸ‘‡ ``` (function () { console.log("Running the Anon function"); return `Your are cool`; })(); ``` Now, if you refresh the page, you will see the log in the console which means our function expression was immediately invoked. It was immediately run. What is the benefit of doing something like that? It used to be very popular before we had modules and block scope. When we get into scoping, you will learn that a function declares its own scope, and it's often handy to even declare functions of them, and it will provide us a sheltered space where the variables can't leak inside. We will go over that later in the course. For now, just know that it's an immediately invoked function. One last thing is what if the function took an age? You would pass it like so πŸ‘‡ ``` (function (age) { console.log("Running the Anon function"); return `Your are cool and ${age}`; })(age); ``` That isn't something you will be using that often, but it does come up when you need to create something like a **closure** *(which will be explained in future video).* ## Methods The next type of functions we will learn about are referred to as **methods**. A method is simply a function that lives inside of an object. *(Wes has so far sort of been saying that methods and functions are the same thing and we have a video coming up that focused entirely on creating your own methods that will make that clearer).* So far Wes has been telling us that `console.log()` is a function. If we take a look at the function `console.log` in the browser, we will see that he has been lying to us. `log()` is actually the function that lives inside of `console`, and `console` is actually an object. If you type `console` into the console and expand it, you will see that there are all kinds of things within it. πŸ‘‡ ![printing console word includes many methods along with it](https://wesbos.com/assets/printing-console-in-console-BHOpMAnn.webp) Scroll down to log, and the little Ζ’ you see means that it's actually a function πŸ‘‰ So `console` is the object and `log()`, `count()` or any of the other functions listed under the console object are the functions. We have a special word to describe functions that live inside of an object and we call those **methods**. So you can actually do something like this.. πŸ‘‡ ``` const wes = { name: "Wes Bos", sayHi: function () { console.log("Hey wes!"); return "Hey Wes!"; }, }; ``` Try it in the browser. First, type `wes` and hit Enter. Next, type `wes.sayHi()` and hit Enter. You should see the following πŸ‘‡ ![wes is an object here and sayHi method it has which gets called](https://wesbos.com/assets/calling-a-method-of-object-in-console-DqtOjvSP.webp) `wes.sayHi()` is a **method**. You make it a property on your object and you set it to a function. Those functions can also have names, for example sometimes you will see something like this πŸ‘‡ ``` const wes = { name: "Wes Bos", sayHi: function sayHi() { console.log("Hey wes!"); return "Hey Wes!"; }, }; ``` Wes doesn't see the point of doing that, but it is technically allowed. There is also a new shorthand method. πŸ‘‡ ``` const wes = { name: "Wes Bos", // Method! sayHi: function sayHi() { console.log("Hey Wes!"); return "Hey Wes!"; }, //Short hand Method yellHi() { console.log("HEY WESSSSS"); }, }; ``` If you refresh the browser and type `wes.yellHi()`, it will work. What we did here is instead of writing `sayHi: function()` *(which does work)*, we can get rid of the `function` keyword and the `:`. That makes it into a property, `yellHi()`, which is set to the function `yellHi`. It's just a shorthand way to write methods inside of an object. There is another way, which is an arrow function. πŸ‘‡ ``` const wes = { name: 'Wes Bos', // Method! sayHi: function sayHi() { console.log('Hey Wes!'); return 'Hey Wes!'; }, // Short hand Method yellHi() { console.log('HEY WESSSSS'); }, // Arrow function whisperHi: () => { console.log('hiii wess im a mouse'); } }; ``` `whisperHi()` is an arrow function that doesn't take any arguments, but it could take in arguments if you wanted. Those are 3 different ways to do methods and the shorthand is the most common way. ## Preview of this The only reason you would do an arrow function is because you don't want to access `this`. We will go over that in detail when we get to objects but really quickly Wes will show us. Modify the `sayHi()` method to add `console.log(this);` and run it in the browser πŸ‘‡ ``` sayHi: function sayHi() { console.log(this); ``` You will see that on the line in our code that we logged, like `50`, the value of `this` has been returned. ![sayHi method logs the whole object, as this points to the whole object here](https://wesbos.com/assets/this-keyword-in-method-Bdml_BuM.webp) ((`this`)) is equal to the object that it was called against. That is cool because you could actually do something like this πŸ‘‡ ``` const wes = { name: 'Westopher Bos', // Method! sayHi: function sayHi() { console.log(`Hey ${this.name}`); console.log('Hey Wes!'); return 'Hey Wes!'; } ``` You would see it immediately fills the value of the name property. πŸ‘‡ ![access the individual properties of object using this operator](data:image/webp;base64,UklGRsgNAABXRUJQVlA4ILwNAADwSgCdASooAZ4APpFAnEuloyKhpFFKwLASCWdu8SAB0GW7oKjcwjdstuE95J9ADpN/KV1XPzt/Zfw88Cv7Z+N3nP4T/Ofsz6lf8B5Fuiv856Gfxn7E/ev6z+0Xs//p/CX4t/zf5O/AF6u/wW+B6z+w3qBevv0X/dfmB5hX836EfV7/ff1H9qvoA/jX89/znGYeaewH/MP7R/5/8t7sf9l/5fLF9Q/+D/N/Af/NP67/0/8D2oR/pMjeISiWjRy74/R+LFq4l1+GiEdYZGMeFMVh1ndv5bUW8cxdgP6qPfXXZwGkGFbvmyWmi5/4Virn6IkqTz8jClmaCZ0MCz6Am6w2rwS55fQA36nmj9FThSzHfjDhT1bwmYpEGxuNmIBFR7ubfOGkgnMD9lbTVExxb6UKjcEodbomwHf1lh86znxz6chD/sRYxSXJ5/vXQ5kD6x7gHV7p2krdFjK7PgvRJt7K2m4E4i1xLbhlpi6OtdlIo37wLMmmSQb6+4v4jb4ixkB+siv6zpQqvMEPXwQWWTgJFYJDtdjuKEjzRA8R5MJ1i9FaJr5KgkkyGGaBiYJDR0iYgmFbVMQ/+hel5sB9tUINolefa/1oWm5m9zCDs4kOqZA7+BXhhpbyvwim0abpY8u169prCxUw81tX67eawa52R0umdnLJVpkiEhEDlwUwYzppJwOM5RV3/vdaoOPMzKfJY38WFXtnNFaUD/w/KivFc98BG/k+aLpelY6diR/CJvBJsosBQkelG0oJ5evZUa7yaAKFJ7S+EGFc/RHZWUX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ZoY4+c9YXOLlXybWkq/zTOfuqZ2o8FuIg+LIDbj3TF8mWInIQBgmS+N8dijnHYSHerJWB9DPlGhD/hT0REfFxKQde+rdLAQK7FXM88K6jBorlq0nvg9wH0gZ2b36dgkjJ4kiqudQgk+rqb7b1ocJxoSacBjeQiLvlWoxA9sFV3KToghZp/FBwodDg2INp1y17emCXi9VLqlUAFRIzcmEGheh2gHYFNh/UO2MxOQtG5+5RYLHKS5p9/YohbEPwaQmWd7l4njX2sIXsAD+1i3Q9GcocKDDhvgqkqijSbWMak075e5vXvECaw/1TwaP3SDtg+MJmzoNm8pD7PtKWIqdwkWLWEOq4itucOQBE91zh7euYIBW/pyz8StJQ9pGoP6/mRtC06aVkFjZ6IXdrPB5tqI7+p3hzwAF4ydXWY0fQBAAArGQc+7k+SkcNjfBOrO5/GW9RNQmToAH+FQ1Tp8VZnCC6Q6lGNtJRcgwJboA/3lWOEDlx2W1ka5C8BgMXsPbmjz/q017GRFnky/nTfsv/2h0u3TfU/pE363lgiOHc8U7o+Ifnyjw1vA/VXo9zDAAAAsqOwzE6Z8LccR8z7RjckasXcU6vYX2DzY9z/zPhnLYebGM/H8GtBVPB0nA/XT8dGIUQTEu4YAAAAA=) That will not work in an arrow function because they take the parent scope of `this`. We will explain that in the future. ## Callback Functions The final thing Wes wants to talk to us about is something called **callback functions**. So a callback function is just a regular function, but we use that name for something that will happen after something is done. The easiest way to define a callback function is either when someone clicks something, run this. Or when this amount of time has passed, run this. Let's look at both of those examples. ### Click Callback We will do a click callback. Go into `index.html` and add a button with a class of `clickMe` and text of "Click Me!" πŸ‘‡ ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width,initial-scale=1.0" /> <title></title> <link rel="stylesheet" href="../../base.css" /> </head> <body> <button class="clickMe">Click Me!</button> <script src="./ways-to-make-a-function.js"></script> </body> </html> ``` Back in the JavaScript file, let's select the element like so πŸ‘‡ *(we will cover the DOM in more depth later)* ``` const button = document.querySelector(".clickMe"); console.log(button); ``` Refresh the page and open the console to see that it works. ![selecting a button element using querySelector and printing in console](https://wesbos.com/assets/html-button-element-in-console-r3wwjQwT.webp) Next, listen for a click on that button as shown below ``` const button = document.querySelector(".clickMe"); button.addEventListener("click", wes.sayHi); ``` When that click happens, we can pass it to any function that we want. in this case, we chose `sayHi()` from our `wes` object from a previous example. Now, every time you click it, it will say "HEY WESSSS" πŸ‘‡ ![using object method as click handler in console](https://wesbos.com/assets/object-method-as-click-handler-in-console-BSbaSYbH.webp) What is happening there is that `.addEventListener()` is an **event listener** that we are listening for a click on, and the callback function is `wes.sayHi()`. It's a function that we give it access to. Notice that we are not running it there, we are just saying here is the function, when someone clicks the button, please call it. That is what is referred to as a callback function. Callback functions can be declared outside of the handler, like so πŸ‘‡ ``` function handleClick() { console.log("Great clicking!!"); } button.addEventListener("click", handleClick); ``` That tells the browser that when the element with a class of `.clickMe` is pressed, run the `handleClick` function. The other option, which is half as common, is to define the function outside and then pass in the reference to the function. Another thing you can do is just pass it an anonymous function, as shown below. ``` button.addEventListener("click", function () { console.log("nice Job!"); }); ``` ![passing anonymous function as callback function in button click listener](data:image/webp;base64,UklGRkAGAABXRUJQVlA4IDQGAADwIwCdASqcAFgAPpE+mksloyIho1K9eLASCWcAV+Z2n9Rv6h2y/5blhZbTcXfp/ivXv2r8AL1N/nd+E5h/SP9lxndyNxq1AD+Zf270LdAj1j7CP64f9DsHlxzKW3KA5McdMiEmoqX5JayDWPzbjdBniFOyIPPUe5v5knqS2RxDplgx0qMuhsE8DJ1mHl64npYfqUnz1RgiDE7+sSGMH4qx9Xy9hzRMJkB1O9KDItntghOz4HSxEtBKWKlEOouFrbWoX8DSHjNCswf4J2Jfeqvlgyihzi+x62pLjS3E0dcWRb4FFZwE6hPur261PnN69wjsxN1w00JOP4hrdFHi6BKny4PQrSg2vBfnbLq12H/Jl2r+mESMsi6zCa+jqJfbJzHCZsacWIhIcAD+t+2XFRy2QN/vD06XLtvi6BE5oezJJpSl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d22I2vqThzDgRnEL47lGXL4Q5dhLqYZgRco3uoZ91b8RqRiIoedms/Xf8+EszZiyNbyhkZPsR9FSFY0Aby8A5i8xXw9n6dGe6GGqAamF/bN9/mugatdKjtFji9lPvBy4kX9ThniAurmiVaqGhOV1uw5UDkuHC8tk6qvfmUg4mz33s94DbQqnimTh8ezHWGXC8F+ss254Z1yjZkEdeqBneSQ/9YHfx1MwiSfH+S3XhXtEMy7tPdFFLr/+kp7TDEFPb/Z3dNl44Esxk8HSSkrYvSciHArH9xuT9VeqOihtbPypEJu8QwHtAafFMxvO6gKZHtSUm4WRjo7buJ6qmJVEdA0J7T8Gvk6rLaVLtlMz23TaF2+g60Ksui6kM/vxSnbeYwGIQwey3rB0yI5H4PyCaA/+Us3jZw/e0OncuIZIjlnhAJu2fHc5P/mCIEU1uw73jdbBEd+qpXitmjCwFT/ac1ke4G255podCbhBUHEa0gXZFVl+EBzk3tNwCrUdYSjorl6THaosF4DfGsO4pcfCRBYZLXvl79hrbR9d2fy1ahNysPE1D3TPombOdCBGniP6IU7eF3y1p3u21v7/F2N1shFNx33r+jIIACXq7VYQAAAAA) And it works just fine when you press it. What we have done there is we have passed it an anonymous function as a value directly, and the browser will know to call this function itself. *(There are upsides and downsides of doing it that way which we will get into another time.)* What you need to know is that a **callback function is a function that gets passed into another function and then it is called by the browser at a later point in time.** ### Timer Callback The other example we have is a timer callback. There are a couple of ways to do timers *(we will go over all of them in the future)* but the simplest is `setTimeout()`. ``` setTimeout(); ``` It takes two things: 1. a function to call after a certain amount of time 2. a duration in milliseconds (after how long should I run this) So let's do `1000` milliseconds which is one second later. ``` setTimeout(wes.yellHi, 1000); ``` If we refresh the page, after one second, it will log HEY WES. You can also pass it an anonymous function. ``` setTimeout(function () { console.log("DONE TIME TO EAT"); }, 1000); ``` After a second that will log "DONE TIME TO EAT". You can pass those as arrow functions as well. ``` setTimeout(() => { console.log("DONE TIME TO EAT"); }, 1000); ``` That will work the same\! 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](https://github.com/wesbos/wesbos/tree/master/src/content/javascript/02-functions/15-different-ways-to-declare-functions/15-different-ways-to-declare-functions.mdx)
Shard63 (laksa)
Root Hash14044395047323946463
Unparsed URLcom,wesbos!/javascript/02-functions/different-ways-to-declare-functions s443