JavaScript Notes
JavaScript Notes
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 locally
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.
JavaScript on the Web
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:
➢ JavaScript can be used in both the front-end and back-end of web development.
➢ JavaScript is standardized so it’s frequently updated with new versions.
➢ JavaScript integrates easily with HTML and CSS.
➢ 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.
➢ 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.
❖
JavaScript for Servers
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.
What Else Can JavaScript Do?
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!
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:
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!
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.
A single line comment will comment out a single line and is denoted with two forward
slashes // preceding it.
You can also use a single line comment to comment after a line of code:
console.log(5); // Prints 5
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:
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:
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!
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
6 min
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:
Add: +
Subtract: -
Multiply: *
Divide: /
Remainder: %
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.
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:
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.
Just like with regular math, we can combine, or chain, our operations to get a final result:
Properties
3 min
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
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
6 min
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.
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!
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
15 min
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:
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:
If you wanted to see the number printed to the terminal, you would still need to use a
console.log() statement:
To see all of the properties and methods on the Math object, take a look at the documentation
here.
Review
1 min
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 7 fundamental data types in JavaScript: strings, numbers, 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.
Variables
1 min
In programming, a variable is a container for a value. You can think of variables as little
containers for information that live in a computer’s memory. Information stored in variables,
such as a username, account number, or even personalized greeting can then be found in
memory.
Variables also provide a way of labeling data with a descriptive name, so our programs can be
understood more clearly by the reader and ourselves.
In short, variables label and store data in memory. There are only a few things you can do with
variables:
It is important to distinguish that variables are not values; they contain values and represent
them with a name. Observe the diagram with the colored boxes. Each box represents variables;
the values are represented by the content, and the name is represented with the label.
In this lesson, we will cover how to use the var, let, and const keywords to create variables.
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, variables. Prior to
the ES6, programmers could only use the var keyword to declare variables.
var, short for variable, is a JavaScript keyword that creates, or declares, a new variable.
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).
= is the assignment operator. It assigns the value ('Arya') to the variable (myName).
'Arya' is the value assigned (=) to the variable myName. You can also say that the myName
variable is initialized with a value of 'Arya'.
After the variable is declared, the string value 'Arya' is printed to the console by
referencing the variable name: console.log(myName).
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.
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 price;
console.log(price); // Output: undefined
price = 350;
console.log(price); // Output: 350
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.
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:
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.
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
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
5 min
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:
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:
String Interpolation
8 min
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:
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
4 min
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.
Let’s break down the first example. Since the value unknown1 is 'foo', a string, typeof unknown1
will return 'string'.
Review Variables
2 min
Nice work! This lesson introduced you to variables, a powerful concept you will use in all your
future programming endeavors.
CONDITIONAL STATEMENTS
1 min
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
7 min
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.
if (true) {
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
4 min
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) {
} else {
Comparison Operators
7 min
When writing conditional statements, sometimes we need to use different types of operators to
compare values. These operators are called comparison operators.
Comparison operators compare the value on the left with the value on the right. For instance:
We can also use comparison operators on different data types like strings:
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:
Logical Operators
10 min
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:
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:
} else {
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:
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.
6 min
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:
if (myVariable) {
console.log(myVariable)
} else {
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
let numberOfApples = 0;
if (numberOfApples){
} else {
}
// 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.
8 min
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 defaultName;
if (username) {
defaultName = username;
} else {
defaultName = '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
10 min
In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else
statement.
if (isNightTime) {
} else {
console.log('Turn off the lights!');
Like if...else statements, ternary operators can be used for conditions which evaluate to true
or false.
Else If Statements
10 min
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:
console.log('Stop!');
console.log('Slow down.');
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.
11 min
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 handling each of them differently. For
example:
let groceryItem = 'papaya';
} 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:
switch (groceryItem) {
case 'tomato':
break;
case 'lime':
break;
case 'papaya':
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
1 min
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.
FUNCTIONS
1 min
When first learning how to calculate the area of a rectangle, there’s a sequence of steps to
calculate the correct answer:
Measure the width of the rectangle.
Measure the height of the rectangle.
Multiply the width and height of the rectangle.
With practice, you can calculate the area of the rectangle without being instructed with these
three steps every time.
We can calculate the area of one rectangle with the following code:
const height = 6;
console.log(area); // Output: 60
const height1 = 6;
const width2 = 4;
const height2 = 9;
In programming, we often use code to perform a specific task multiple times. Instead of
rewriting the same code, we can group a block of code together and associate it with one task,
then we can reuse that block of code whenever we need to perform the task again. We achieve
this by creating a function. A function is a reusable block of code that groups together a
sequence of statements to perform a specific task.
In this lesson, you will learn how to create and use functions, and how they can be used to
create clearer and more concise code.
Function Declarations
7 min
In JavaScript, there are many ways to create a function. One way to create a function is by using
a function declaration. Just like how a variable declaration binds a value to a variable name, a
function declaration binds a function to a name, or an identifier. Take a look at the anatomy of a
function declaration below:
A function declaration consists of:
A function declaration is a function that is bound to an identifier, or name. In the next exercise
we’ll go over how to run the code inside the function body.
We should also be aware of the hoisting feature in JavaScript which allows access to function
declarations before they’re defined.
function greetWorld() {
console.log('Hello, World!');
}
Notice how hoisting allowed greetWorld() to be called before the greetWorld() function was
defined! Since hoisting isn’t considered good practice, we simply want you to be aware of this
feature.
If you want to read more about hoisting, check out MDN documentation on hoisting.
Calling a Function
5 min
However, a function declaration does not ask the code inside the function body to run, it just
declares the existence of the function. The code inside a function body runs, or executes, only
when the function is called.
To call a function in your code, you type the function name followed by parentheses.
This function call executes the function body, or all of the statements between the curly braces
8 min
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.
In the diagram above, calculateArea(), computes the area of a rectangle, based on two inputs,
width and height. The parameters are specified between the parenthesis as width and height,
and inside the function body, they act just like regular variables. width and height act as
placeholders for values that will be multiplied together.
When calling a function that has parameters, we specify the values in the parentheses that
follow the function name. The values that are passed to the function when it is called are called
arguments. Arguments can be passed to the function as values or variables.
In the function call above, the number 10 is passed as the width and 6 is passed as height.
Notice that the order in which arguments are passed and assigned follows the order that the
parameters are declared.
The variables rectWidth and rectHeight are initialized with the values for the height and width
of a rectangle before being used in the function call.
By using parameters, calculateArea() can be reused to compute the area of any rectangle!
Functions are a powerful tool in computer programming so let’s practice creating and calling
functions with parameters.
Default Parameters
5 min
One of the features added in ES6 is the ability to use default parameters. Default parameters
allow parameters to have a predetermined value in case there is no argument passed into the
function or if the argument is undefined when called.
Take a look at the code snippet below that uses a default parameter:
console.log(`Hello, ${name}!`)
}
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.
Return
11 min
When a function is called, the computer will run through the function’s code and evaluate the
result. By default, the resulting value is undefined.
}
console.log(rectangleArea(5, 7)) // Prints undefined
In the code example, we defined our function to calculate the area of a width and height
parameter. Then rectangleArea() is invoked with the arguments 5 and 7. But when we went to
print the results we got undefined. Did we write our function wrong? No! In fact, the function
worked fine, and the computer did calculate the area as 35, but we didn’t capture it. So how can
we do that? With the keyword return!
To pass back information from the function call, we use a return statement. To create a return
statement, we use the return keyword followed by the value that we wish to return. Like we saw
above, if the value is omitted, undefined is returned instead.
When a return statement is used in a function body, the execution of the function is stopped
and the code that follows it will not be executed. Look at the example below:
}
If an argument for width or height is less than 0, then rectangleArea() will return 'You need
positive integers to calculate area!'. The second return statement width * height will not
run.
The return keyword is powerful because it allows functions to produce an output. We can then
save the output to a variable for later use.
Helper Functions
10 min
We can also use the return value of a function inside another function. These functions being
called within another function are often referred to as helper functions. Since each function is
carrying out a specific task, it makes our code easier to read and debug if necessary.
If we wanted to define a function that converts the temperature from Celsius to Fahrenheit, we
could write two functions like:
function multiplyByNineFifths(number) {
};
function getFahrenheit(celsius) {
};
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.
Function Expressions
13 min
Another way to define a function is to use a function expression. To define a function inside an
expression, we can use the function keyword. In a function expression, the function name is
usually omitted. A function with no name is called an anonymous function. A function
expression is often stored in a variable in order to refer to it.
Declare a variable to make the variable’s name be the name, or identifier, of your
function. Since the release of ES6, it is common practice to use const as the keyword to
declare the variable.
Assign as that variable’s value an anonymous function created by using the function
keyword followed by a set of parentheses with possible parameters. Then a set of curly
braces that contain the function body.
To invoke a function expression, write the name of the variable in which the function is stored
followed by parentheses enclosing any arguments being passed into the function.
variableName(argument1, argument2)
Unlike function declarations, function expressions are not hoisted so they cannot be called
before they are defined.
Arrow Functions
3 min
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:
return area;
};
It’s important to be familiar with the multiple ways of writing functions because you will come
across each of these when reading other JavaScript code.
5 min
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:
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.
A function body composed of a single-line block does not need curly braces. Without the
curly braces, whatever that line evaluates will be automatically returned. The contents of
the block should immediately follow the arrow => and the return keyword can be
removed. This is referred to as implicit return.
So if we have a function:
};
The parentheses around num have been removed, since it has a single parameter.
The curly braces { } have been removed since the function consists of a single-line
block.
The return keyword has been removed since the function consists of a single-line block.
Review Functions
1 min
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:
To call a function in your code:
ES6 introduces new ways of handling arbitrary parameters through default parameters
which allow us to assign a default value to a parameter in case no argument is passed
into the function.
To return a value from a function, we use a return statement.
To define a function using function expressions:
It’s good to be aware of the differences between function expressions, arrow functions, and
function declarations. As you program more in JavaScript, you’ll see a wide variety of how these
function types are used.
SCOPE
Scope
1 min
An important idea in programming is scope. Scope defines where variables can be accessed or
referenced. While some variables can be accessed from anywhere within a program, other
variables may only be available in a specific context.
You can think of scope like the view of the night sky from your window. Everyone who lives on
the planet Earth is in the global scope of the stars. The stars are accessible globally. Meanwhile,
if you live in a city, you may see the city skyline or the river. The skyline and river are only
accessible locally in your city, but you can still see the stars that are available globally.
Over the next few exercises, we’ll explore how scope relates to variables and learn best
practices for variable declaration.
9 min
Before we talk more about scope, we first need to talk about blocks.
We’ve seen blocks used before in functions and if statements. A block is the code found inside
a set of curly braces {}. Blocks help us group one or more statements together and serve as an
important structural marker for our code.
console.log(color); // blue
if (dusk) {
console.log(color); // pink
In the next few exercises, we’ll see how blocks define the scope of variables.
Global Scope
8 min
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
Even though the color variable is defined outside of the block, it can be accessed in the
function block, giving it global scope.
In turn, color can be accessed within the returnSkyColor function block.
Let’s work with global variables to see how data can be accessible from any place within a
program.
Block Scope
7 min
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.
};
You’ll notice:
Scope Pollution
6 min
It may seem like a great idea to always make your variables accessible, but having too many
global variables can cause problems in a program.
When you declare global variables, they go to the global namespace. The global namespace
allows the variables to be accessible from anywhere in the program. These variables remain
there until the program finishes which means our global namespace can fill up really quickly.
Scope pollution is when we have too many global variables that exist in the global namespace,
or when we reuse variables across different scopes. Scope pollution makes it difficult to keep
track of our different variables and sets us up for potential accidents. For example, globally
scoped variables can collide with other variables that are more locally scoped, causing
unexpected behavior in our code.
Let’s look at an example of scope pollution in practice so we know how to avoid it:
console.log(num);
};
You’ll notice:
While it’s important to know what global scope is, it’s best practice to not define variables in the
global scope.
8 min
Given the challenges with global variables and scope pollution, we should follow best practices
for scoping our variables as tightly as possible using block scope.
Tightly scoping your variables will greatly improve your code in several ways:
It will make your code more legible since the blocks will organize your code into discrete
sections.
It makes your code more understandable since it clarifies which variables are associated
with different parts of the program rather than having to keep track of them line after
line!
It’s easier to maintain your code, since your code will be modular.
It will save memory in your code because it will cease to exist after the block finishes
running.
Here’s another example of how block scope works, as defined within an if block:
};
Block scope is a powerful tool in JavaScript, since it allows us to define variables with precision,
and not pollute the global namespace. If a variable does not need to exist outside a block— it
shouldn’t!
Review: Scope
1 min
In this lesson, you learned about scope and how it impacts the accessibility of different
variables.
Scope refers to where variables can be accessed throughout the program, and is
determined by where and how they are declared.
Blocks are statements that exist within curly braces {}.
Global scope refers to the context within which variables are accessible to every part of
the program.
Global variables are variables that exist within global scope.
Block scope refers to the context within which variables are accessible only within the
block they are defined.
Local variables are variables that exist within block scope.
Global namespace is the space in our code that contains globally scoped information.
Scope pollution is when too many variables exist in a namespace or variable names are
reused.
As you continue your coding journey, remember to use best practices when declaring your
variables! Scoping your variables tightly will ensure that your code has clean, organized, and
modular logic.
Introduction
4 min
You know a bunch about JavaScript syntax, control flow, and functions! The best way to reinforce these skills is
through practice. We’ve created a series of problems designed to use your JavaScript knowledge. We encourage you
to review relevant lessons, look things up in the documentation, check out the hints and solution code if you get
stuck, and, most of all, have fun!
The tasks provided are designed to be challenging. Throughout this code challenge, we’ll be running tests to check
that the functions you write are working correctly. We’ll often provide some example code to test your function. We
encourage you to write additional code to test your functions. To pass our tests, your function will need to work as
described in the prompt. This means your function may seem to be passing when you run it, but it will still fail the test
because it doesn’t run as expected in every situation we’re testing behind the scenes. Take special note of
strings—strings must be identical to that requested to pass!
Instructions
Checkpoint 1 Passed
1.
Write a function, greetWorld(). Your function should have no parameters and return the string
'Hello, World!'.
Helpful Notes:
Your function can be a function expression or a function declaration.
Notice that the prompt requires your function to return the string—it will not pass the test
if the string is printed to the console rather than returned.
Your code must return 'Hello, World!' exactly. The test will not pass with the
canIVote()
5 min
Instructions
Checkpoint 1 Passed
1.
The most common minimum age to vote is 18. Write a function canIVote() that takes in
a number, representing the person’s age, and returns the boolean true if they are 18
years old or older, and the boolean false if they are not.
agreeOrDisagree()
5 min
Instructions
Checkpoint 1 Passed
1.
Write a function, agreeOrDisagree(), that takes in two strings, and returns 'You agree!'
if the two strings are the same and 'You disagree!' if the two strings are different.
lifePhase()
14 min
Instructions
Checkpoint 1 Passed
1.
Write a function, lifePhase(), that takes in a person’s age, as a number, and returns
which phase of life they are in.
Here are the classifications:
0-3 should return 'baby'
4-12 should return 'child'
13-19 should return 'teen'
20-64 should return 'adult'
65-140 should return 'senior citizen'
If the number is less than 0 or greater than 140, the program should return 'This is
not a valid age'
finalGrade()
18 min
Instructions
Checkpoint 1 Passed
1.
Write a function, finalGrade(). It should:
take three arguments of type number
find the average of those three numbers
return the letter grade (as a string) that the average corresponds to
return ‘You have entered an invalid grade.’ if any of the three grades are
less than 0 or greater than 100
0-59 should return: 'F'
60-69 should return: 'D'
70-79 should return: 'C'
80-89 should return: 'B'
90-100 should return: 'A'
reportingForDuty()
5 min
Instructions
Checkpoint 1 Passed
1.
Write a function, reportingForDuty(), that has two string parameters, rank and
lastName, and returns a string in the following format: ‘rank lastName reporting for
duty!’
reportingForDuty('Private', 'Fido')
// Should return 'Private Fido reporting for duty!'
Instructions
Checkpoint 1 Passed
1.
We wrote a function, rollTheDice(), which is supposed to simulate two dice being
rolled and totalled. It’s close to doing what we want, but there’s something not quite
right. Can you fix our code, please?
console.log(rollTheDice());
calculateWeight()
13 min
Instructions
Checkpoint 1 Passed
1.
Though an object’s mass remains consistent throughout the universe, weight is
determined by the force of gravity on an object. Since different planets have
different gravity, the same object would weigh different amounts on each of
those planets! Cool, huh?
Write a function, calculateWeight(). It should:
have two parameters: earthWeight and planet
expect earthWeight to be a number
expect planet to be a string
return a number representing what that Earth-weight would equate to
on the planet passed in.
Handle the following cases:
'Mercury' weight = earthWeight * 0.378
'Venus' weight = earthWeight * 0.907
'Mars' weight = earthWeight * 0.377
'Jupiter' weight = earthWeight * 2.36
'Saturn' weight = earthWeight * 0.916
For all other inputs, return 'Invalid Planet Entry. Try: Mercury, Venus, Mars,
Jupiter, or Saturn.'
truthyOrFalsy()
6 min
Instructions
Checkpoint 1 Passed
1.
It can be hard to keep track of what’s truthy or falsy in JavaScript. Write a function,
truthyOrFalsy(), that takes in any value and returns true if that value is truthy and
false if that value is falsy.
numImaginaryFriends()
5 min
Instructions
Checkpoint 1 Passed
1.
A person’s number of imaginary friends are always 25% (or 1/4) of their total friends.
Write a function, numImaginaryFriends(), that takes in the total number of friends a
person has and returns the number of imaginary friends they have.
Since friends can only come in whole numbers, be sure to round your result up to the
nearest whole number before returning it.
The JavaScript Math.ceil() function will come in handy. Check out the documentation
here to figure out how it works.
sillySentence()
5 min
Instructions
Checkpoint 1 Passed
1.
Write a function, sillySentence(), that has 3 string parameters and returns the
following silly sentence with the blanks filled in by the arguments passed into the
function:
sillySentence('excited', 'love', 'functions');
// Should return 'I am so excited because I love coding! Time to
write some more awesome functions!'
howOld()
23 min
Instructions
Checkpoint 1 Passed
1.
Write a function, howOld(), that has two number parameters, age and year, and
returns how old someone who is currently that age was (or will be) during that
year. Handle three different cases:
If the year is in the future, you should return a string in the following
format:
'You will be [calculated age] in the year [year passed in]'
If the year is before they were born, you should return a string in the
following format:
'The year [year passed in] was [calculated number of years]
years before you were born'
If the year is in the past but not before the person was born, you should
return a string in the following format:
'You were [calculated age] in the year [year passed in]'
Instructions
Checkpoint 1 Passed
1.
Given the percentage of DNA shared between two people, you can calculate
their likely familial relationship.
We wrote a function, whatRelation(), that has one number parameter,
percentSharedDNA, and returns the likely relationship. We expect the number
passed in to always be an integer from 0 to 100, but for some reason it’s not
working!
Here’s how it’s supposed to calculate the relationship:
100 should return 'You are likely identical twins.'
35-99 should return 'You are likely parent and child or full
siblings.'
tipCalculator()
8 min
Instructions
Checkpoint 1 Passed
1.
Create a function, tipCalculator(), that has two parameters, a string representing the
quality of the service received and a number representing the total cost.
Return the tip, as a number, based on the following:
‘bad’ should return a 5% tip
‘ok’ should return a 15% tip
‘good’ should return a 20% tip
‘excellent’ should return a 30% tip
all other inputs should default to 18%
tipCalculator('good', 100) // Should return 20
toEmoticon()
6 min
Instructions
Checkpoint 1 Passed
1.
Write a function, toEmoticon(), that takes in a string and returns the corresponding
emoticon as a string. Use a switch/case, and cover these cases:
'shrug' should return '|_{"}_|'
'smiley face' should return ':)'
'frowny face' should return':('
'winky face' should return ';)'
'heart' should return '<3'
any other input should return '|_(* ~ *)_|'
development. JS code is normally added using the HTML <script> element for executing in
web browsers, but most modern browsers also provide a console as part of their developer
tools where we can directly write and run JS, typically for testing and debugging purposes. The
logging to the console. The console itself is also the place to view the messages that were
logged by JS code, as well as any other information that the browser had documented,
In this article, we’ll walk through how to open the developer console and run JS code right in
your browser!
as well as your computer’s operating system. But generally, you should be able to bring up the
developer tools by right clicking and selecting Inspect or Inspect Element, and then
navigate to the Console tab from there. (If you are using Apple Safari, you will first need to go
to your Preferences and check the “Show Develop menu in menu bar” option under the
Advanced tab.) Below are some alternative ways of bringing up the console:
Google Chrome
Mac
Cmd + Opt + J
Windows
Ctrl + Shift + J
Mozilla Firefox
Mac
Cmd + Opt + K
Windows
Ctrl + Shift + K
Open menu (3-bar icon ☰) > Web Developer > Web Console
Microsoft Edge
Mac
Cmd + Opt + J
Windows
Settings and more (3-dot icon ⋯) > More tools > Developer
Apple Safari
Mac
Cmd + Opt + C
We’ll be using Google Chrome for the following examples — also, feel free to try to follow along
with the examples! When you pull up the console, you might see some messages that have
been logged by the browser, depending on what site you’re on. If you do, feel free to run
by typing it after the > prompt and hitting Enter/Return. The expression will be evaluated, and
the return value is printed to the console on the next line following the < arrow:
Similarly, we can use comparison operators to compare values, which will evaluate to true or
false:
In some newer browsers, you may notice that the console displays a preview of the return
as calling functions and methods. A list of the built-in functions and objects that are available
to use in the console can be found in the MDN web docs. For example, Math.sqrt() returns
The console object can also be accessed in the web browser’s console. Most frequently, it is
Notice that two new lines appear after running the previous code, one preceded by the < arrow
and one without. This is because console.log() simply prints the message to the console
and does not return anything. Thus, the first line we see is the logged message, and the
second line that starts with < is the return value, or undefined.
We can also write our own functions in the console. In the example below, we define a function
called addTwo() which logs a message to the console, then returns the input number plus 2:
Because the function declaration itself does not evaluate to any value, undefined is returned
When we call the addTwo() function, Evaluating... is first outputted to the console from
our console.log() call. Then, the function’s return value—which is what the function call
have opened in the browser. But what makes the console particularly useful is that we could
also directly inspect and modify the page’s DOM if we wanted to. Let’s look at a simple
To bring up a blank page, we can enter about:blank into the browser’s address bar. We can
confirm that there is no HTML inside the <body> element of the page by checking
the body, as seen below. Once we run the following code, the change will immediately be
element. This shorthand resembles jQuery syntax and helps make manipulating the DOM
the color property to "blue". This statement returns the value "blue" to the console, and
Conclusion
As we can see, the console provides a quick and convenient way of running any JS code in the
browser, whether independent of or directly related to the page content. If any edits are made
to the page, the changes are temporary and will be gone upon refreshing, which works great
for testing purposes when you don’t want to modify the actual code. Combined with the other
developer tools offered by browsers, we can see how the console can quickly become an
objects your program can access and it can also impact how it runs. This article covers the two
using any text editor, you could create a file on your own computer called my_website.html and
Save your file, then open your favorite browser. Most browsers will allow you to load websites
that you have created locally by going to the menu File > Open File > my_website.html.
Upon loading, the embedded <script></script> will execute and the window.alert()
method will create a pop-up box in your browser with the text "Hello World". How is this
possible? Where did the window.alert() method come from and how can it control your
browser?
The answer is that you are executing this code in the browser’s runtime environment. The
window.alert() method is built into this environment and any program executed in a
browser has access to this method. In fact, the window object provides access to a huge
amount of data and functionality relating to the open browser window beyond just .alert().
Try replacing window.alert() with window.prompt() or window.confirm()
Applications created for and executed in the browser are known as front-end applications. For
a long time, JavaScript code could only be executed in a browser and was used exclusively for
creating front-end applications. In order to create back-end applications that could run on a
computer WITHOUT a browser, you would need to use other programming languages such as
Java or PHP.
code without a browser, thus enabling programmers to create full-stack (front-end and
values and functions, like window.alert(), can’t be used. Instead, the Node runtime
browser, such as access to the server’s file system, database, and network.
For example, suppose you created a file called my-app.js. We can check to see the directory
that this file is located in using the Node runtime environment variable process:
// my-app.js
console.log(process.env.PWD);
Notice that we are using console.log now instead of window.alert() since the window
process is an object containing data relating to the JavaScript file being executed.
which contains the current working directory (and stands for “Print Working Directory”).
To execute the JavaScript code in this file, first make sure that you have set up Node on your
The node command tells your computer to execute the my-app.js file in the Node
environment. You can also use the node command without a file argument to open up the
$ node
> process.env.HOME
'/home/ccuser'
Summary
A runtime environment is where your program will be executed. JavaScript code may be
In each of these environments, different data values and functions are available, and these
Back-end JavaScript applications are executed in the Node runtime environment and
have access to the file system, databases, and networks attached to the server.
Setting Up Node Locally
Learn how to download Node on your local machine, so you can use the powerful Node.js
runtime from your own computer.
What is Node?
Node.js is a JavaScript runtime, or an environment which runs JavaScript code outside of the
language and compiles it down to code the computer can execute. Node was created with the
goal of building web servers and web applications in JavaScript, but it’s a powerful and flexible
environment that can be used for building all sorts of applications. Check out our course on
Installing Node
When you’re ready, running Node on your own computer is an exciting step towards becoming a
developer. Playing on the Node REPL in your own terminal and executing your first local
JavaScript program will set you on your way to building all sorts of exciting projects.
Before you install Node, you’ll need to make sure you have your command line set up.
Navigate to the Node website, and download the version of Node labeled “LTS” on the main
page. For additional download options, such as different operating systems and versions, you
After your download is complete, open the downloaded installation package and follow the
installation instructions.
After installation, open a new terminal window. To confirm Node was downloaded, you can run
the terminal command which node which will print the filepath to Node. You can also check
which version of Node you downloaded with the node -v terminal command.
Note: The current LTS version of Node.js is v14.17.1. The Node version used in the videos below is
older, but the installation process remains the same. If the node command is not found, try closing
Read and write JavaScript syntax for arrays, loops, objects, and iterators