0% found this document useful (0 votes)
26 views37 pages

JavaScript I

Notes JavaScript

Uploaded by

lzfb
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)
26 views37 pages

JavaScript I

Notes JavaScript

Uploaded by

lzfb
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/ 37

Introduction: JavaScript Syntax, Part I

In this unit, you will be introduced to JavaScript and learn the basics.
The goal of this unit is to introduce you to JavaScript and get comfortable with the
basics of writing JavaScript programs.
After this unit, you will be able to:
 Relate JavaScript’s role in web development
 Read and write introductory JavaScript syntax related to variables,
conditionals, functions, and scope
 Practice JavaScript syntax
 Execute JavaScript code beyond the Codecademy site
Learning is social. Whatever you’re working on, be sure to connect with the
Codecademy community in the forums. Remember to check in with the
community regularly, including for things like asking for code reviews on your
project work and providing code reviews to others in the projects category, which
can help to reinforce what you’ve learned.

Why JavaScript Is Essential


Learn what is JavaScript and why it is the most popular programming
language. Discover its history, web development role, backend
capabilities, and future potential in technology.

Introduction to JavaScript and its rise in web development


When the Internet boomed in the 1990s, technology companies battled to build
the most powerful and efficient web browser on the market. This sparked the first
“browser war,” between Microsoft (Internet Explorer) and NetScape (NetScape
Navigator) to gain dominance in the usage share of web browsers.
Netscape needed a lightweight scripting language for easier programming which
ultimately made web development more accessible, unlike other languages that
required deeper training. In 1995, a NetScape employee, Brendan Eich, was given
ten days to help build the company a lightweight scripting language. As a result,
Eich built Mocha, which was later renamed JavaScript. The moral of the story –
JavaScript was never intended to become the standard language for the web!
However, as NetScape won the browser war, the popularity of JavaScript grew.
More and more sites began using JavaScript, and those that didn’t eventually had
to as most developers used JavaScript to make websites.
JavaScript is now an essential web technology that’s supported by major web
browsers. The language is crucial for anyone who wants to become a web
developer. Many experts agree that JavaScript will continue to grow as an
indispensable language for web development.
How JavaScript powers modern websites
JavaScript, also called JS, is a flexible and powerful language that is implemented
consistently by various web browsers, making it the language for web
development. JavaScript, HTML, and CSS are the core components of web
technology. While HTML is responsible for structure and CSS is responsible for
style, JavaScript provides interactivity to web pages in the browser.
Popularity of JavaScript
At this point, you may be wondering: how is it that a language written in 10 days
by one guy became mass-adopted by the world wide web? In short, JavaScript
became a hit because it turned web browsers into application platforms. Here’s
how:
1. JavaScript can be used in both the front-end and back-end of web
development.
2. JavaScript is standardized so it’s frequently updated with new versions.
3. JavaScript integrates easily with HTML and CSS.
4. JavaScript allows websites to have interactivity like scroll transitions and
object movement. Modern browsers still compete to process JavaScript the
fastest for the best user experiences. Chrome, the most used Internet
browser in 2017, has been so successful because of its ability to process
JavaScript quickly.
5. JavaScript offers a wide range of frameworks and libraries that help
developers create complex applications with low overhead. Programmers
can import libraries and frameworks in their code to augment their
application’s functionality.

Using JavaScript for backend development


In the early 2000s, big platforms like Facebook and Google began using
JavaScript in their back-end server logic to process and respond to front-end
requests. JavaScript helped businesses scale since engineers who knew
JavaScript could apply those skills in a back-end context.
JavaScript used for servers, also known as server-side JavaScript, gained
popularity because it allowed for scalability. In the server, JavaScript can be
integrated with other languages to communicate with databases.
Node.JS, or Node, is one of the most popular versions of server-side JavaScript.
Node has been used to write large platforms for NASA, eBay and many others.
Since Javascript can execute programs out of sequential order, Node can be used
to create scalable web applications, messaging platforms, and multiplayer
games. This is why Google Cloud and Amazon Web Service depend on Node for
some of their services.

JavaScript for apps, VR, and IoT


Beyond the web, JavaScript has a large presence amongst cross-platform
applications. We use some popular standalone desktop apps like Slack, GitHub,
Skype, and Tidal. These applications are developed with the JavaScript framework
called Electron.js. Electron is excellent for making desktop applications that need
to work across different devices regardless of operating system.
In addition, JavaScript has the potential of expanding into other innovative
technologies such as virtual reality and gaming. JavaScript can be used for
animating, rendering and scaling. JavaScript even has contributed to the internet
of things, the technology that makes simple objects, like your fridge, smarter.
Everyday devices can become interactive and collect data using JavaScript
libraries.
Conclusion
When diving into either programming or web development, JavaScript is an
excellent language to learn. The capabilities of JavaScript allow you to use it in
many different fields. Mastering what is known as “vanilla” or plain JavaScript will
help you to tackle more complicated frameworks and libraries to make you a
competitive developer. Take some of our Codecademy JavaScript courses to
become the JavaScript rockstar companies are looking for!

JavaScript Versions: ES6 and Before


