Evaluating expressions
Learning Objectives
💡Tip
Computers work by storing and performing operations on data.
Computer programs are built from many expressions. We must understand how expressions are evaluated to understand how computer programs are executed.
We can take an expression like 36 * 45 and ask what it evaluates to. If we know what the * operator represents (multiplication) and if we understand the arithmetic rules represented by the operation we can evaluate this expression ourselves.
Happily, computers can evaluate expressions for us.
NodeJS is an application that runs JavaScript programs. In other words, NodeJS can understand and execute programs written in JavaScript. One feature of Node is the REPL.
📝Note
REPL is a special type of program that stands for:
- Read - Users enter some code that Node will read
- Evaluate - Node will then evaluate this code
- Print - Node will print the result to the terminal
- Loop - Node will loop back to the beginning and prompt users to input some more code
With a REPL we can run pieces of code and look at what happens.
We input JavaScript instructions that are then executed by NodeJS. The REPL replies with, or prints out, the result of this execution.
Type each of the following expressions into the REPL one at a time and then press enter to check the result.
10 + 3232 / 10🕹️Activity
In this activity, you’ll check you’re ready to use the Node REPL on your machine.
- Open the terminal on your computer
- Check you’ve got Node installed on your computer
- Start the Node REPL in your terminal
- Enter the expressions and evaluate them using the Node REPL
If you don’t know how to do any of the steps above, then try searching for an appropriate command online. Searching for things when you’re stuck is super important part of being a developer!
🕹️Activity
Create your own expressions and enter them into the Node REPL.
🧠 Before you type in the expressions, predict what the REPL output will be. Write your prediction down and compare it to the outcome.
Prep Directory
Learning Objectives
We will provide some code examples as you progress through the course but you will also write a lot of code yourself. You’re going to need somewhere in your system to store it all.
Create a working directory for the module
- Fork the coursework module (always linked in every backlog), clone it to your laptop and open it in VSCode.
- In your VSCode terminal, navigate to the root of your project directory.
- Create a new directory called
prepto store all the files you’ll be working on for this module.
As you work through the module, you’ll be creating files in this directory to code along with the prep content. You are expected to code along with the prep content.
You will need to do this at the start of every module. We suggest adding further sub-directories for each sprint but it’s up to you to organise your files in a way that suits you. For more complex problems you may need to create further sub-directories and write the code there. Try making notes as you go to document the process. Having your own notes will be very useful if you need to remind yourself how to do something in future!
Saving expressions
Learning Objectives
In programming we often want to reuse our work. Consider the string: "Hello there"
Suppose we want to create different greetings for different people, like: "Hello there, Alicia" or "Hello there, Barney"
We can use a variable to store this string and reuse it. A variable is a label for a piece of data. We assign a piece of data to a label and then refer back to this label, in place of the data.
Declaring variables
We can create a variable in our program by writing a variable declaration. A declaration is an instruction that binds an identifier to a value, like this:
const greeting = "Hello there";Break down the different syntactic elements of this variable declaration:
constis a keyword used to indicate we’re creating a variable.greetingis the identifier - it can be used to refer to a variable after it has been declared.=is the assignment operator. It means assign to the labelgreetingthe value of the expression on the right hand side."Hello there"- this is the expression whose value we’re assigning to the labelgreeting.
✍️Exercise: Declare a variable
greeting.js. Open the file in VSCode and declare a variable called greeting like we did above.Accessing variables
Our data is stored in a variable, so how can we use it again later?
To access the data stored in a variable we just need to type the variable’s name. When our code is executed the appropriate value will be inserted and the expression will be evaluated. Try it now with your new variable:
console.log(greeting);"Hello there" has been printed to the terminal even though we didn’t explicitly write that in the code.
Using variables in expressions
Accessing variables can form part of complex expressions. Let’s add a second variable called name to our program. We’ll also add this variable to our console.log call so we print the greeting and the name together.
const greeting = "Hello there";
const name = "Alicia";
console.log(`${greeting}, ${name}`);We just used backticks to create a template literal.
A template literal places ${expressions} inside strings;With template literals, we can insert expressions into strings to produce new strings. Any time we want to reference a variable inside a template literal we use a dollar sign $ and a set of curly braces {}. We can put any expression (e.g. a variable name) inside the curly braces. The value that expression evaluates to is then placed inside the string.
When an operation uses an expression, that expression is immediately evaluated, and how it was written is forgotten about. Each of these expressions evaluates to the same thing:
"Hello there, Alicia";
`Hello there, ${name}`;
`${greeting}, ${name}`;
greeting + ", " + name;📖Definition: String literal
In the first example we don’t use a variable or a template to create a string. Instead we write a string "Hello there, Alicia".
A sequence of characters enclosed in quotation marks is called a string literal. "Hello there, Alicia" is a string literal.
Similarly, 10 is a number literal.
Reassigning a variable
Let’s say we want to greet people in a different way. That would mean changing the value of our greeting variable. This is a very common thing to do, in fact many of the programs you write will need you to do this.
We reassign a variable using the = operator:
const greeting = "Hello there";
greeting = "Good morning"If we try to run our code now we’ll see an error (more on these at the end of this sprint). What went wrong?
The const keyword means that our variable is a constant - we can’t change its value! If we need to reassign a variable we need to use the let keyword when declaring the function instead.
let greeting = "Hello there";
greeting = "Good morning"Now it works!
The first line of this block is the variable declaration, the second line is a statement. Note that we don’t need to use let again when reassigning the variable.
Declarations and statements
Learning Objectives
A variable declaration is an example of a
let versionNumber = "2.0.0"; // declaration
versionNumber = "2.0.1"; // statement
The code above has one variable declaration and one statement.
- The first line is a declaration - creating a variable
versionNumberwith a value of"2.0.0" - The second line is a statement -
reassignment🧶 of the value of🧶 reassignmentReassignment means changing the value associated with an identifier. versionNumberto"2.0.1"
In this example, we’ve used the let keyword to declare a new variable.
The let keyword allows us to create new variables like the const keyword.
However, we can reassign the value of a variable that is declared with the let keyword.
If we’d used const to declare versionNumber, we wouldn’t be allowed to reassign it a new value.
In JavaScript, we build up programs by combining declarations and statements.
Functions
Learning Objectives
When we are writing programs we often find ourselves needing to do the same thing over and over again. Think back to our password checker from the previous sprint: there are lots of places where you need to enter a password!
We could re-write the code to check a password every time we needed to use it but that wouldn’t be very efficient. It would take a long time to write and there’s a chance we could make a mistake and introduce a bug. It would be much easier if we could write the code once and reuse it anywhere it was needed.
This applies to any repeated process. Let’s look at how we can round a decimal to the nearest whole number.
Reusing instructions
There is no operator for rounding a number in JavaScript, but we will want to round numbers again and again. We can use a function to do this. A function is a reusable set of instructions.
We don’t need to declare this function ourselves. JavaScript comes with many built-in functions, ready for us to use, and rounding is so common that there is already one for it: Math.round.
Functions usually take inputs and then apply their set of instructions to the inputs to produce an output. Math.round takes a number as an input and produces the nearest whole number as its output. Because the number is an input, and not fixed inside the instructions, Math.round can round any number we give it, not just 10.3.
✍️Exercise: Using a function
Create a new file to work in and add the following line:
console.log(Math.round);Take a look at the output in the console:
[Function: round]
This is telling us that Math.round is a function.
Calling a function
For our function to work, we need Node to read the instructions and execute them. Execution simply means the computer will run the code with the instructions in it. Update your code to add some extra information.
console.log(Math.round(10.3));Notice the ( and ) brackets after the name of the function and a number inside the brackets. These brackets mean we are calling the function. The number inside the brackets is the input we’re passing to the function.
📖Definition: Calling a function
Math.round(10.3) is a call expression; read this as:
“apply the set of instructions for Math.round to the number 10.3.”
If we type Math.round(10.3) then we get the result 10. So we say that Math.round(10.3) returns 10.
A call expression is an expression which evaluates to the value returned by the function when it is called. So the expression Math.round(10.3) evaluates to the value 10.
If we assign that expression to a variable, or use it in a string, we’ll get the value 10. We can use this value just like any other that we store in a variable.
✍️Exercise: Calling functions
- Update your code from earlier to store the result of calling
Math.round(10.3)in a variable and print the variable usingconsole.log - Create a second variable to store the result of
Math.round(4.2)and print the sum of the two values.
Example solution:
roundedNumber = Math.round(10.3);
console.log(roundedNumber);firstRoundedNumber = Math.round(10.3);
secondRoundedNumber = Math.round(4.2);
console.log(firstRoundedNumber + secondRoundedNumber);Running scripts
Learning Objectives
It’s time to write our first lines of JavaScript!
There are some tools available which will enable us to write code and instantly see the results. These are called REPLs - Read, Evaluate, Print and Loop. These are great for quickly checking something but not very practical for production uses.
Usually our programs will have many instructions which we want to keep and re-run instead of typing them out each time. So we save our instructions in files. We can run these files from the terminal.
We use the node command to run a JavaScript file in the terminal. A JavaScript file ends with the .js file extension.
Let’s suppose we have a file hello_world.js. We run the command node hello_world.js. This terminal command is an instruction to execute the program written inside hello_world.js.
Printing to the terminal
Our first program will print the text “Hello World!” in the terminal. First we need to create a file to work in.
Open a terminal. You can either do this using your Terminal app or in VSCode, it doesn’t matter. Navigate to the prep directory you created in the last section and create a file called hello_world.js.
💡Tip: pwd
pwd command to print working directory if you lose track of where you are in your file system.cd Module-Onboarding/prep # Replace this with your file path if it's different
touch hello_world.jsOpen your new file in VSCode.
JavaScript prints values to the terminal using a function called console.log.
📖Definition: console.log
console usually means a text interface like a terminal. A log is a written record of something that happened.
So console.log will record something that happens in our program and print it to a text based interface.
console.log prints the result of expressions while our program is executing. Usually we will interact with our programs using some sort of graphical interface like a web browser so we won’t use this function often, but it is a very useful tool to help us solve problems in our code. It lets us check what values expressions evaluate to at specific moments of our program execution.
Let’s see how to use console.log . In your hello_world.js file write the name of the function console.log, a set of parentheses () and the message to be printed.
console.log("Hello World!");📝Note: Semicolons
Note that we have added a semicolon (;) at the end of the expression. Different programming languages handle semicolons in different ways: in some languages they are essential, in others including them will cause an error.
JavaScript code will run with or without a semicolon at the end of expressions but it’s good practice to include them. They help to keep your code organised and are helpful for anyone reviewing your code. Plus it’s good practice if you ever use a language like Java where they are required!
Now switch to the terminal and run the file using node:
node hello_world.js💡'Error: Cannot find module
pwd to check you are in the right directory. If not, navigate to teh correct place using cd and try again.We should see the string "Hello World!" logged out in the terminal. Congratulations, you have written your first JavaScript program!
✍️Exercise: Running JavaScript files
Let’s try again from the beginning
- In your terminal, create a new file called
facts.js. - Pick one of your fun facts from the Git sections in the first sprint
- Run the file using Node.
Logging
Learning Objectives
❗Caution
Should combine this with scripts section
Printing to the terminal
To look at values when our program runs, we can use a function called console.log.
💡console.log
console usually means a text interface like a terminal. A log is a written record of something that happened.
So console.log will record something that happens in our program and print it to a text based interface.
console.log logs the result of expressions while our program is executing.
This is very useful for complex programs when we need to check what values expressions evaluate to at specific moments of our program execution.
Let’s see how to use console.log . In a file called example.js, write the name of the function console.log.
console.log;If we run this file with Node, we won’t be able to see anything in the terminal. As with Math.round we need to use the syntax for calling a function. Add brackets after the function name:
console.log("hello there!");We should see the string "hello there!" logged out in the terminal.
Errors
Learning Objectives
Recall that a programming language is a set of rules for writing computer instructions. What would happen if we break those rules?
Let’s take an example:
| |
On line 1, we have a variable declaration, but the string has a missing " We’re not obeying the syntactic rules for JavaScript: the rules for writing expressions, statements and other parts of the language.
When we execute the code above, we get this:
const firstName = "Francesco;
^^^^^^^^^^^
Uncaught SyntaxError: Invalid or unexpected token
We get a SyntaxError message. This error message is telling us that we’ve broken one of the rules of the language. In this case the interpreter didn’t expect to see the semicolon - it needs us to add the missing " before the expression makes sense.
✍️Exercise: Predict and Explain
Each block of code in this activity is broken. Create a new file to test these expressions in, but before you run each block of code:
- Predict the error.
- Explain why the error happened.
const volunteer = "Shadi";
const volunteer = "Abdi";const volunteer = "Shadi";
volunteer = "Hinde";console.log(Math.round(10.3);Percentages
Learning Objectives
Let’s begin with this problem:
Given a decimal number I want to convert it into a percentage format.
For example, given the decimal number 0.5 we return the string "50%". Given the decimal number 0.231 we return the string "23.1%".
Restating the problem
Our function must convert any decimal to a percentage. We have used functions already. Here are some functions we’ve used:
| |
All these expressions are function calls: we’re passing input ("hello world" or 3.141) to the functions (console.log or Math.round) to use their functionality. Math.round and console.log are functions that the JavaScript language designers have written and stored inside the language, because everyone needs them all the time.
No such pre-built function converts any number to a percentage, so we must write our own. We’re going to create a function called convertToPercentage with the following requirements:
Given a number input
When we call convertToPercentage with the number input
Then we get back a string representing the percentage equivalent of that number.
Here are some examples:
| |
| |
Useful expressions
It is often helpful to solve a problem in one specific instance before doing it for all cases.
We’re not going to define our function yet. Instead we will work out what our function should do. Then we’ll define a function which does the same thing.
In programming, we always try the simplest thing first. Let’s consider how to convert just one number to a percentage. Look at this variable declaration:
| |
We want to create an expression for the percentage using the value of decimalNumber. To convert to a percentage, we will multiply the number by 100 and then add a "%" sign on the end.
| |
Recalling template literals, the expression in the curly braces will be evaluated first and then inserted into the string, giving us the percentage string.
Now that we’ve solved the problem of converting a single decimal number to a percentage, let’s practice solving other similar problems using expressions.
Create a new JavaScript file so that you can try running the code for yourself.
Calculating the area and perimeter of a rectangle
In one of these new files, let’s make two variables that describe the dimensions of a rectangle:
const height = 10; // 10 is just an example of a value here - your code should still work if you change this to another value.
const width = 30; // Also just an example - your code should still work if this changes.
Using these variables, let’s calculate the area and perimeter of the rectangle.
We can calculate the area and perimeter by creating expressions that use the height and width variables we just created. Hint: read the links above if you don’t know how to calculate area and perimeter of a rectangle.
Finally, we’ll create two more variables: area and perimeter to store the result of the calculations.
const area = FILL_ME_IN;
const perimeter = FILL_ME_IN;Now, if we change the numbers assigned to height and width, are the area and perimeter values still correct? Try using console.log to print out the value of the variables and then run the script using Node to view the output.
Remember to create a new JavaScript file to run the code for yourself.
Converting pence to pounds
Like the rectangle example, we’ll start by creating a variable to store a price in pence:
const price = 130; // Just an example value. Try changing this value to 0, 10, or 1521, and make sure you still get the right answer from your code.
Now, you should write an expression that calculates the price in pounds. The price in pounds should be shown with 2 decimal places and start with “£”.
Try using console.log to print out the value of price in pounds and then run the script using Node to view the output.
Declaring functions
Learning Objectives
We have our pseudocode from the previous section and it’s time to write our first function.
// Already have the password stored in a variable
// Receive the value which the user entered
// Compare the two values
// If they match print "Correct password entered"
// If they don't match print "Incorrect password, please try again"
It can be tempting to jump straight to the interesting bit, but just like any other set of instructions we need to start at the beginning. In this case we need to declare a variable to store our password.
// Already have the password stored in a variable
const password = "secretword123";
// Receive the value which the user entered
// Compare the two values
// If they match print "Correct password entered"
// If they don't match print "Incorrect password, please try again"
To create our function we need to use a function declaration. In JavaScript we declare functions like this:
function checkPassword(input) {}The function declaration consists of the following syntactic elements:
functionkeyword - begins the function declarationcheckPassword- the name of the function()- any input to the function will go between these parentheses. We still need them if a function has no input, we just leave them empty. We call these inputs parameters.{}- the body of the function is written inside the braces. The code we want to execute will be written here.
📝Functions in other languages
We can add our function declaration to our code.
// Already have the password stored in a variable
const password = "secretword123";
// Receive the value which the user entered
function checkPassword(userInput){
// Compare the two values
// If they match print "Correct password entered"
// If they don't match print "Incorrect password, please try again"
}We changed a couple of things here:
- Instead of
inputwe named our function’s parameteruserInput. Just like any other variable, we want to use meaningful names which tell us what the value represents. - We wrapped the braces
{}around the other steps in the pseudocode. These lines say what we want the function to do, so we place them inside it. - We indented those lines inside the braces. Indentation gives us a visual indication of where a block starts and ends.
Now it’s time to fill in the detail of what our function will do! We have already seen how to do this using an if statement in the last sprint.
✍️Exercise: Complete the body of the function
Add the code to complete the steps described by the pseudocode. Remember to line the comments up with the code!
Example solution:
// Already have the password stored in a variable
const password = "secretword123";
// Receive the value which the user entered
function checkPassword(userInput){
// Compare the two values
if (userInput === password) {
// If they match print "Correct password entered"
console.log("Correct password entered");
} else {
// If they don't match print "Incorrect password, please try again"
console.log("Incorrect password, please try again");
}
}Now we have defined our function we can call it in exactly the same way as we called Math.round() before. Try it with different inputs to check that it works!
checkPassword("secretword123");
// "Correct password entered"
checkPassword("WrongGuess99");
// "Incorrect password, please try again"
📖Definition: Arguments
When we call a function we have a special name for the values we place in the parentheses: arguments. When we provide a value as an input we are passing an argument to the function.
There is an important distinction between parameters and arguments:
- A function’s parameters are the placeholder values used when we define the function
- A function’s arguments are the actual values in the program when we call the function
Playing computer
Learning Objectives
To understand how convertToPercentage works we must build a mental model of how the computer executes our code. To build this model, we use a method called
We will use an interactive code visualiser to play computer.
🕹️👣 Step through
In a JavaScript program, each line is an instruction that will have some effect. For example, a line of code with a variable declaration means “store a new variable with this value in memory”. In the interactive widget, arrows are used to show which line just executed and which line is next to be executed.
Click next to see what happens when the computer executes the following program. Pay particular attention to what happens when the function convertToPercentage is called.
🖼️ Global frame
As we step through the program, we keep track of two things: memory and the line that is being currently executed. We keep track of this information using a
The global frame is always the first frame that gets created when our program starts executing. It is like the starting point for our program, the place where code gets executed first. When we run the code above, decimalNumber and convertToPercentage are both stored in the global frame.
🖼️ Local frame
💡recall
Whenever we call a function a new frame is created for executing the code inside that function. In the example above, we call the function convertToPercentage on line 7 and then a new frame is created for convertToPercentage. Inside the convertToPercentage frame, the computer executes the instructions inside convertToPercentage, storing new variables in memory and keeping track of the current line that is being executed.
Scope
Learning Objectives
At the moment our password checking function does what we need it to but is quite limited. The only way it can let us know if the input was correct or not is by printing a message, but what if another part of the program needs to know?
For that to happen we will need to store the response in a variable, so let’s make some changes to our code:
const password = "secretword123";
function checkPassword(userInput){
let response;
if (userInput === password) {
response = "Correct password entered";
} else {
response = "Incorrect password, please try again";
}
}Now we can call our function then try printing response:
checkPassword("secretword123");
console.log(response);It looks like we have a problem though…
ReferenceError: response is not defined
We definitely did define response though, it’s right there above the if statement! It’s the only variable which throws this error: if we print password the value will be displayed. So why does it work for one and not the other?
We get an error because of the variable’s scope. Scope determines where a variable can be accessed from in our code. When we define passwordChecker we also define a local scope - the block of code enclosed inside passwordChecker’s function body. This means any variables we declare inside that local scope can only be accessed within the same block. If we attempt to reference a variable from outside the scope where it was declared we get a ReferenceError.
The response variable is declared inside passwordChecker’s local scope so when we try to print it the ReferenceError is thrown. The password variable is declared outside the function’s local scope so we can access it without the error being thrown.
Global Scope
There are two ways in which we could fix this. The first is to move the response declaration outside of the function. That means it is no longer within the function’s scope but that could cause some problems for us in future. What happens if the code in the function isn’t executed? Our variable would always have the value undefined and we may not be prepared to handle that.
The second is to remove the declaration altogether and handle declaration and assignment at the same time in the if block. TRy it now and see what happens!
const password = "secretword123";
function checkPassword(userInput){
if (userInput === password) {
response = "Correct password entered";
} else {
response = "Incorrect password, please try again";
}
}
checkPassword("secretword123");
console.log(response);No error, and the correct value is printed. So why does this work?
When we declare a variable using const or let it gives the variable local scope. When we don’t use a keyword the variable has global scope instead. Now there are no restrictions, the variable can be accessed from anywhere. That doesn’t sound very secure though, does it?
We have a stand-off: on one side our code is secure but we can’t access the value we need, on the other we can access the value but so can everything else. We need to make some changes to our function to fix this.
Returning from a function
Learning Objectives
We need a way to access the value that is created inside checkPassword. To access values created inside functions, we use the return keyword. When we return something from a function we make it available at the point the function was called.
Let’s undo our global variable changes from the last section and add a return statement to the function:
const password = "secretword123";
function checkPassword(userInput){
let response;
if (userInput === password) {
response = "Correct password entered";
} else {
response = "Incorrect password, please try again";
}
return response;
}We haven’t quite fixed everything though. If we call the function and try to print response like before we’ll still get a ReferenceError.
Using the output
We sometimes refer to the value returned by a function as its output. We can store that output in a variable.
const output = checkPassword("secretword123");Now the value returned by our function is stored in the output variable and can be handled just like any other variable. Let’s try printing it to check everything worked:
console.log(output);
// "Correct password entered"
Success!
Reusing the function
Learning Objectives
Our goal is for convertToPercentage to be reusable for any number. To check this goal, let’s call convertToPercentage with different arguments and check the return value each time:
| |
When we execute this code we want to log the target output for each input: 0.5 and 0.231:
50%
23.1%However, given the function’s current implementation, we get the following logs:
50%
50%🌍 Global scope
At the moment, decimalNumber is in the
🎮 Play computer
Play computer and step through the code to check why we get the output below:
50%
50%
Parameterising a function
Learning Objectives
Our checkPassword function is nice and reusable now with its ability to check any value we pass to it as an argument, but in practice we will see lots of functions which need more than one piece of information to do their job. How we provide this information is critical. In a future sprint we will look at ways of testing our code to ensure we have set everything up correctly but we can avoid a lot of problems by paying close attention to how we use our functions.
Let’s create a new function to work with for this example. In a new file let’s define a function which will print a greeting for someone with a different message depending on what time of day it is.
function greet(timeOfDay, name){
console.log(`Good ${timeOfDay}, ${name}.`);
}Ordering
If a function expects to receive two pieces of information then it expects to receive them in the order they are defined. In our example we have said the first argument greet receives will represent the timeOfDay parameter and the second argument will be for name. We can test it to see what happens:
greet("afternoon", "Colin");
// "Good afternoon, Colin."
✍️Exercise: Changing the order of arguments
Try to predict what will happen if we swap the order of the arguments when calling the function.
Answer:
greet("Colin", "afternoon");
// "Good Colin, afternoon."
As far as the function is concerned everything is fine: it needed two pieces of information and it got two, so it’s happy. The output doesn’t make sense to us as users though!
The output may not make much sense, but it could be worse. What might happen if one of the arguments was expected to be a number? If we’re not careful when passing arguments we can cause errors by trying to do something we’re not able to do to a value.
Wrong number of arguments
Some languages are very strict about passing the right number of arguments to a function when it is called. JavaScript is not one of those languages. JavaScript is quite forgiving and will do its best with what we give it.
✍️Exercise: Missing arguments
Try to predict what will happen if we omit the second argument when calling our function. Hint: think about the value of a variable which we declare but never initialise.
Answer:
greet("afternoon");
// "Good afternoon, undefined."
When the function is called timeOfDay and name are both declared but we only have a value to assign to timeOfDay. name will remain undefined while the code is executed.
Now predict what will happen if we omit the first argument.
Answer:
greet("Colin");
// "Good Colin, undefined."
Remember that ordering matters. The interpreter will assign the first value it receives to the first parameter, it doesn’t know there was meant to be something else there first.
✍️Exercise: Extra arguments
Try to predict what will happen if we pass a third argument to our function.
Answer:
greet("afternoon", "Colin", 2026);
// "Good afternoon, Colin."
The function only expects two pieces of information and once it has them it doesn’t care about anything else we give it. Remember about the ordering though! It only expects two values and it will take the first two values, whatever they are.
Default values
There are many reasons why we might be missing a piece of data which is actually quite important for our program. In production code we would usually have several checks in place to ensure we didn’t even try to call our function if something was missing but it never hurts to have another one.
In our greet example we were able to get away with the missing value because we can still print undefined but that won’t always be the case. We can’t add two numbers together if once of them is undefined, for example. To help avoid this we can assign default values to parameters when we define a function. If a function expects to receive a value when it is called but doesn’t it will substitute the parameter’s default, avoiding the value being undefined.
✍️Exercise: Assigning defaults
Research how to assign default values to a parameter and update the function definition so that it prints “user” instead of “undefined” if the name argument is not passed. Hint: The functions page of the MDN docs could be a good place to start!
Solution:
function greet(timeOfDay, name="user"){
console.log(`Good ${timeOfDay}, ${name}.`)
}Solving Problems with Functions
Learning Objectives
To get the most out of this workshop - don’t just watch, code along 💻 You can use the code samples below as a starting point.
Exercise 1
// Write a function that will calculate the area of a rectangle
// given it's width and height
let width = 3;
let height = 4;
function calculateArea() {
const area = width * height;
}
console.log(area);Exercise 2
function capitaliseFirstLetter(name) {
console.log(name[0].toUpperCase() + name.substring(1));
}
function createGreeting(name) {
const result = capitaliseFirstLetter(name);
return `Welcome ${result}`;
}
const greeting = createGreeting("barath");
console.log(greeting);