2
2
if (wordCount) {
} else {
if (favoritePhrase) {
} else {
}
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
tool='marker';
isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to
open the door.');
favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");
another condition:
isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to
open the door.');
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!' .
} else {
console.log('Invalid season.');
Switch case :
switch (athleteFinalPosition) {
break;
break;
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.
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:
switch(athleteFinalPosition){
break;
break;
break;
default:
break;
}
CONDITIONAL STATEMENTS
Review
Way to go! Here are some of the major concepts for conditionals:
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.
switch (randomNumber){
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
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.
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:
Start time:
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.
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.
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
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.
let early=false;
let age=20;
raceNumber +=1000;
}
else{
}
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, { }.
function greetWorld() {
console.log('Hello, World!');
}
Let’s create another function that prints a useful Spanish travel phrase to the
console.
function getReminder() {
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.
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.
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.
makeShoppingList();
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.
function multiplyByNineFifths(number) {
return number * (9/5);
};
function getFahrenheit(celsius) {
return multiplyByNineFifths(celsius) + 32;
};
getFahrenheit(15); // Returns 59
In the example above:
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
Concept Review
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.
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:
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.
So if we have a function:
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.
Give yourself a pat on the back, you just navigated through functions!
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:
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 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.
*/
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;
earlyYears *= 10.5;
/* 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. */
/* This was the original code that I wrote initially according to the instructions:
if (myAge < 2) {
myAge *= 10.5;
} else {
}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.
Set the result equal to a variable called laterYears. We’ll be changing this value
later.
Write your name as a string, call its built-in method .toLowerCase(), and store
the result in a variable called myName.
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.
function getComputerChoice() {
switch (Math.floor(Math.random() * 3)) {
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
};
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.
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());
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
return 'The stars over the ' + skyscraper + ' in ' + city;
Checkpoint 5 Passed
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.
console.log(returnSkyColor()); // blue
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:
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.
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
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
You’ll notice that it logs a ReferenceError since the variable is tied to the block
scope of the function!
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.
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.
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.
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.
console.log(color); // ReferenceError
Here, you’ll notice:
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.
console.log(lightWaves);
};
logVisibleLightWaves();
logVisibleLightWaves();
Code and example final:
logVisibleLightWaves();
SCOPE
Review: Scope
In this lesson, you learned about scope and how it impacts the accessibility of
different variables.
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
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