Ever heard of the term “ES6” and wondered what it’s about? Read this
article and find out!
You might have seen the term “ES6” or “Javascript ES6” and wondered what it
actually means. Well wonder no further, because we’re going to dive into what
ES6 is and how it relates to Javascript!
First, let’s bring in some history. JavaScript was introduced in 1995 by the
company Netscape Communications as a scripting language for web designers
and programmers to interact with web pages. The next year, Netscape submitted
JavaScript to a standards-developing organization called Ecma International to
create standards for a scripting language (a type of programming language). In
1997, Ecma International released ECMA-262 which sets standards for the first
version of a scripting language called ECMAScript, shortened to ES.
These new ECMAScript standards provided rules for the architecture of JavaScript
features. As new programming paradigms emerged and developers sought new
features, newer versions of ECMAScript provided a basis for consistency between
new and old JavaScript versions.
To fully distinguish the difference between JavaScript and ECMAScript: if you want
to create an app or program you can use JavaScript — if you want to create a new
scripting language you can follow the guidelines in ECMAScript. So, when you see
ES6 or JavaScript ES6, it means that that version of JavaScript is following the
specifications in the sixth edition of ECMAScript! You might also see ES2015
instead of ES6, but both terminologies are referring to the same 6th edition of
ECMAScript that was released in 2015. Take a look at the timeline below to see
how JavaScript has evolved over the years:
Now, you may be asking, what makes an update in 2015 still relevant today when
there are more recent updates like ES7 and ES8?
Well, despite the release of newer versions, ES6 is actually the biggest update
made to ECMAScript since the first edition was released in 1997! Some
developers even refer to ES6 as “Modern JavaScript” because of all the major
additions. There were so many great features added to help JavaScript
developers that include:
 new keywords like let and const to declare variables,
 new function syntax using Arrow functions,
 creation of Classes,
 parameters with default values,
 promises for asynchronous actions,
 and many more!
Up-to-date browsers now support most of the ES6 features which allow
developers to take advantage of these new additions. ES6 ultimately allows
programmers to save time and write more concise code. As with all ES6 features,
there are other underlying benefits and tradeoffs to consider. Nonetheless, there
has been a strong adoption of ES6 in the development community. One big ES6
benefit is the ease it allows for utilizing a popular programming paradigm, Object-
Oriented Programming (OOP). This change allowed developers of other languages
who are used to OOP to transition into learning/using JavaScript. Another reason
for the popularity of ES6 is correlated with the usage of ES6 in popular
frameworks like React. So, if you want to learn the newest tools and frameworks,
you will have to pick up ES6 along the way.
This being said you shouldn’t disregard legacy code, i.e. older versions of
JavaScript. In fact, there are still many projects that are built and maintained with
legacy code! If you want the ability and freedom to work on any sort of JavaScript
project, you should familiarize yourself with pre-ES6 and ES6 JavaScript syntax.
But don’t worry, we cover both pre-ES6 and ES6 in our JavaScript course. Check it
out to become a rockstar at JavaScript basics and learn fundamental
programming skills!

Documentation: JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript
The provided link goes directly to the official documentation for JavaScript.
Instead of trying to remember it all, use the documentation as a readily available
resource for syntax or implementation help!

INTRODUCTION TO JAVASCRIPT

What is JavaScript?
Last year, millions of learners from our community started with JavaScript. Why?
JavaScript is primarily known as the language of most modern web browsers, and
its early quirks gave it a bit of a bad reputation. However, the language has
continued to evolve and improve. JavaScript is a powerful, flexible, and fast
programming language now being used for increasingly complex web
development and beyond!
Since JavaScript remains at the core of web development, it’s often the first
language learned by self-taught coders eager to learn and build. We’re excited for
what you’ll be able to create with the JavaScript foundation you gain here.
JavaScript powers the dynamic behavior on most websites, including this one.
In this lesson, you will learn introductory coding concepts including data types
and built-in objects—essential knowledge for all aspiring developers. Make sure
to take notes and pace yourself. This foundation will set you up for understanding
the more complex concepts you’ll encounter later.

Console
The console is a panel that displays important messages, like errors, for
developers. Much of the work the computer does with our code is invisible to us
by default. If we want to see things appear on our screen, we can print, or log, to
our console directly.
In JavaScript, the console keyword refers to an object, a collection of data and
actions, that we can use in our code. Keywords are words that are built into the
JavaScript language, so the computer recognizes them and treats them specially.
One action, or method, that is built into the console object is the .log() method.
When we write console.log() what we put inside the parentheses will get
printed, or logged, to the console.
It’s going to be very useful for us to print values to the console, so we can see the
work that we’re doing.
console.log(5);

This example logs 5 to the console. The semicolon denotes the end of the line, or
statement. Although in JavaScript your code will usually run as intended without a
semicolon, we recommend learning the habit of ending each statement with a
semicolon so you never leave one out in the few instances when they are
required.
You’ll see later on that we can use console.log() to print different kinds of data.

Comments
Programming is often highly collaborative. In addition, our own code can quickly
become difficult to understand when we return to it— sometimes only an hour
later! For these reasons, it’s often useful to leave notes in our code for other
developers or ourselves.
As we write JavaScript, we can write comments in our code that the computer will
ignore as our program runs. These comments exist just for human readers.
Comments can explain what the code is doing, leave instructions for developers
using the code, or add any other useful annotations.
There are two types of code comments in JavaScript:
1. A single line comment will comment out a single line and is denoted with
two forward slashes // preceding it.
// Prints 5 to the console
console.log(5);

You can also use a single line comment to comment after a line of code:
console.log(5); // Prints 5

1. A multi-line comment will comment out multiple lines and is denoted


with /* to begin the comment, and */ to end the comment.
/*
This is all commented
console.log(10);
None of this is going to run!
console.log(99);
*/

You can also use this syntax to comment something out in the middle of a line of
code:
console.log(/*IGNORED!*/ 5); // Still just prints 5

Data Types
Data types are the classifications we give to the different kinds of data that we
use in programming. In JavaScript, there are eight fundamental data types:
 Number: Any number, including numbers with decimals: 4, 8, 1516,
23.42.
 BigInt: Any number, greater than 253-1 or less than -(253-1), with n
appended to the number: 1234567890123456n.
 String: Any grouping of characters on your keyboard (letters, numbers,
spaces, symbols, etc.) surrounded by single quotes: ' ... ' or double quotes
" ... ", though we prefer single quotes. Some people like to think of string
as a fancy word for text.
 Boolean: This data type only has two possible values— either true or false
