0% found this document useful (0 votes)
692 views107 pages

2

Here are the key steps to register runners for a race: 1. Define variables to track a runner's age, registration status (early or late), and race details like number and start time. 2. Use conditional statements like if/else to assign each runner a race number and start time depending on their age and registration status. 3. Output the runner's details to confirm their registration is complete. This allows the program to systematically register runners, place them in the appropriate categories, and provide their race information so they know the logistics on race day. Conditionals are essential for applying different rules and yielding different outputs based on users' unique attributes and decisions.

Uploaded by

ilias ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
692 views107 pages

2

Here are the key steps to register runners for a race: 1. Define variables to track a runner's age, registration status (early or late), and race details like number and start time. 2. Use conditional statements like if/else to assign each runner a race number and start time depending on their age and registration status. 3. Output the runner's details to confirm their registration is complete. This allows the program to systematically register runners, place them in the appropriate categories, and provide their race information so they know the logistics on race day. Conditionals are essential for applying different rules and yielding different outputs based on users' unique attributes and decisions.

Uploaded by

ilias ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 107

let wordCount = 5;

if (wordCount) {

console.log("Great! You've started your work!");

} else {

console.log('Better get to work!');

let favoritePhrase = '';

if (favoritePhrase) {

console.log("This string doesn't seem to be empty.");

} else {

console.log('This string is definitely empty.');

}
Hins: Since we reassign tool to a non-empty string, the value
of writingUtensil becomes 'marker' and 'The marker is mightier than the sword'  is

logged to the console.

let tool = '';

tool='marker';

// Use short circuit evaluation to assign writingUtensil variable below:


let writingUtensil=tool||'pen';

console.log(`The ${writingUtensil} is mightier than the sword.`);

Hints: The structure of a ternary operator looks like:

condition ? firstExpression : secondExpression


let isLocked = false;

isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to
open the door.');

let isCorrect = true;

isCorrect ? console.log('Correct!') : console.log('Incorrect!');

let favoritePhrase = 'Love That!';

favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");

another condition:

let isLocked = true;

isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to
open the door.');

let isCorrect = false;

isCorrect ? console.log('Correct!') : console.log('Incorrect!');

let favoritePhrase = 'Love That!';


favoritePhrase != 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");
Hints:

Add a final else if statement that checks if season is equal to 'summer'.

Inside the code block of the else if statement you just created, add
a console.log() that prints the string 'It\'s sunny and warm because it\'s summer!' .

let season = 'summer';

if (season === 'spring') {

console.log('It\'s spring! The trees are budding!');

} else if(season === 'winter') {

console.log('It\'s winter! Everything is covered in snow.');

} else if(season === 'fall') {

console.log('It\'s fall! Leaves are falling!');

} else if(season === 'summer') {


console.log('It\'s sunny and warm because it\'s summer!');

} else {

console.log('Invalid season.');

Switch case :

let athleteFinalPosition = '3rd place';

switch (athleteFinalPosition) {

case 'first place':

console.log(' medel awarede');

break;

case 'second place':

console.log('end mdelel awarded');

break;

case '3rd place':

console.log('3rd awareded');

break;

default:

console.log('Invalid item');

break;

}
 The switch keyword initiates the statement and is followed by ( ... ),
which contains the value that each case will compare. In the example,
the value or expression of the switch statement is groceryItem.
 Inside the block, { ... }, there are multiple cases. The case keyword
checks if the expression matches the specified value that comes after it.
The value following the first case is 'tomato'. If the value
of groceryItem equalled 'tomato', that case‘s console.log() would run.
 The value of groceryItem is 'papaya', so the third case runs— Papayas are
$1.29 is logged to the console.
 The break keyword tells the computer to exit the block and not execute
any more code or check any other cases inside the code block. Note:
Without break keywords, the first matching case will run, but so will
every subsequent case regardless of whether or not it matches—
including the default. This behavior is different from if/else conditional
statements that execute only one block of code.
 At the end of each switch statement, there is a default statement. If
none of the cases are true, then the code in the default statement will
run.
Instructions

1.
Let’s write a switch statement to decide what medal to award an athlete.

athleteFinalPosition isalready defined at the top of main.js. So start by


writing a switch statement with athleteFinalPosition as its expression.
let athleteFinalPosition = 'first place';

switch(athleteFinalPosition){
case 'first place':
console.log('You get the gold medal!');
break;
case 'second place':
console.log('You get the silver medal!');
break;
case 'third place':
console.log('You get the bronze medal!');
break;
default:
console.log('No medal awarded.');
break;
}2.
Inside the switch statement, add three cases:

 The first case checks for the value 'first place'


o If the expression’s value matches the value of
the case then console.log() the string 'You get the gold
medal!'
 The second case checks for the value 'second place'
o If the expression’s value matches the value of
the case then console.log() the string 'You get the silver
medal!'
 The third case checks for the value 'third place'
o If the expression’s value matches the value of
the case then console.log() the string 'You get the bronze
medal!'
Remember to add a break after each console.log().
Stuck? Get a hint
3.
Now, add a default statement at the end of the switch that
uses console.log() to print 'No medal awarded.'.

If athleteFinalPosition does not equal any value of our cases, then the


string 'No medal awarded.' is logged to the console.

Remember to add the break keyword at the end of the default case.

let athleteFinalPosition = 'first place';

switch(athleteFinalPosition){

case 'first place':

console.log('You get the gold medal!');

break;

case 'second place':

console.log('You get the silver medal!');

break;

case 'third place':

console.log('You get the bronze medal!');

break;

default:

console.log('No medal awarded.');

break;

}
CONDITIONAL STATEMENTS
Review
Way to go! Here are some of the major concepts for conditionals:

 An if statement checks a condition and will execute a task if that condition


evaluates to true.
 if...else statements make binary decisions and execute different code blocks
based on a provided condition.
 We can add more conditions using else if statements.
 Comparison operators, including <, >, <=, >=, ===, and !== can compare two values.
 The logical and operator, &&, or “and”, checks if both provided expressions are
truthy.
 The logical operator ||, or “or”, checks if either provided expression is truthy.
 The bang operator, !, switches the truthiness and falsiness of a value.
 The ternary operator is shorthand to simplify concise if...else statements.
 A switch statement can be used to simplify the process of writing multiple else
if statements. The break keyword stops the remaining cases from being checked
and executed in a switch statement.

LEARN JAVASCRIPT
Magic Eight Ball
You’ve learned a powerful tool in JavaScript: control flow! It’s so powerful, in fact, that it
can be used to tell someone’s fortune.

In this project we will build the Magic Eight Ball using control flow in JavaScript.

The user will be able to input a question, then our program will output a random
fortune.

If you get stuck during this project or would like to see an experienced developer work
through it, click “Get Unstuck“ to see a project walkthrough video.

let userName = 'ilias ahmed';

userName? console.log(`Hello, ${userName}.`) : console.log('hello!');


let userQuestion = 'can u question to me?';

console.log('the user asked :$(userQuestion)');

let randomNumber = Math.floor(Math.random() * 8);

let eightBall = '';

switch (randomNumber){

case 0:

eigthBall = 'It is certain';

break;

case 1:

eightBall = 'It is decidedly so';

break;

case 2:

eightBall = 'Reply hazy try again';

break;

case 3:

eightBall = 'Cannot predict now';

break;

case 4:

eightBall = 'Dont count on it';

break;

case 5:

eightBall = 'My sources say no';

break;
case 6:

eightBall = 'Outlook not so good';

break;

case 7:

eightBall = 'Signs point to yes';

break;

console.log('User question: ' + userQuestion);

console.log('The eight ball answer: ' + eightBall);


raceday:

Race Day
Codecademy’s annual race is just around the corner! This year, we have a lot
of participants. You have been hired to write a program that will register
runners for the race and give them instructions on race day.

As a timeline, registration would look like this:

Here’s how our registration works. There are adult runners (over 18 years of
age) and youth runners (under 18 years of age). They can register early or late.
Runners are assigned a race number and start time based on their age and
registration.

Race number:

 Early adults receive a race number at or above 1000.


 All others receive a number below 1000.

Start time:

 Adult registrants run at 9:30 am or 11:00 am.


o Early adults run at 9:30 am.
o Late adults run at 11:00 am.
 Youth registrants run at 12:30 pm (regardless of registration).

But we didn’t plan for runners that are exactly 18! We’ll handle that by the end
of the project.

If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.

Tasks

9/9 Complete
Mark the tasks as complete by checking them off
1.
Race numbers are assigned randomly. We’ve provided the necessary code at
the top of the file.

Check off this task after reading that line.

You can read the hint if you want to learn how it works!
Stuck? Get a hint
2.
Create a variable that indicates whether a runner registered early or not.

Set it equal to a Boolean value. You’ll change this later as you test different
runner conditions.
Stuck? Get a hint
3.
Create a variable for the runner’s age and set it equal to a number.

You’ll change this later as you test different runner conditions.


Stuck? Get a hint
4.
Create a control flow statement that checks whether the runner is an adult
AND registered early.

Add 1000 to their raceNumber if this is true.


Stuck? Get a hint
5.
Create a separate control flow statement below the first (starting
with if again). This statement will check age and registration time to
determine race time.

For runners over 18 who registered early, log a statement to the console
telling them that they will race at 9:30 am. Include their raceNumber.
Stuck? Get a hint
6.
“Late adults run at 11:00 am”
Since we already checked for early adults we can write a statement like
this: else if runner is over 18 AND did not register early they will race at
11:00am

Write the corresponding else if statement.

Within that, log a string to the console telling them that they will race at 11:00
am. Include their raceNumber.
Stuck? Get a hint
7.
“Youth registrants run at 12:30 pm (regardless of registration)”

For people who are under 18, log a statement to the console telling them that
they will race at 12:30 pm. Include their raceNumber.
Stuck? Get a hint
8.
Enter different combinations of values for the two variables you created and
run your code several times. Verify that the correct statements are printing to
the console!

You can check your work using the examples provided in the hint.
Stuck? Get a hint
9.
Don’t forget about runners exactly 18 years old!

Add an else statement that logs a statement to the console telling the runner
to see the registration desk.

Code and examples:

let raceNumber = Math.floor(Math.random() * 1000);

let early=false;

let age=20;

if(early && age > 18){

raceNumber +=1000;
}

if(early && age > 18){

console.log('race at time 9.30','your racenumber is :${raceNumber}.');

else if(early && age > 18){

console.log('race at time 11.00','your racenumber is :${raceNumber}.');

else if(early && age > 18){

console.log('race at time 12.30pm','your racenumber is :${raceNumber}.');

else{

console.log('plese go desk for registration,thanks');

}
A function declaration
consists of:

 The function keyword.
 The name of the function, or its identifier, followed by parentheses.
 A function body, or the block of statements required to perform a specific
task, enclosed in the function’s curly brackets, { }.

A function declaration is a function that is bound to an identifier, or name. In the


next exercise we’ll go over how to run the code inside the function body.

We should also be aware of the hoisting feature in JavaScript which allows access


to function declarations before they’re defined.

Take a look at example of hoisting:

greetWorld(); // Output: Hello, World!

function greetWorld() {
  console.log('Hello, World!');

}
Let’s create another function that prints a useful Spanish travel phrase to the
console.

Using a function declaration, create a function called greetInSpanish().


Checkpoint 4 Passed

Stuck? Get a hint


4.
Add code to the function body of greetInSpanish():

 In the function body console.log() the following Spanish phrase


to the console: 'Buenas Tardes.'

function getReminder() {

console.log('Water the plants.');

function greetInSpanish() {

console.log('Buenas Tardes.');
}

2.
Call sayThanks() to view the thank you message in the console.

3.
Functions can be called as many times as you need them.

Imagine that three customers placed an order and you wanted to send each of
them a thank you message. Update your code to call sayThanks() three times.
FUNCTIONS
Parameters and Arguments
So far, the functions we’ve created execute a task without an input. However, some functions can
take inputs and use the inputs to perform a task. When declaring a function, we can specify
its parameters. Parameters allow functions to accept input(s) and perform a task using the
input(s). We use parameters as placeholders for information that will be passed to the function
when it is called.

Let’s observe how to specify parameters in our function declaration:

In the diagram above, calculateArea(), computes the area of a rectangle, based on two


inputs, width and height. The parameters are specified between the parenthesis
as width and height, and inside the function body, they act just like regular
variables. width and height act as placeholders for values that will be multiplied together.

When calling a function that has parameters, we specify the values in the parentheses that follow
the function name. The values that are passed to the function when it is called are
called arguments. Arguments can be passed to the function as values or variables.

In the function call above, the number 10 is passed as the width and 6 is passed as height. Notice
that the order in which arguments are passed and assigned follows the order that the parameters
are declared.
The variables rectWidth and rectHeight are initialized with the values for the height and width of
a rectangle before being used in the function call.

By using parameters, calculateArea() can be reused to compute the area of any rectangle!


Functions are a powerful tool in computer programming so let’s practice creating and calling
functions with parameters.
Code and examples:

function sayThanks(name) {

console.log('Thank you for your purchase '+ name + '! We appreciate your business.');

sayThanks('Cole');
 In the example above, we used the = operator to assign the
parameter name a default value of 'stranger'. This is useful to have in case
we ever want to include a non-personalized default greeting!
 When the code calls greeting('Nick') the value of the argument is passed
in and, 'Nick', will override the default parameter of 'stranger' to
log 'Hello, Nick!' to the console.
 When there isn’t an argument passed into greeting(), the default value
of 'stranger' is used, and 'Hello, stranger!' is logged to the console.
By using a default parameter, we account for situations when an argument isn’t
passed into a function that is expecting an argument.

Let’s practice creating functions that use default parameters.

The function makeShoppingList() creates a shopping list based on the items that


are passed to the function as arguments.
Imagine that you always purchase milk, bread, and eggs every time you go
shopping for groceries. To make creating a grocery list easier, let’s assign default
values to the parameters in makeShoppingList().

Change the parameters of makeShoppingList() into default parameters :

 Assign ‘milk’ as the default value of item1.


 Assign ‘bread’ as the default value of item2.
 Assign ‘eggs’ as the default value of item3.

function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs'){

console.log(`Remember to buy ${item1}`);

console.log(`Remember to buy ${item2}`);

console.log(`Remember to buy ${item3}`);

function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs'){

console.log(`Remember to buy ${item1}`);


console.log(`Remember to buy ${item2}`);

console.log(`Remember to buy ${item3}`);

makeShoppingList();

function monitorCount(rows, columns) {

return rows * columns;

const numOfMonitors = monitorCount(5, 4);

console.log(numOfMonitors);
FUNCTIONS
Helper Functions
We can also use the return value of a function inside another function. These functions
being called within another function are often referred to as helper functions. Since each
function is carrying out a specific task, it makes our code easier to read and debug if
necessary.

If we wanted to define a function that converts the temperature from Celsius to


Fahrenheit, we could write two functions like:

function multiplyByNineFifths(number) {
  return number * (9/5);
};

function getFahrenheit(celsius) {
  return multiplyByNineFifths(celsius) + 32;
};

getFahrenheit(15); // Returns 59
In the example above:

 getFahrenheit() is called and 15 is passed as an argument.


 The code block inside of getFahrenheit() calls multiplyByNineFifths() and
passes 15 as an argument.
 multiplyByNineFifths() takes the argument of 15 for the number parameter.
 The code block inside of multiplyByNineFifths() function multiplies 15 by (9/5),
which evaluates to 27.
 27 is returned back to the function call in getFahrenheit().
 getFahrenheit() continues to execute. It adds 32 to 27, which evaluates to 59.
 Finally, 59 is returned back to the function call getFahrenheit(15).

We can use functions to section off small bits of logic or tasks, then use them when we
need to. Writing helper functions can help take large and difficult tasks and break them
into smaller and more manageable tasks.
1.
In the previous exercise, we created a function to find the number of monitors
to order for an office. Now let’s write another function that uses
the monitorCount function to figure out the price.
Below monitorCount Create a function declaration named costOfMonitors that
has two parameters, the first parameter is rows and the second parameter
is columns. Leave the function body empty for now.
Checkpoint 2 Passed

Stuck? Get a hint


2.
Time to add some code to the function body of costOfMonitors to calculate the
total cost.

Add a return statement that returns the value of calling monitorCount(rows,


columns) multiplied by 200.
Checkpoint 3 Passed

Stuck? Get a hint


3.
We should save the cost to a variable.

Declare a variable named totalCost using the const keyword. Assign


to totalCost the value of calling costOfMonitors() with the
arguments 5 and 4 respectively.
Checkpoint 4 Passed

Stuck? Get a hint


4.
To check that the function worked properly, log totalCost to the console.
Checkpoint 5 Passed

Concept Review

function monitorCount(rows, columns) {

return rows * columns;

function costOfMonitors(rows, columns) {

return monitorCount(rows, columns) * 200;

const totalCost = costOfMonitors(5, 4);


console.log(totalCost);

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How are the functions connected and where does “number” come from?

2.

What is the difference between var and const?

Still have questions? View this exercise's thread in the Codecademy Forums.


const plantNeedsWater = function(day) {

if(day === 'Wednesday'){

return true;

} else {

return false;

};

plantNeedsWater('Tuesday');

console.log(plantNeedsWater('Tuesday'));
FUNCTIONS
Arrow Functions
ES6 introduced arrow function syntax, a shorter way to write functions by
using the special “fat arrow” () => notation.

Arrow functions remove the need to type out the keyword function every time
you need to create a function. Instead, you first include the parameters inside
the ( ) and then add an arrow => that points to the function body surrounded
in { } like this:

const rectangleArea = (width, height) => {


  let area = width * height;
  return area;
};
It’s important to be familiar with the multiple ways of writing functions
because you will come across each of these when reading other JavaScript
code.

Instructions
FUNCTIONS
Concise Body Arrow Functions
JavaScript also provides several ways to refactor arrow function syntax. The
most condensed form of the function is known as concise body. We’ll explore a
few of these techniques below:

1. Functions that take only a single parameter do not need that parameter
to be enclosed in parentheses. However, if a function takes zero or
multiple parameters, parentheses are required.

2. A function body composed of a single-line block does not need curly


braces. Without the curly braces, whatever that line evaluates will be
automatically returned. The contents of the block should immediately
follow the arrow => and the return keyword can be removed. This is
referred to as implicit return.

So if we have a function:

const squareNum = (num) => {


  return num * num;
};
We can refactor the function to:

const squareNum = num => num * num;


Notice the following changes:

 The parentheses around num have been removed, since it has a single


parameter.
 The curly braces { } have been removed since the function consists of a
single-line block.
 The return keyword has been removed since the function consists of a
single-line block.

Instructions
1.
Let’s refactor plantNeedsWater() to be a concise body. Notice that we’ve already
converted the if/else statement to a ternary operator to make the code fit on
one line.

const plantNeedsWater = day => day === 'Wednesday' ? true : false;


Review Functions

Give yourself a pat on the back, you just navigated through functions!

In this lesson, we covered some important concepts about functions:

 A function is a reusable block of code that groups together a sequence of statements to


perform a specific task.
 A function declaration :

 A parameter is a named variable inside a function’s block which will be assigned the
value of the argument passed in when the function is invoked:

 To call a function in your code:

 ES6 introduces new ways of handling arbitrary parameters through default


parameters which allow us to assign a default value to a parameter in case no argument is
passed into the function.
 To return a value from a function, we use a return statement.
 To define a function using function expressions:

 To define a function using arrow function notation:

 Function definition can be made concise using concise arrow notation:


It’s good to be aware of the differences between function expressions, arrow functions, and
function declarations. As you program more in JavaScript, you’ll see a wide variety of how these
function types are used.
Code Editor

main.js

Run
Output-only Terminal
Output:

 
Code and examples:

var favoriteFood='pizza';

var numOfSlices=8;

console.log(numOfSlices);

console.log(favoriteFood);
VARIABLES
Create a Variable: let
As mentioned in the previous exercise, the let keyword was introduced in ES6.
The let keyword signals that the variable can be reassigned a different value. Take a
look at the example:

let meal = 'Enchiladas';


console.log(meal); // Output: Enchiladas
meal = 'Burrito';
console.log(meal); // Output: Burrito
Another concept that we should be aware of when using let (and even var) is that we
can declare a variable without assigning the variable a value. In such a case, the variable
will be automatically initialized with a value of undefined:
let price;
console.log(price); // Output: undefined
price = 350;
console.log(price); // Output: 350
Notice in the example above:

 If we don’t assign a value to a variable declared using the let keyword, it


automatically has a value of undefined.
 We can reassign the value of the variable.

Code and example:

let changeMe=true;

changeMe=false;

console.log(changeMe);

Ilias ahmed

Ocjp ,Microsoft
certified,front
end devoloper
Ilias ahmed

Ocjp ,Microsoft
certified,front
end devoloper
/* Dogs mature at a faster rate than human beings. We often say a dog’s age can be calculated in “dog
years” to account for their growth compared to a human of the same age. In some ways we could say,
time moves quickly for dogs — 8 years in a human’s life equates to 45 years in a dog’s life. How old
would you be if you were a dog? Here’s how you convert your age from “human years” to “dog years”:

- The first two years of a dog’s life count as 10.5 dog years each.

- Each year following equates to 4 dog years

*/

let myAge = 1;

/* Setting a variable with my age. I've changed that to "let" instead of "const", so i can work with my
"if/else" fix */

let earlyYears = 2;

/* Early years of a dog */

earlyYears *= 10.5;

let laterYears = myAge - 2;

/* Since we already accounted for the first two years, take the myAge variable, and subtract 2 from it.*/

laterYears *= 4;

/* Multiply the laterYears variable by 4 to calculate the number of dog years accounted for by your later
years. */

myAgeInDogYears = laterYears + earlyYears;


const myName = "Dimi".toLowerCase();

/* This was the original code that I wrote initially according to the instructions:

console.log(`My name is ${myName}. I am ${myAge} years old in human years, which is $


{myAgeInDogYears} years old in dog years.`); */

if (myAge < 2) {

myAge *= 10.5;

console.log(`My age in dog years is ${myAge}`);

} else {

console.log(`My name is ${myName}. I am ${myAge} years old in human years, which is $


{myAgeInDogYears} years old in dog years.`);

}LEARN JAVASCRIPT

Dog Years
Dogs mature at a faster rate than human beings. We often say a dog’s age can
be calculated in “dog years” to account for their growth compared to a human
of the same age. In some ways we could say, time moves quickly for dogs — 8
years in a human’s life equates to 45 years in a dog’s life. How old would you
be if you were a dog?

Here’s how you convert your age from “human years” to “dog years”:

 The first two years of a dog’s life count as 10.5 dog years each.
 Each year following equates to 4 dog years.

Before you start doing the math in your head, let a computer take care of it!
With your knowledge of math operators and variables, use JavaScript to
convert your human age into dog years.
If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.

Tasks

10/10 Complete
Mark the tasks as complete by checking them off
1.
Create a variable named myAge, and set it equal to your age as a number.

Write a comment that explains this line of code.


Stuck? Get a hint
2.
Create a variable named earlyYears and save the value 2 to it. Note, the value
saved to this variable will change.

Write a comment that explains this line of code.


Stuck? Get a hint
3.
Use the multiplication assignment operator to multiply the value saved
to earlyYears by 10.5 and reassign it to earlyYears.
Stuck? Get a hint
4.
Since we already accounted for the first two years, take the myAge variable, and
subtract 2 from it.

Set the result equal to a variable called laterYears. We’ll be changing this value
later.

Write a comment that explains this line of code.


Stuck? Get a hint
5.
Multiply the laterYears variable by 4 to calculate the number of dog years
accounted for by your later years. Use the multiplication assignment operator
to multiply and assign in one step.
Write a comment that explains this line of code.
Stuck? Get a hint
6.
If you’d like to check your work at this point, print earlyYears and laterYears to
the console. Are the values what you expected?

Check off this task when you’re ready to move on.


Stuck? Get a hint
7.
Add earlyYears and laterYears together, and store that in a variable
named myAgeInDogYears.

Write a comment that explains this line of code.


8.
Let’s use a string method next.

Write your name as a string, call its built-in method .toLowerCase(), and store
the result in a variable called myName.

The toLowerCase method returns a string with all lowercase letters.

Write a comment that explains this line of code.


Stuck? Get a hint
9.
Write a console.log statement that displays your name and age in dog years.
Use string interpolation to display the value in the following sentence:

My name is NAME. I am HUMAN AGE years old in human years which
is DOG AGE years old in dog years.
Replace NAME with myName, HUMAN AGE with myAge, and DOG
AGE with myAgeInDogYears in the sentence above.

Write a comment that explains this line of code.


Stuck? Get a hint
10.
Great work! You can convert any human age to dog years. Try
changing myAge and see what happens.
If you’d like extra practice, try writing this project without the *= operator.
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput ===
'scissors') {
return userInput;
} else {
console.log('Error!');
}
};

function getComputerChoice() {
switch (Math.floor(Math.random() * 3)) {
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
};

function determineWinner(userChoice, computerChoice) {


if (userChoice === computerChoice) {
return 'The game is a tie!';
}// closing if tie clause!!!

if (userChoice === 'rock') {


if (computerChoice === 'paper') {
return 'The computer won!';
} else {
return 'You Won!';
}
};

if (userChoice === 'paper') {


if (computerChoice === 'scissors') {
return 'The computer won!';
} else {
return 'You won!';
}
}
};

const playGame = () => {


let userChoice = getUserChoice('scissors');
const computerChoice = getComputerChoice();
console.log('You threw: ' + userChoice);
console.log('The computer threw: ' + computerChoice);
console.log(determineWinner(userChoice,computerChoice));
}
playGame();
Scope
An important idea in programming is scope. Scope defines where variables can be
accessed or referenced. While some variables can be accessed from anywhere within a
program, other variables may only be available in a specific context.

You can think of scope like the view of the night sky from your window. Everyone who
lives on the planet Earth is in the global scope of the stars. The stars are
accessible globally. Meanwhile, if you live in a city, you may see the city skyline or the
river. The skyline and river are only accessible locally in your city, but you can still see
the stars that are available globally.

Over the next few exercises, we’ll explore how scope relates to variables and learn best
practices for variable declaration.

Code and examples of scope:

const city = 'New York City';

const logCitySkyline = () => {
  let skyscraper = 'Empire State Building';
  return 'The stars over the ' + skyscraper + ' in ' + city;
};

console.log(logCitySkyline());
const city = 'Jamalpur economics zone,city of jamalpur';

const logCitySkyline = () => {
  let skyscraper = 'Administration  Building';
  return 'The location  over the ' + skyscraper + ' in ' + city;
};

console.log(logCitySkyline());

Blocks and Scope


Before we talk more about scope, we first need to talk about blocks.

We’ve seen blocks used before in functions and if statements. A block is the


code found inside a set of curly braces {}. Blocks help us group one or more
statements together and serve as an important structural marker for our code.

A block of code could be a function, like this:

const logSkyColor = () => {


  let color = 'blue';
  console.log(color); // blue
}
Notice that the function body is actually a block of code.

Observe the block in an if statement:

if (dusk) {
  let color = 'pink';
  console.log(color); // pink
}
In the next few exercises, we’ll see how blocks define the scope of variables.

Instructions

1.
At the top of main.js, declare a const variable, named city set equal to 'New
York City'. This variable will exist outside of the block.
Checkpoint 2 Passed

2.
Below the city variable, write a function named logCitySkyline.
Checkpoint 3 Passed

Stuck? Get a hint


3.
Inside of the function body of logCitySkyline(), write another variable
using let named skyscraper and set it equal to 'Empire State Building'.
Checkpoint 4 Passed

Stuck? Get a hint


4.
Inside the function, include a return statement like this:

return 'The stars over the ' + skyscraper + ' in ' + city;
Checkpoint 5 Passed

Stuck? Get a hint


5.
Beneath the logCitySkyline() function, use console.log() to log the value
of logCitySkyline() to the console.

You’ll notice that the logCitySkyline() function is able to access both variables


without any problems. In the next exercise we’ll consider why would it be
preferable to have one variable outside of a block and the other inside of a
block.
const city = 'New York City';
const logCitySkyline = () => {

let skyscraper = 'Empire State Building';

return 'The stars over the ' + skyscraper + ' in ' + city;

};

console.log(logCitySkyline());
SCOPE
Global Scope
Scope is the context in which our variables are declared. We think about scope in
relation to blocks because variables can exist either outside of or within these blocks.

In global scope, variables are declared outside of blocks. These variables are
called global variables. Because global variables are not bound inside a block, they can
be accessed by any code in the program, including code in blocks.

Let’s take a look at an example of global scope:

Let’s take a look at an example of global scope:

const color = 'blue';

const returnSkyColor = () => {


  return color; // blue
};

console.log(returnSkyColor()); // blue

 Even though the color variable is defined outside of the block, it can be


accessed in the function block, giving it global scope.
 In turn, color can be accessed within the returnSkyColor function block.

Let’s work with global variables to see how data can be accessible from any
place within a program.

Instructions

1.
At the top of main.js, write three global variables:

 Name the first variable satellite and set it equal to 'The Moon'.


 Name the second variable galaxy and set it equal to 'The Milky
Way'.
 Name the third variable stars and set it equal to 'North Star'.

Stuck? Get a hint


2.
Below the variables created in the previous step, write a function
named callMyNightSky. Inside the function, include a return statement like this:

return 'Night Sky: ' + satellite + ', ' + stars + ', and '
+ galaxy;
Stuck? Get a hint
3.
Beneath the callMyNightSky() function, use console.log() to log the value
of callMyNightSky() to the console.

You’ll notice that the function block for callMyNightSky() is able to access the
global variables freely since the variables are available to all lines of code in
the file.
Code and example:
-----------------------------
let satellite='The Moon';
let galaxy='The Milky Way';
let stars='North Star';
const callMyNightSky=()=>{
return 'Night Sky: ' + satellite + ', ' + stars + ', and ' + galaxy;
};
console.log(callMyNightSky());
References error will be shown
SCOPE
Block Scope
The next context we’ll cover is block scope. When a variable is defined inside a
block, it is only accessible to the code within the curly braces {}. We say that
variable has block scope because it is only accessible to the lines of code within
that block.

Variables that are declared with block scope are known as local
variables because they are only available to the code that is part of the same
block.

Block scope works like this:

const logSkyColor = () => {


  let color = 'blue';
  console.log(color); // blue
};

logSkyColor(); // blue
console.log(color); // ReferenceError
You’ll notice:

 We define a function logSkyColor().
 Within the function, the color variable is only available within the curly
braces of the function.
 If we try to log the same variable outside the function, throws
a ReferenceError.

Instructions

1.
In main.js, define a function logVisibleLightWaves().
Checkpoint 2 Passed

Stuck? Get a hint


2.
Within the logVisibleLightWaves() function, using const, create a
variable lightWaves and set it equal to 'Moonlight'.
Checkpoint 3 Passed

3.
Within the logVisibleLightWaves() function, beneath the lightWaves variable,
add a console.log() statement that will log the value of the lightWaves variable
when the function runs.
Checkpoint 4 Passed

Stuck? Get a hint


4.
Call the logVisibleLightWaves() function from outside the function.
Checkpoint 5 Passed

Stuck? Get a hint


5.
Beneath the function call, log the value of lightWaves to the console from
outside the function.

You’ll notice that it logs a ReferenceError since the variable is tied to the block
scope of the function!

const logVisibleLightWaves= () =>{


const lightWaves='Moonlight';
console.log(lightWaves);
};
logVisibleLightWaves(lightWaves);
SCOPE
Scope Pollution
It may seem like a great idea to always make your variables accessible, but
having too many global variables can cause problems in a program.

When you declare global variables, they go to the global namespace. The


global namespace allows the variables to be accessible from anywhere in the
program. These variables remain there until the program finishes which means
our global namespace can fill up really quickly.

Scope pollution is when we have too many global variables that exist in the
global namespace, or when we reuse variables across different scopes. Scope
pollution makes it difficult to keep track of our different variables and sets us
up for potential accidents. For example, globally scoped variables can collide
with other variables that are more locally scoped, causing unexpected
behavior in our code.

Let’s look at an example of scope pollution in practice so we know how to


avoid it:

let num = 50;

const logNum = () => {


  num = 100; // Take note of this line of code
  console.log(num);
};

logNum(); // Prints 100


console.log(num); // Prints 100
You’ll notice:

 We have a variable num.
 Inside the function body of logNum(), we want to declare a new variable
but forgot to use the let keyword.
 When we call logNum(), num gets reassigned to 100.
 The reassignment inside logNum() affects the global variable num.
 Even though the reassignment is allowed and we won’t get an error, if
we decided to use num later, we’ll unknowingly use the new value of num.

While it’s important to know what global scope is, it’s best practice to not
define variables in the global scope.

Instructions

1.
Let’s see what happens if we create a variable that overwrites a global variable.

Inside the callMyNightSky() function, on the very first line of the function body,


assign the variable stars to 'Sirius' as such:

stars = 'Sirius';
Checkpoint 2 Passed

2.
Outside the function, under the current console.log() statement, add
another console.log() statement to log stars to the console.

You’ll notice that the global variable stars was reassigned to 'Sirius'. In other


words, we changed the value of the global stars variable but it’s not easy to
read what exactly happened. This is bad practice in code maintainability and
could impact our program in ways we do not intend.

Code and example:

const satellite = 'The Moon';


const galaxy = 'The Milky Way';
let stars = 'North Star';

const callMyNightSky = () => {

stars = 'Sirius';
return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
};

console.log(callMyNightSky(stars));
console.log(stars);
-
SCOPE
Practice Good Scoping
Given the challenges with global variables and scope pollution, we should
follow best practices for scoping our variables as tightly as possible using
block scope.

Tightly scoping your variables will greatly improve your code in several ways:

 It will make your code more legible since the blocks will organize your
code into discrete sections.
 It makes your code more understandable since it clarifies which
variables are associated with different parts of the program rather than
having to keep track of them line after line!
 It’s easier to maintain your code, since your code will be modular.
 It will save memory in your code because it will cease to exist after the
block finishes running.

Here’s another example of how to use block scope, as defined within


an if block:

const logSkyColor = () => {


  const dusk = true;
  let color = 'blue';
  if (dusk) {
    let color = 'pink';
    console.log(color); // pink
  }
  console.log(color); // blue
};

console.log(color); // ReferenceError
Here, you’ll notice:

 We create a variable dusk inside the logSkyColor() function.


 After the if statement, we define a new code block with the {} braces.
Here we assign a new value to the variable color if the if statement is
truthy.
 Within the if block, the color variable holds the value 'pink', though
outside the if block, in the function body, the color variable holds the
value 'blue'.
 While we use block scope, we still pollute our namespace by reusing the
same variable name twice. A better practice would be to rename the
variable inside the block.

Block scope is a powerful tool in JavaScript, since it allows us to define


variables with precision, and not pollute the global namespace. If a variable
does not need to exist outside a block— it shouldn’t!

Instructions

1.
Inside the function body of logVisibleLightWaves(), beneath the region variable
and before the provided console.log() statement, create an if statement that
checks if the region is the 'The Arctic'.
Stuck? Get a hint
2.
Inside the if block, define a new let variable lightWaves and set it equal
to 'Northern Lights'.
3.
Beneath the variable in the if block, use console.log() to log the value of the
block variable inside the if block.

Run your code and notice the output. Inside


the if block console.log(lightWaves) logs the value Northern Lights to the
console. Outside the if block, but still within the function, the same statement
logs Moonlight to the console.

Code and example practice:


const logVisibleLightWaves = () => {
let lightWaves = 'Moonlight';
let region = 'The Arctic';
// Add if statement here:

console.log(lightWaves);
};
logVisibleLightWaves();

code and example final:

const logVisibleLightWaves = () => {


let lightWaves = 'Moonlight';
let region = 'The Arctic';
// Add if statement here:
if (region === 'The Arctic'){
let lightWaves = 'Northern Lights';
console.log(lightWaves);
}
console.log(lightWaves);
};

logVisibleLightWaves();
Code and example final:

const logVisibleLightWaves = () => {


let lightWaves = 'Moonlight';
let region = 'The Arctic';
// Add if statement here:
if (region === 'The Arctic'){
let lightWaves = 'Northern Lights';
console.log(lightWaves);
}
console.log(lightWaves);
};

logVisibleLightWaves();
SCOPE
Review: Scope
In this lesson, you learned about scope and how it impacts the accessibility of
different variables.

Let’s review the following terms:

 Scope is the idea in programming that some variables are


accessible/inaccessible from other parts of the program.
 Blocks are statements that exist within curly braces {}.
 Global scope refers to the context within which variables are accessible
to every part of the program.
 Global variables are variables that exist within global scope.
 Block scope refers to the context within which variables that are
accessible only within the block they are defined.
 Local variables are variables that exist within block scope.
 Global namespace is the space in our code that contains globally
scoped information.
 Scope pollution is when too many variables exist in a namespace or
variable names are reused.

As you continue your coding journey, remember to use best practices when
declaring your variables! Scoping your variables tightly will ensure that your
code has clean, organized, and modular logic.

Instructions

Practice the concepts you’ve learned in the code editor!


LEARN JAVASCRIPT
Training Days
As a seasoned athlete, one of your favorite activities is running marathons.
You use a service called Training Days that sends you a message for the event
you signed up for and the days you have left to train.

Since you also code, Training Days has asThe program currently uses the
wrong scope for its variables. They know this can be troublesome as their
service evolves. In this project you will make Training Days more maintainable
and less error-prone by fixing variable scopes.

If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.
Start

LEARN JAVASCRIPT
Training Days
As a seasoned athlete, one of your favorite activities is running marathons.
You use a service called Training Days that sends you a message for the event
you signed up for and the days you have left to train.
Since you also code, Training Days has asked you to help them solve a
problem: The program currently uses the wrong scope for its variables. They
know this can be troublesome as their service evolves. In this project you will
make Training Days more maintainable and less error-prone by fixing variable
scopes.

If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.
Start

You might also like