JavaScript I
JavaScript 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.
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
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.'
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
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
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
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 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 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
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);
// 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 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?
// 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
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.
Conditional Statements
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!
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!');
}
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
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
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!');
}
if (username) {
defaultName = username;
} else {
defaultName = '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';
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!');
}
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';
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.
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;
}
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.
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.