(without quotes). It’s helpful to think of booleans as on and off switches or
as the answers to a “yes” or “no” question.
 Null: This data type represents the intentional absence of a value, and is
represented by the keyword null (without quotes).
 Undefined: This data type is denoted by the keyword undefined (without
quotes). It also represents the absence of a value though it has a different
use than null. undefined means that a given value does not exist.
 Symbol: A newer feature to the language, symbols are unique identifiers,
useful in more complex coding. No need to worry about these for now.
 Object: Collections of related data.
The first 7 of those types are considered primitive data types. They are the most
basic data types in the language. Objects are more complex, and you’ll learn
much more about them as you progress through JavaScript. At first, eight types
may not seem like that many, but soon you’ll observe the world opens with
possibilities once you start leveraging each one. As you learn more about objects,
you’ll be able to create complex collections of data.
But before we do that, let’s get comfortable with strings and numbers!
console.log('Location of Codecademy headquarters: 575 Broadway, New
York City');
console.log(40);

In the example above, we first printed a string. Our string isn’t just a single word;
it includes both capital and lowercase letters, spaces, and punctuation.
Next, we printed the number 40, notice we did not use quotes.

Arithmetic Operators
Basic arithmetic often comes in handy when programming.
An operator is a character that performs a task in our code. JavaScript has
several built-in arithmetic operators, that allow us to perform mathematical
calculations on numbers. These include the following operators and their
corresponding symbols:
1. Add: +
2. Subtract: -
3. Multiply: *
4. Divide: /
5. Remainder: %
The first four work how you might guess:
console.log(3 + 4); // Prints 7
console.log(5 - 1); // Prints 4
console.log(4 * 2); // Prints 8
console.log(9 / 3); // Prints 3

Note that when we console.log() the computer will evaluate the expression inside
the parentheses and print that result to the console. If we wanted to print the
characters 3 + 4, we would wrap them in quotes and print them as a string.
console.log(11 % 3); // Prints 2
console.log(12 % 3); // Prints 0

The remainder operator, sometimes called modulo, returns the number that
remains after the right-hand number divides into the left-hand number as many
times as it evenly can: 11 % 3 equals 2 because 3 fits into 11 three times, leaving
2 as the remainder.

String Concatenation
Operators aren’t just for numbers! When a + operator is used on two strings, it
appends the right string to the left string:
console.log('hi' + 'ya'); // Prints 'hiya'
console.log('wo' + 'ah'); // Prints 'woah'
console.log('I love to ' + 'code.')
// Prints 'I love to code.'

This process of appending one string to another is called concatenation. Notice in


the third example we had to make sure to include a space at the end of the first
string. The computer will join the strings exactly, so we needed to make sure to
include the space we wanted between the two strings.
console.log('front ' + 'space');
// Prints 'front space'
console.log('back' + ' space');
// Prints 'back space'
console.log('no' + 'space');
// Prints 'nospace'
console.log('middle' + ' ' + 'space');
// Prints 'middle space'
Just like with regular math, we can combine, or chain, our operations to get a
final result:
console.log('One' + ', ' + 'two' + ', ' + 'three!');
// Prints 'One, two, three!'

Properties
When you introduce a new piece of data into a JavaScript program, the browser
saves it as an instance of the data type. All data types have access to specific
properties that are passed down to each instance. For example, every string
instance has a property called length that stores the number of characters in that
string. You can retrieve property information by appending the string with a
period and the property name:
console.log('Hello'.length); // Prints 5
The . is another operator! We call it the dot operator.
In the example above, the value saved to the length property is retrieved from
the instance of the string, 'Hello'. The program prints 5 to the console, because
Hello has five characters in it.

Methods
Remember that methods are actions we can perform. Data types have access to
specific methods that allow us to handle instances of that data type. JavaScript
provides a number of string methods.
We call, or use, these methods by appending an instance with:
 a period (the dot operator)
 the name of the method
 opening and closing parentheses
E.g. 'example string'.methodName().
Does that syntax look a little familiar? When we use console.log() we’re calling
the .log() method on the console object. Let’s see console.log() and some real
string methods in action!
console.log('hello'.toUpperCase()); // Prints 'HELLO'
console.log('Hey'.startsWith('H')); // Prints true
Let’s look at each of the lines above:
 On the first line, the .toUpperCase() method is called on the string instance
'hello'. The result is logged to the console. This method returns a string in
all capital letters: 'HELLO'.
 On the second line, the .startsWith()
method is called on the string instance 'Hey'. This method also accepts the
character 'H' as an input, or argument, between the parentheses. Since the string
'Hey' does start with the letter 'H', the method returns the boolean true.
You can find a list of built-in string methods in the JavaScript documentation.
Developers use documentation as a reference tool. It describes JavaScript’s
keywords, methods, and syntax.

Built-in Objects
In addition to console, there are other objects built into JavaScript. Down the line,
you’ll build your own objects, but for now these “built-in” objects are full of useful
functionality.
For example, if you wanted to perform more complex mathematical operations
than arithmetic, JavaScript has the built-in Math object.
The great thing about objects is that they have methods! Let’s call the .random()
method from the built-in Math object:
console.log(Math.random()); // Prints a random number between 0 and 1
In the example above, we called the .random() method by appending the object
name with the dot operator, the name of the method, and opening and closing
parentheses. This method returns a random number between 0 (inclusive) and 1
(exclusive).
To generate a random number between 0 and 50, we could multiply this result by
50, like so:
Math.random() * 50;
The example above will likely evaluate to a decimal. To ensure the answer is a
whole number, we can take advantage of another useful Math method called
Math.floor().
Math.floor() takes a decimal number, and rounds down to the nearest whole
number. You can use Math.floor() to round down a random number like this:
Math.floor(Math.random() * 50);
In this case:
1. Math.random() generates a random number between 0 and 1.
2. We then multiply that number by 50, so now we have a number between 0
and 50.
3. Then, Math.floor() rounds the number down to the nearest whole number.
If you wanted to see the number printed to the terminal, you would still need to
use a console.log() statement:
console.log(Math.floor(Math.random() * 50)); // Prints a random whole
number between 0 and 50
To see all of the properties and methods on the Math object, take a look at the
documentation here.

Review
Let’s take one more glance at the concepts we just learned:
 Data is printed, or logged, to the console, a panel that displays messages,
with console.log().
 We can write single-line comments with // and multi-line comments
between /* and */.
 There are 8 fundamental data types in JavaScript: numbers, BigInts,
strings, booleans, null, undefined, symbol, and object.
 Numbers are any number without quotes: 23.8879
 Strings are characters wrapped in single or double quotes: 'Sample
String'
 The built-in arithmetic operators include +, -, *, /, and %.
 Objects, including instances of data types, can have properties, stored
information. The properties are denoted with a . after the name of the
object, for example: 'Hello'.length.
 Objects, including instances of data types, can have methods which
perform actions. Methods are called by appending the object or instance
with a period, the method name, and parentheses. For example:
'hello'.toUpperCase().
 We can access properties and methods by using the “.”, dot operator.
 Built-in objects, including Math, are collections of methods and properties
that JavaScript provides.
Here are a few more resources to add to your toolkit:
 Codecademy Docs: JavaScript
 Codecademy Workspaces: JavaScript
Make sure to bookmark these links so you have them at your disposal.

Variables

Create a Variable: var


There were a lot of changes introduced in the ES6 version of JavaScript in 2015.
One of the biggest changes was two new keywords, let and const, to create, or
declare,
Preview: Docs Variables are used to store a piece of data at a named location in
memory.
variables
. Prior to the ES6, programmers could only use the var keyword to declare
variables.
var myName = 'Arya';
console.log(myName);
// Output: Arya

Let’s consider the example above:


1. var, short for variable, is a JavaScript keyword that creates, or declares, a
new variable.
2. myName is the variable’s name. Capitalizing in this way is a standard
convention in JavaScript called camel casing. In camel casing you group
words into one, the first word is lowercase, then every word that follows
will have its first letter uppercased. (e.g. camelCaseEverything).
3. = is the assignment operator. It assigns the value ('Arya') to the variable
(myName).
4. 'Arya' is the value assigned (=) to the variable myName. You can also say
that the myName variable is initialized with a value of 'Arya'.
5. After the variable is declared, the string value 'Arya' is printed to the
console by referencing the variable name: console.log(myName).
There are a few general rules for naming variables:
 Variable names cannot start with numbers.
 Variable names are case sensitive, so myName and myname would be
different variables. It is bad practice to create two variables that have the
same name using different cases.
 Variable names cannot be the same as keywords. For a comprehensive list
of keywords check out MDN’s keyword documentation.
In the next exercises, we will learn why ES6’s let and const are the preferred
variable keywords by many programmers. Because there is still a ton of code
written prior to ES6, it’s helpful to be familiar with the pre-ES6 var keyword.
If you want to learn more about var and the quirks associated with it, check out
the MDN var documentation.

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.

Create a Variable: const


The const keyword was also introduced in ES6, and is short for the word constant.
Just like with var and let you can store any value in a const variable. The way you
declare a const variable and assign a value to it follows the same structure as let
and var. Take a look at the following example:

const myName = 'Gilberto';


console.log(myName); // Output: Gilberto

However, a const variable cannot be reassigned because it is constant. If you try


to reassign a const variable, you’ll get a TypeError.
Constant variables must be assigned a value when declared. If you try to declare
a const variable without a value, you’ll get a SyntaxError.
If you’re trying to decide between which keyword to use, let or const, think about
whether you’ll need to reassign the variable later on. If you do need to reassign
the variable use let, otherwise, use const.

Mathematical Assignment Operators


Let’s consider how we can use variables and math operators to calculate new
values and assign them to a variable. Check out the example below:
let w = 4;
w = w + 1;

console.log(w); // Output: 5

In the example above, we created the variable w with the number 4 assigned to
it. The following line, w = w + 1, increases the value of w from 4 to 5.
Another way we could have reassigned w after performing some mathematical
operation on it is to use built-in mathematical assignment operators. We could re-
write the code above to be:
let w = 4;
w += 1;
console.log(w); // Output: 5

In the second example, we used the += assignment operator to reassign w.


We’re performing the mathematical operation of the first operator + using the
number to the right, then reassigning w to the computed value.
We also have access to other mathematical assignment operators: -=, *=, and /=
which work in a similar fashion.
let x = 20;
x -= 5; // Can be written as x = x - 5
console.log(x); // Output: 15

let y = 50;
y *= 2; // Can be written as y = y * 2
console.log(y); // Output: 100

let z = 8;
z /= 2; // Can be written as z = z / 2
console.log(z); // Output: 4

Let’s practice using these mathematical assignment operators!

The Increment and Decrement Operator


Other mathematical assignment operators include the increment operator (++)
and decrement operator (--).
The increment operator will increase the value of the variable by 1. The
decrement operator will decrease the value of the variable by 1. For example:
let a = 10;
a++;
console.log(a); // Output: 11

let b = 20;
b--;
console.log(b); // Output: 19

Just like the previous mathematical assignment operators (+=, -=, *=, /=), the
variable’s value is updated and assigned as the new value of that variable.

String Concatenation with Variables


In previous exercises, we assigned strings to variables . Now, let’s go over how to
connect, or concatenate, strings in variables.
The + operator can be used to combine two string values even if those values are
being stored in variables:
let myPet = 'armadillo';
console.log('I own a pet ' + myPet + '.');
// Output: 'I own a pet armadillo.'
In the example above, we assigned the value 'armadillo' to the myPet variable.
On the second line, the + operator is used to combine three strings: 'I own a pet',
the value saved to myPet, and '.'. We log the result of this concatenation to the
console as:
I own a pet armadillo.

String Interpolation
In the ES6 version of JavaScript, we can insert, or interpolate, variables into
strings using template literals. Check out the following example where a template
literal is used to log strings together:
const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.

Notice that:
 a template literal is wrapped by backticks ` (this key is usually located on
the top of your keyboard, left of the 1 key).
 Inside the template literal, you’ll see a placeholder, ${myPet}. The value
of myPet is inserted into the template literal.
 When we interpolate `I own a pet ${myPet}.`, the output we print is the
string: 'I own a pet armadillo.'
One of the biggest benefits to using template literals is the readability of the
code. Using template literals, you can more easily tell what the new string will be.
You also don’t have to worry about escaping double quotes or single quotes.

typeof operator
While writing code, it can be useful to keep track of the data types of the
variables in your program. If you need to check the data type of a variable’s
value, you can use the typeof operator.
The typeof operator checks the value to its right and returns, or passes back, a
string of the data type.
const unknown1 = 'foo';
console.log(typeof unknown1); // Output: string

const unknown2 = 10;


console.log(typeof unknown2); // Output: number

const unknown3 = true;


console.log(typeof unknown3); // Output: boolean
Let’s break down the first example. Since the value unknown1 is 'foo', a string,
typeof unknown1 will return 'string'.

Review Variables
Nice work! This lesson introduced you to variables, a powerful concept you will
use in all your future programming endeavors.
Let’s review what we learned:
 Variables hold reusable data in a program and associate it with a name.
 Variables are stored in memory.
 The var keyword is used in pre-ES6 versions of JS.
 let is the preferred way to declare a variable when it can be reassigned,
and const is the preferred way to declare a variable with a constant value.
 Variables that have not been initialized store the primitive data type
undefined.
 Mathematical assignment operators make it easy to calculate a new value
and assign it to the same variable.
 The + operator is used to concatenate strings including string values held
in variables.
 In ES6, template literals use backticks ` and ${} to interpolate values into
a string.
 The typeof keyword returns the data type (as a string) of a value.

Instructions
To learn more about variables take on these challenges!
o Create variables and manipulate the values.
o Check what happens when you try concatenating strings using
variables of different data types.
o Interpolate multiple variables into a string.
o See what happens when you use console.log() on variables declared
by different keywords (const, let, var) before they’re defined. For
example:
console.log(test1);

const test1 = 'figuring out quirks';


o Find the data type of a variable’s value using the typeof keyword on
a variable.
o Use typeof to find the data type of the resulting value when you
concatenate variables containing two different data types.

Building Interactive Websites - Kelvin Weather


In this project, we’re going to practice variables and printing to the console in
JavaScript so you can hone your skills and feel confident taking them to the real
world. Why? You’ve got to master the basics. Get comfortable with these
fundamentals.
Here's what to expect
 Check off the project tasks as you complete each one.
 This is not an exam, so you can refer to other resources to help you
complete the project.
// Task 1: The forecast today is 293 Kelvin. To start, create a variable
named kelvin, and set it equal to 293.
// The value saved to kelvin will stay constant. Choose the variable type
with this in mind.
// Task 2: Write a comment above that explains this line of code.
// This constant variable stores the temperature in Kelvin, which will not
change.
const kelvin = 293;

// Task 3: Celsius is similar to Kelvin — the only difference is that Celsius is


273 degrees less than Kelvin.
// Let’s convert Kelvin to Celsius by subtracting 273 from the kelvin
variable. Store the result in another variable, named celsius.
// Task 4: Write a comment above that explains this line of code.
// This line converts the Kelvin temperature to Celsius by subtracting
273.15 (more precise than 273).
// Using 273.15 for better accuracy in scientific contexts, though 273 might
be acceptable in some simpler cases.
const celsius = kelvin - 273.15;

// Task 5: Use this equation to calculate Fahrenheit, then store the answer
in a variable named fahrenheit.
// Fahrenheit = Celsius * (9/5) + 32
// In the next step we will round the number saved to fahrenheit. Choose
the variable type that allows you to change its value.
// Task 6: Write a comment above that explains this line of code.
// This line calculates the temperature in Fahrenheit from Celsius. 'let' is
used because its value will be re-assigned after rounding.
let fahrenheit = celsius * (9 / 5) + 32;

// Task 7: When you convert from Celsius to Fahrenheit, you often get a
decimal number.
// Use the .floor() method from the built-in Math object to round down the
Fahrenheit temperature. Save the result to the fahrenheit variable.
// Task 8: Write a comment above that explains this line of code.
// This line rounds down the Fahrenheit temperature to the nearest whole
number.
fahrenheit = Math.floor(fahrenheit);

// Task 9: Use console.log and string interpolation to log the temperature in


fahrenheit to the console as follows:
// The temperature is TEMPERATURE degrees Fahrenheit.
// Use string interpolation to replace TEMPERATURE with the value saved to
fahrenheit.
console.log(`The temperature is ${fahrenheit} degrees Fahrenheit.`);

// Task 10: Run your program to see your results!


// (You would run this code in a JavaScript environment like a browser's
developer console or Node.js)

