You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
In this lesson, we'll introduce functions and cover how to create and executethem. There are no tests, but be sure to follow along with the examples.
Getting Started
To start,fork and clone this lesson into your local environment.
Once the lesson has been forked and cloned, navigate into the lesson directoryin the terminal, then runcode . to open the files in Visual Studio Code.(If you are using a different text editor, the command will be different.) Youwill be writing your code in theindex.js file, and running it by enteringnode index.js in the terminal. Remember that you need to save the file beforerunning the command.
Writing and Calling JavaScript Functions
So far, our programs have consisted of writing individual lines of code directlyinto a REPL. This is a great way to test out JavaScript functionality and to geta feel for how it handles different values and operations, but it's not superextensible. What if, for example, we wanted to log"Hello, world!" a bunch oftimes? We could write the statement out repeatedly:
But that quickly gets tiresome, and it's easy to see how even small programswould come to rivalWar and Peace in length.
The good news is, there's a better way! We can use a function!
Functions are ways of giving instructions to the JavaScript interpreter that canbe reused over and over again bycalling the function. Functions are the basicbuilding blocks of programming in many languages (although they aren't alwayscalledfunctions), serving both to store the instructions for how to perform acertain task, and to help organize the code in our programs. By using functions— and giving them meaningful names — we can make our code easier toread, debug and maintain.
In JavaScript, functions are written with thefunction keyword:
functiondoNothing(){}
As you can see, when we declare a function, we start with thefunctionkeyword, followed by a name for the function (in this case,doNothing),followed by a pair of parentheses. Next comes a pair of curly braces, whichcontains the code to be executed when the function is called. In this case, thefunction, as its name implies, doesn't do much. Copy the function intoindex.js and then execute it by runningnode index.js in the terminal.
...
Anything happen? No? Good! This isn't surprising because even though we declaredthe function, we didn't give it any instructions. (Conventionally, a functionthat does nothing is called a "noop" (pronounced "no op") — sometimes theycome in handy!)
Let's declare another function and this time give it something to do. Asmentioned above, we put the code that we want to be executed when our functionis called inside the curly braces — this is called thefunction body.
functionsayHello(){console.log("Hello!");}
Here we have a function calledsayHello; its body readsconsole.log('Hello!');. Add this function toindex.js and then execute itagain.
What happened this time? Still nothing? That's because the code above is justthefunction declaration. So far, all we have done isdefine the function.In order to actually execute the code in the function body, we have tocallit. To call the function, we simply type the name of the function followed by().
Add the following toindex.js, after the function declaration:
sayHello();
Now when you execute the code, you should seeHello! printed in theterminal!
Note: We've just learned that, in order for the code in a function to beexecuted, the function must be called. Any time you're trying out code, eitherin a REPL or in your local environment, you'll need to add the function call,as we did above, before executing the code. Forlabs, however, you willgenerallynot need to do this yourself. The tests will take care of it foryou.
Saying hello
Let's write a function to say hello to Guadalupe — be sure to follow along!
We can stack all three of these calls inindex.js and, when we execute thecode, we should see all three messages output in the terminal.
While these functions are undoubtedly useful, they're only useful if we onlytalk to Guadalupe, Liz, and Samip. Every time we want to greet someone new (oruse a greeting other than "Hello," for that matter), we need to define a newfunction.
What if there was some way to take what's similar about these functions —the fact that they all callconsole.log() with "Hello," a name, and anexclamation point — and substitute what's different (the name) as we go?
Turns out, we can! We can use something called anargument to pass informationto a function.
Understandarguments andparameters
Arguments give us a way to pass information into a function to make ourfunctions more flexible. We pass the argument at the time that wecall thefunction, by including it inside the parentheses after the name of the function:
functiondoSomething(thing){console.log(thing);}doSomething("anything");// passing the argument 'anything' into our function
Try this out with a few different arguments. You'll see that whatever value wepass in when wecall the function is what the function logs. Pretty cool,right?
We can easily extend this to our "say hello to" example; by using an argument,we no longer need a separate function for each person we want to say hello to:
functionsayHelloTo(firstName){console.log(`Hello,${firstName}!`);}sayHelloTo("Guadalupe");// "Hello, Guadalupe!"sayHelloTo("Jane");// "Hello, Jane!"sayHelloTo("R2-D2");// "Hello, R2-D2!"sayHelloTo(1);// "Hello, 1!"// ^ Note that in the above, JavaScript coerces the number 1 to the string "1"
In the example above, you may have noticed that there's also something insidethe parentheses in the functiondeclaration:function sayHelloTo(firstName).This is called theparameter, in this casefirstName. Aparameter is aplaceholder that stores whatever value gets passed in as anargument. Forexample, when we run the function callsayHelloTo('Guadalupe'), the value of theargument, 'Guadalupe', gets stored in the parameterfirstName. Then, inside thefunction body, we access that value by using the parameter name, interpolate itinto the string, and log the string to the terminal.
Essentially, the arguments are the actual values that we pass to the function,and the parameters are the named references where we store those passed-invalues. An argument can be any JavaScript expression — any piece ofJavaScript code that evaluates to a value — from something as simple as5 or'Avi' to something as complex as an entire function.
Defining a parameter in our function declaration ensures that the argument getsstored as a local, function-level variable that's available anywhere in thefunction body. We access the value simply by using the name of the parameterthat it's stored in.
Note that we can only access parameters within the body of the function. Tryaddingconsole.log(firstName) to the end of theindex.js and running thecode. You should see aReferenceError telling you thatfirstName is notdefined. This relates to a very important concept in JavaScript,variablescope.
Variable Scope
Variables in JavaScript exist within a particularscope. For example, if avariable is defined in a function — whether it's defined as a parameter orinside the body of the function — it can only be accessed inside thatfunction.
Variables can also be declared in theglobal scope, i.e., outside of anyfunction. These variables will be accessible (and can potentially beoverwritten) everywhere within the program. As a general rule, it is best toavoid global variables as much as possible because they can lead to bugs thatcan be difficult to track down. Using local variables instead makes it easier tokeep track of the values of your variables and makes your code easier to debugand maintain.
The topic of scope in JavaScript is quite complex. You will learn more about it,and its implications, later in the course.
Saying something new
What if we want our function to say something other than "Hello"? Well, we canmove the greeting to a parameter as well:
Add the above to yourindex.js file along with the function callsay("Goodbye", "Julio");. When you run the code you should see "Goodbye,Julio!" written out to the terminal.
Order of Arguments
What if we reversed the order of our arguments? Try this function call:
say("Julio","hello");
You should now see "Julio, hello!" in the terminal. It looks like the name isnow stored in thegreeting parameter and the greeting is stored in thenamevariable. We can verify that by adding a couple moreconsole.log()s:
When you run this using the function call above, you should see this:
firstName: hellogreeting: JulioJulio, hello!
You've just illustrated an important point:the parameter names only havemeaning to us, the programmer; JavaScript assigns values to parameters basedsolely on the order of the arguments that are passed.
Return Values in JavaScript
These functions we've been coding are pretty cool, but they don't actually do awhole lot — mostly they just print things to the terminal. We've seen howwe can make them a little bit more dynamic with arguments, but how do we makethem do something for us? For example, we might want to create a functionadd() that allows us to add together two numbers. Enter the following inindex.js:
functionadd(x,y){returnx+y;}
When we return inside a function, we're giving that value back to the worldoutside the function. Let's add the function calladd(1, 2) and run the code.Wait — nothing happened! What's going on here? Well, our function isreturning the value of the sumx + y but we can't see that because we aren'tdoing anything with it. So let's use our handy developer tool,console.log(),to see what it's returning. Rerun the code after modifying your function call asfollows:
console.log(add(1,2));
See that? We got3 back! What if we pass 80 and 9000 as our arguments instead?Whoa! We got 9080!
Let's unpack what's happening here. We'recalling ouradd() function,passing in two numbers as the arguments. The function isreturning the valueof the sum of the two arguments, and we'relogging that result in the terminalso we can see it. The difference between this and what we were doing before— having thefunction itself log something to the terminal — mayseem subtle, but it's actually quite important. Let's look at another example.Be sure to follow along.
Let's rewrite oursay() function from above so that now instead ofconsole.log()-ing what it says, it returns it.
Now when we callconsole.log(say("Hello", "Liz")); we'll seeHello, Liz!, just as we did before. But what if we try logging the result ofcalling theoriginal version of the function:
Nowconsole.log(say("Hello", "Liz")); will result in the following:
Hello, Liz!undefined
The first line comes from theconsole.log() inside the function body, and thesecond line comes from logging the result of the function call. What this showsus is that this version of our functiondoes not have a return value! Thisis because aconsole.log() doesn't return anything — it just writessomething out for the developer to see.In JavaScript, in order to have ourfunction return a value, we need to use thereturn keyword.
We can also see this if we go back to ouradd() function, and remove thereturn keyword:
functionadd(x,y){x+y;}
Now if you call the function and log the results:
console.log(add(1,2));
you'll see that the function has no return value. Our function is doing theaddition but we can't do anything with the result, which makes it prettyuseless. Be sure to add thereturn keyword back in.
Setting up your function to return a value means that value is available to beused elsewhere in your program. So how might we use the return value of ouradd() function? Let's say we're creating a simple calculator function. Ahigh-level outline of how it could work might be:
the calculator function asks the user to enter two numbers they want to beadded together,
the values are stored into variables (num1 andnum2, perhaps),
the function then calls theadd() function, passingnum1 andnum2 asarguments,
theadd() functionreturns the sum
the calculator function returns a message to the user telling them what thesum is.
Note what's happening in step 3: our calculator function iscalling our addfunction. This is an important thing to know about functions: they can be calledby other functions! Eventually we'll want our calculator to do more than justadd. Rather than build one very long function that contains code for adding,subtracting, multiplying, etc., we canencapsulate the code for each operatorinto its own function and call them.
The code that calls theadd() function and creates the message might looksomething like this:
constsum=add(num1,num2);constmessage=`The sum of your numbers is:${sum}.`;
Or, equivalently:
constmessage=`The sum of your numbers is:${add(num1,num2)}.`;
Themessage could then be written out to the screen.
One Last Point Aboutreturn
There's one additional thing it's important to know aboutreturn. If we wantedto bothreturnand log a string in oursay() function, we might trywriting:
functionsay(greeting,firstName){return`${greeting},${firstName}!`;console.log("I was called!");}
Let's call the function and log the result:
console.log(say("Howdy","partner"));
When you run that code, the return value is logged, but theconsole.log()inside the function body does not execute!
This is becausereturnends the execution inside the function. Nothingafter the line with thereturn will be executed.
Top Tip: Take a look at the above code inindex.js. Depending on whichtext editor you're using, you may see that the line with theconsole.log()is "grayed out." This is the text editor giving you a hint that that line ofcode is unreachable.
To both log and return like we want to, we can switch the order around:
functionsay(greeting,firstName){console.log("I was called!");return`${greeting},${firstName}!`;}
Now if we rerun the code, we should see the output of bothconsole.log()s.
Your turn!
Try rewriting some of the functions that we've written in this lesson to getused to the difference betweenreturn-ing and printing (console.log()-ing)to the terminal. Try writing a function of your own that returns something.