βΉοΈ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions |
| Last Crawled | 2026-04-16 14:10:12 (3 days ago) |
| First Indexed | 2021-06-09 11:12:17 (4 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Different Ways to Declare Functions - Wes Bos |
| Meta Description | One thing you will hear often when getting into JavaScript is that functions are "first-class citizens". |
| Meta Canonical | null |
| 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 | [](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

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

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:
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.

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:
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

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

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
["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

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:
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.

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:
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) |
| Shard | 63 (laksa) |
| Root Hash | 14044395047323946463 |
| Unparsed URL | com,wesbos!/javascript/02-functions/different-ways-to-declare-functions s443 |