// Task 11: By using variables, your program should work for any Kelvin
temperature — just change the value of kelvin and run the program again.
// What’s 0 Kelvin in Fahrenheit?

// Let's change the kelvin value to 0 for this test:


// const kelvin = 0; // If uncommented, you'd need to re-run the
calculations below or wrap in a function.
// For demonstration, I'll recalculate specifically for 0 Kelvin here:
const kelvinAbsoluteZero = 0;
const celsiusAbsoluteZero = kelvinAbsoluteZero - 273.15;
let fahrenheitAbsoluteZero = celsiusAbsoluteZero * (9 / 5) + 32;
fahrenheitAbsoluteZero = Math.floor(fahrenheitAbsoluteZero);
console.log(`\n--- Test for 0 Kelvin ---`);
console.log(`0 Kelvin is ${fahrenheitAbsoluteZero} degrees Fahrenheit.`); //
Output will be -460

// Task 12: Great work! Kelvin can now publish his forecasts in Celsius and
Fahrenheit.
// If you’d like extra practice, try this:
// Convert celsius to the Newton scale using the equation below
// Newton = Celsius * (33/100)
// Round down the Newton temperature using the .floor() method
// Use console.log and string interpolation to log the temperature in newton
to the console

// Convert the original celsius (from kelvin = 293) to Newton


let newton = celsius * (33 / 100);
newton = Math.floor(newton);

console.log(`\n--- Extra Practice: Newton Scale ---`);


console.log(`The temperature is ${newton} degrees Newton.`);
Building Interactive Websites - Dog Years
In this project, we’re going to practice variables and strings in JavaScript so you
can hone your skills and feel confident taking them to the real world. Why? These
concepts will help you use your data to output information to your users.
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.
Task 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.
Task 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.
Task 3
Use the multiplication assignment operator to multiply the value saved to
earlyYears by 10.5 and reassign it to earlyYears.
Task 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.
Task 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.
Task 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.
Task 7
Add earlyYears and laterYears together, and store that in a variable named
myAgeInDogYears.
Write a comment that explains this line of code.
Task 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.
Task 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.
Task 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.

//Create variables with my name and age.


const myName = "Luiz".toLowerCase();
const myAge = 45
//Calculate dog years.
function calculateDogYears(humanAge) {
let earlyYears = 2 * 10.5;
let laterYears = (humanAge - 2) * 4;
return earlyYears + laterYears;
}
let myAgeInDogYears = calculateDogYears(myAge)

//Print the text with the information.


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

Conditional Statements

What are Conditional Statements?


In life, we make decisions based on circumstances. Think of an everyday decision
as mundane as falling asleep — if we are tired, we go to bed, otherwise, we wake
up and start our day.
These if-else decisions can be modeled in code by creating conditional
statements. A conditional statement checks a specific condition(s) and performs
a task based on the condition(s).
In this lesson, we will explore how programs make decisions by evaluating
conditions and introduce logic into our code!
We’ll be covering the following concepts:
 if, else if, and else statements
 comparison operators
 logical operators
 truthy vs falsy values
 ternary operators
 switch statement
So if you’re ready to learn these concepts go to the next lesson— else, read over
the concepts, observe the diagram, and prepare yourself for this lesson!

If Statement
We often perform a task based on a condition. For example, if the weather is nice
today, then we will go outside. If the alarm clock rings, then we’ll shut it off. If
we’re tired, then we’ll go to sleep.
In programming, we can also perform a task based on a condition using an if
statement:
if (true) {
console.log('This message will print!');
}
// Prints: This message will print!

Notice in the example above, we have an if statement. The if statement is


composed of:
 The if keyword followed by a set of parentheses () which is followed by a
code block, or block statement, indicated by a set of curly braces {}.
 Inside the parentheses (), a condition is provided that evaluates to true or
false.
 If the condition evaluates to true, the code inside the curly braces {} runs,
or executes.
 If the condition evaluates to false, the block won’t execute.

If...Else Statements
In the previous exercise, we used an if statement that checked a condition to
decide whether or not to run a block of code. In many cases, we’ll have code we
want to run if our condition evaluates to false.
If we wanted to add some default behavior to the if statement, we can add an
else statement to run a block of code when the condition evaluates to false. Take
a look at the inclusion of an else statement:
if (false) {
console.log('The code in this block will not run.');
} else {
console.log('But the code in this block will!');
}

// Prints: But the code in this block will!

An else statement must be paired with an if statement, and together they are
referred to as an if...else statement.
In the example above, the else statement:
 Uses the else keyword following the code block of an if statement.
 Has a code block that is wrapped by a set of curly braces {}.
 The code inside the else statement code block will execute when the if
statement’s condition evaluates to false.
if...else statements allow us to automate solutions to yes-or-no questions, also
known as binary decisions.

Comparison Operators
When writing conditional statements, sometimes we need to use different types
of operators to compare values. These operators are called comparison
operators.
Here is a list of some handy comparison operators and their syntax:
 Less than: <
 Greater than: >
 Less than or equal to: <=
 Greater than or equal to: >=
 Is equal to: ===
 Is not equal to: !==
Comparison operators compare the value on the left with the value on the right.
For instance:
10 < 12 // Evaluates to true

It can be helpful to think of comparison statements as questions. When the


answer is “yes”, the statement evaluates to true, and when the answer is “no”,
the statement evaluates to false. The code above would be asking: is 10 less
than 12? Yes! So 10 < 12 evaluates to true.
We can also use comparison operators on different data types like strings:
'apples' === 'oranges' // false

In the example above, we’re using the identity operator (===) to check if the
string 'apples' is the same as the string 'oranges'. Since the two strings are not
the same, the comparison statement evaluates to false.
All comparison statements evaluate to either true or false and are made up of:
 Two values that will be compared.
 An operator that separates the values and compares them accordingly (>,
<, <=,>=,===,!==).

Logical Operators
Working with conditionals means that we will be using booleans, true or false
values. In JavaScript, there are operators that work with boolean values known as
logical operators. We can use logical operators to add more sophisticated logic to
our conditionals. There are three logical operators:
 the and operator (&&)
 the or operator (||)
 the not operator, otherwise known as the bang operator (!)
When we use the && operator, we are checking that two things are true:
if (stopLight === 'green' && pedestrians === 0) {
console.log('Go!');
} else {
console.log('Stop');
}

When using the && operator, both conditions must evaluate to true for the entire
condition to evaluate to true and execute. Otherwise, if either condition is false,
the && condition will evaluate to false and the else block will execute.
If we only care about either condition being true, we can use the || operator:
if (day === 'Saturday' || day === 'Sunday') {
console.log('Enjoy the weekend!');
} else {
console.log('Do some work.');
}

When using the || operator, only one of the conditions must evaluate to true for
the overall statement to evaluate to true. In the code example above, if either
day === 'Saturday' or day === 'Sunday' evaluates to true the if‘s condition will
evaluate to true and its code block will execute. If the first condition in an ||
statement evaluates to true, the second condition won’t even be checked. Only if
day === 'Saturday' evaluates to false will day === 'Sunday' be evaluated. The
code in the else statement above will execute only if both comparisons evaluate
to false.
The ! not operator reverses, or negates, the value of a boolean:
let excited = true;
console.log(!excited); // Prints false

let sleepy = false;


console.log(!sleepy); // Prints true

Essentially, the ! operator will either take a true value and pass back false, or it
will take a false value and pass back true.
Logical operators are often used in conditional statements to add another layer of
logic to our code.
Truthy and Falsy
Let’s consider how non-boolean data types, like strings or numbers, are
evaluated when checked inside a condition.
Sometimes, you’ll want to check if a variable exists and you won’t necessarily
want it to equal a specific value — you’ll only check to see if the variable has
been assigned a value.
Here’s an example:
let myVariable = 'I Exist!';

if (myVariable) {
console.log(myVariable)
} else {
console.log('The variable does not exist.')
}

The code block in the if statement will run because myVariable has
a truthy value; even though the value of myVariable is not explicitly the
value true, when used in a boolean or conditional context, it evaluates
to true because it has been assigned a non-falsy value.
So which values are falsy— or evaluate to false when checked as a condition? The
list of falsy values includes:
 0
 Empty strings like "" or ''
 null which represent when there is no value at all
 undefined which represent when a declared variable lacks a value
 NaN, or Not a Number
Here’s an example with numbers:
let numberOfApples = 0;

if (numberOfApples){
console.log('Let us eat apples!');
} else {
console.log('No apples left!');
}

// Prints 'No apples left!'

The condition evaluates to false because the value of the numberOfApples is 0.


Since 0 is a falsy value, the code block in the else statement will run.

Truthy and Falsy Assignment


Truthy and falsy evaluations open a world of short-hand possibilities!
Say you have a website and want to take a user’s username to make a
personalized greeting. Sometimes, the user does not have an account, making
the username variable falsy. The code below checks if username is defined and
assigns a default string if it is not:
let username = '';
let defaultName;

if (username) {
defaultName = username;
} else {
defaultName = 'Stranger';
}

console.log(defaultName); // Prints: Stranger

Copy to Clipboard
If you combine your knowledge of logical operators you can use a short-hand for
the code above. In a boolean condition, JavaScript assigns the truthy value to a
variable if you use the || operator in your assignment:
let username = '';
let defaultName = username || 'Stranger';

console.log(defaultName); // Prints: Stranger

Because || or statements check the left-hand condition first, the


variable defaultName will be assigned the actual value of username if it is truthy,
and it will be assigned the value of 'Stranger' if username is falsy. This concept is
also referred to as short-circuit evaluation.

Ternary Operator
In the spirit of using short-hand syntax, we can use a ternary operator to simplify
an if...else statement.
Take a look at the if...else statement example:
let isNightTime = true;

if (isNightTime) {
console.log('Turn on the lights!');
} else {
console.log('Turn off the lights!');
}

We can use a ternary operator to perform the same functionality:


isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the
lights!');

In the example above:


 The condition, isNightTime, is provided before the ?.
 Two expressions follow the ? and are separated by a colon :.
 If the condition evaluates to true, the first expression executes.
 If the condition evaluates to false, the second expression executes.
Like if...else statements, ternary operators can be used for conditions which
evaluate to true or false.

Else If Statements
We can add more conditions to our if...else with an else if statement. The else
if statement allows for more than two possible outcomes. You can add as
many else if statements as you’d like, to make more complex conditionals!
The else if statement always comes after the if statement and before
the else statement. The else if statement also takes a condition. Let’s take a look
at the syntax:
let stopLight = 'yellow';

if (stopLight === 'red') {


console.log('Stop!');
} else if (stopLight === 'yellow') {
console.log('Slow down.');
} else if (stopLight === 'green') {
console.log('Go!');
} else {
console.log('Caution, unknown!');
}

The else if statements allow you to have multiple possible outcomes. if/else
if/else statements are read from top to bottom, so the first condition that
evaluates to true from the top to bottom is the block that gets executed.
In the example above, since stopLight === 'red' evaluates to false and stopLight
=== 'yellow' evaluates to true, the code inside the first else if statement is
executed. The rest of the conditions are not evaluated. If none of the conditions
evaluated to true, then the code in the else statement would have executed.

The switch keyword


else if statements are a great tool if we need to check multiple conditions. In
programming, we often find ourselves needing to check multiple values and
handle each of them differently. For example:
let groceryItem = 'papaya';
if (groceryItem === 'tomato') {
console.log('Tomatoes are $0.49');
} else if (groceryItem === 'papaya'){
console.log('Papayas are $1.29');
} else {
console.log('Invalid item');
}

In the code above, we have a series of conditions checking for a value that
matches a groceryItem variable. Our code works fine, but imagine if we needed
to check 100 different values! Having to write that many else if statements
sounds like a pain!
A switch statement provides an alternative syntax that is easier to read and
write. A switch statement looks like this:
let groceryItem = 'papaya';

switch (groceryItem) {
case 'tomato':
console.log('Tomatoes are $0.49');
break;
case 'lime':
console.log('Limes are $1.49');
break;
case 'papaya':
console.log('Papayas are $1.29');
break;
default:
console.log('Invalid item');
break;
}

// Prints 'Papayas are $1.29'

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

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.

JavaScript Operators: Key Concepts for Beginners


Operators are special symbols or characters that perform actions on
values and variables in JavaScript. Understanding them is fundamental to
writing any functional code.
1. Assignment Operator (=)
 Purpose: Assigns a value to a variable.
 Example: let x = 42; (assigns the value 42 to the variable x).
2. Arithmetic Operators
 Purpose: Perform mathematical calculations on numeric values.
 Key Operators:
o +: Addition (also used for string concatenation).
o -: Subtraction.
o *: Multiplication.
o /: Division.
o %: Modulo (finds the remainder of a division).
o **: Exponentiation (e.g., 2 ** 3 is 2 to the power of 3, which is 8).
o ++: Increment (adds 1 to a value).
o --: Decrement (subtracts 1 from a value).
 Beginner Tip: These are straightforward and work as you'd expect in
mathematics. Pay attention to + for string concatenation, which can
sometimes be a source of confusion.
3. Other Assignment Operators (Compound Assignment)
 Purpose: A shorthand way to perform an arithmetic operation and then
assign the result back to the same variable.
 Key Operators:
o +=: Add and assign (e.g., number += 10 is equivalent to number =
number + 10).
o -=: Subtract and assign.
o *=: Multiply and assign.
o /=: Divide and assign.
o %=: Modulo and assign.
o **=: Exponentiate and assign.
 Beginner Tip: These operators make your code more concise and are
very commonly used.
4. Comparison Operators
 Purpose: Compare two values and return a boolean (true or false) based
on the comparison.
 Crucial Operators for Beginners:
o == (Loose Equality): Checks if values are equal, performing "type
coercion" (JavaScript might convert types before comparing). Avoid
using this generally.
o === (Strict Equality): Checks if values and types are equal.
Always prefer this for reliable comparisons.
o != (Loose Inequality): Checks if values are not equal, with type
coercion. Avoid using this generally.
o !== (Strict Inequality): Checks if values and types are not equal.
Always prefer this for reliable comparisons.
o >: Greater than.
o <: Less than.
o >=: Greater than or equal to.
o <=: Less than or equal to.
 Beginner Tip: The distinction between == and === is one of the most
important concepts for JavaScript beginners. Always use === and !== to
prevent unexpected behavior due to JavaScript's automatic type
conversions.
5. Logical Operators
 Purpose: Combine multiple boolean expressions or values to produce a
single boolean output.
 Key Operators:
o && (AND): Returns true only if all operands are true.
o || (OR): Returns true if at least one operand is true.
o ! (NOT): Reverses the boolean value of an operand (e.g., !true is
false).
 Beginner Tip: These are essential for controlling program flow and
making decisions within your code.
6. Unary Operator (typeof)
 Purpose: Operates on a single term or variable.
 typeof: Returns a string indicating the data type of its operand.
 Example: console.log(typeof 'hello'); // Output: "string"
 Beginner Tip: typeof is useful for debugging and understanding the data
types you're working with.
7. Conditional (Ternary) Operator (? :)
 Purpose: A concise way to assign a value to a variable based on a
condition, acting as a shorthand for simple if...else statements.
 Syntax: variable = condition ? valueIfTrue : valueIfFalse;
 Beginner Tip: While it can make code more compact, use it for simple
conditions. For more complex logic, traditional if...else statements are often
more readable, especially for beginners. Be careful with complex multi-
step operations within a single ternary operator, as parentheses placement
is crucial.

Building Interactive Websites - 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 a 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.
Tasks
9/9 complete
Mark the tasks as complete by checking them off
Task 1
In the first line of the program, define a variable called userName that is set to an
empty string.
If the user wants, they can enter their name in between the quotation marks.
Task 2
Below this variable, create a ternary expression that decides what to do if the
user enters a name or not. If the user enters a name — like 'Jane' — use string
interpolation to log Hello, Jane! to the console. Otherwise, simply log Hello!.
Task 3
Create a variable named userQuestion. The value of the variable should be a
string that is the question the user wants to ask the Magic Eight Ball.
Task 4
Write a console.log() for the userQuestion, stating what was asked. You can
include the user’s name in the console.log() statement, if you wish!
Task 5
We need to generate a random number between 0 and 7.
Create another variable, and name it randomNumber. Set it equal to this
expression, which uses two methods (Math.floor() and Math.random()) from the
Math library.
Math.floor(Math.random() * 8);

Copy to Clipboard
Check the hint to learn how it works!
Task 6
Create one more variable named eightBall, and set it equal to an empty string.
We will save a value to this variable in the next steps, depending on the value
of randomNumber.
Task 7
We need to create a control flow that takes in the randomNumber we made in
step 5, and then assigns eightBall to a reply that a Magic Eight Ball would return.
Think about utilizing if/else or switch statements. Here are 8 Magic Eight Ball
phrases that we’d like to save to the variable eightBall:
 'It is certain'
 'It is decidedly so'
 'Reply hazy try again'
 'Cannot predict now'
 'Do not count on it'
 'My sources say no'
 'Outlook not so good'
 'Signs point to yes'
If the randomNumber is 0, then save an answer to the eightBall variable;
if randomNumber is 1, then save the next answer, and so on. If you’re feeling
creative, make your own responses!
Task 8
Write a console.log() to print the Magic Eight Ball’s answer, the value of
the eightBall variable.
Task 9
Run your program a few times to see random results appear in the console!
If you want extra practice:
 If you started with a switch statement, convert it to if/else
if/else statements.
 If you started with if/else if/else statements, convert them to
a switch statement.

You might also like