0% found this document useful (0 votes)
4 views75 pages

PART 2 - Programming With JavaScript

This document provides an overview of a JavaScript programming course designed for new developers, covering essential topics such as variables, functions, and programming paradigms. It emphasizes JavaScript's significance in web development and its versatility across front-end and back-end applications. The course includes practical modules on testing, compatibility, and culminates in a graded assessment project, preparing learners for various job opportunities in the tech industry.

Uploaded by

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

PART 2 - Programming With JavaScript

This document provides an overview of a JavaScript programming course designed for new developers, covering essential topics such as variables, functions, and programming paradigms. It emphasizes JavaScript's significance in web development and its versatility across front-end and back-end applications. The course includes practical modules on testing, compatibility, and culminates in a graded assessment project, preparing learners for various job opportunities in the tech industry.

Uploaded by

Natalia Olivera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to Programming with JavaScript

So much of what you take for granted in your everyday online life, like using a search
engine, shopping, and using social media, is made possible by JavaScript. Nearly all
of the interactivity you experience online, like drop-down menus or the autocomplete
function, is facilitated by JavaScript. JavaScript is most well-known for being the
programming language of the web. But it has become so much more. Now, it is used
not only for the front-end development, but also for back-end development, and you
can even create mobile apps using JavaScript and React. Without JavaScript, the
modern software development landscape would look a lot different. Because it is
such a powerful tool and so integral to software development, it is important for you,
as a new developer, to know how it works and how to use it. In this course, starting
with Module 1, you will cover an introduction to JavaScript, that will help you
understand how it is used in the real-world. You'll learn how to set up Visual Studio
Code and install the code runner extinction. This module also introduces you to
programming in JavaScript, which includes learning about variables, datatypes,
operators, strings, booleans, and numbers. After this, you'll progress to learning
about conditional statements and loops. In Module 2, you will build on what you've
learned in the first module, by learning about arrays, objects, and functions. You will
also learn about bugs and errors. In Module 3, you will learn about the functional
programming and object-oriented programming paradigm, which includes function
calling, recursion, and scope. With scoping, you will learn how to use var, let, and
const. Furthermore, you will learn about object-oriented programming, and you will
design and build an object-oriented program. You will also learn about advanced
JavaScript features, like destructuring arrays and objects using four of loops and
template literals. Additionally, you will learn about data structures and the spread and
rest operators. You will also learn how JavaScript is used in the browser. In this
module, you will have an opportunity to practice updating the contents of a webpage.
Module 4 is all about testing and compatibility. Therefore, you will learn about types
of testing and you'll write a unit test. You will also be introduced to Jest and learn
how to write tests with Jest in an exercise. You will learn about test-driven
development and get to practice applying it too. You will also learn about JavaScript
testing challenges, which include learning about webpack, transpiling, and working
with arrow functions in React. As part of this module, you will also learn about other
JavaScript environments, like Node and NPM. In Module 5, you will have an
opportunity to put your new skills into practice by creating the little lemon receipt
maker. In summary, this course provides you with an introduction to JavaScript. It is
part of a program of courses that leads you towards a career in software
development. You have probably encountered many new technical words and
terminology in this video. Don't worry if you don't fully understand all these terms
right now, everything will become clear soon. After all, this is part of the reason why
you were taking this course.
How is JavaScript used in the real world?
Anytime you're using a browser, anytime you're browsing the Internet, you are using
JavaScript. It's the language of the Internet.
Play video starting at ::13 and follow transcript

0:13
My name is Murtadha. I'm a software engineer at Meta based in the Seattle office.
I've been coding in JavaScript since 2012, so JavaScript is actually something that
as you're watching me now through this video, it's something that you're using
probably as you made your coffee this morning, maybe your coffee maker had some
JavaScript, your car might have JavaScript. Nowadays, we are in a world where
JavaScript is so common and so used across a lot of technologies and a lot of
devices that it's become a language that cannot be replaced. The first time I use
JavaScript was, I was an intern at the time Facebook and then the time JavaScript
had not been as popular and as common. I hadn't actually learned it in university or
in my courses. The other more attractive or interesting languages at the time were
people writing in Java or C plus, plus. People used to sometimes not take JavaScript
very seriously and think like it's a language that's not used by real and serious
developers. But now we see the world runs using JavaScript and just about every
application we interact with today probably has some JavaScript in it, one way or
another. What are the things that makes JavaScript so popular and important is that
it's the only language that is used in web development. In game development or
other types of applications. There are choices to use other languages like you could
use C plus plus or you could use Java, or you could use other things. But when it
comes to web development, the only available language is JavaScript, and that's
what makes it so popular and common and important to learn when you're
developing web applications. At Metta, we use JavaScript in our entire web stack,
but we also use JavaScript in other places too. One of the unique things about
JavaScript that no other language has is that it's a language that can be used for
writing the front-end and the back-end, so a lot of applications, they have a back-
end, maybe in Python or PHP or Java or something else. But they're required to
have a JavaScript front-end because that's the only language of the front end. But
because JavaScript can also be used on the backend if you design your application
and if you choose to make it consistently JavaScript across the entire stack,
sometimes that may simplify the application and then you don't have to learn multiple
languages or maintain code bases that are written in different languages. Some of
the challenges that I faced when switching between other languages, like I had been
used to Java and came to the world of JavaScript. Even though they seem like they
might be very similar they're like half of the name is the same. But actually it turns
out there are some things in JavaScript that are specific and they are very unique to
its language. There are certain things about JavaScript that are a little inconsistent
when compared to other programming languages like you have your C plus plus and
Java and some other languages that follow certain behaviors, and then JavaScript is
sometimes in its own corner doing weird things. But I actually find that a lot of times
JavaScript is easier to learn than some of these other languages, so even in its
weirdness and in its quirks and some of the things that are confusing about it,
overall, I find it an easier language to learn and use than these other ones. As you're
learning JavaScript, you'll stumble upon challenges and you might find that things
are not making sense. I encourage you to power through them, and you will find that
with time, you will likely come to enjoy and love this language. At this point, we live in
a world where JavaScript is so commonly used across devices and technologies. I
can't comprehend or think of all the different applications or places that are running
JavaScript in them. As you as developer who's learning coding, it's an important skill
to have and you'll find that many employers will be interested in hiring you if you can
code in JavaScript. Give it a shot and be patient with it. If it confuses you or
frustrates you, don't let that stop you from going through. Do the thing at the end too.

Course syllabus
This course is the second of a series that aims to help you learn more about web
development.

In this course, you will explore the following:

Module 1: Introduction to JavaScript

In this module, you are introduced to JavaScript. You'll learn why JavaScript is so
integral to software development. And you'll get an overview of how to write
JavaScript code inside the browser. Furthermore, you will learn about the most
common operators as well as conditional statements and loops.

After completing this module, you will be able to:

● Explain the importance of JavaScript in software development


● Demonstrate how to write JavaScript code inside the browser
● Demonstrate how to write basic JavaScript code
● List common operators, conditional statements and loops
● Demonstrate how to use variables and output their value in the console
Module 2: The building blocks of a program

Here you'll learn how to use objects, arrays and functions. In addition, you will learn
about the most common built-in methods, and the difference between undefined, null
and empty strings. And you'll explore both error handling and defensive
programming.

After completing this module, you will be able to:

● Build and use objects, arrays, and functions


● List some common built-in methods on built-in objects
● Describe handling bugs and errors using try, catch, throw, and defensive
programming
● Explain the difference between undefined, null, and empty strings
● Demonstrate how to write basic code using arrays, objects and functions

Module 3: Programming paradigms

This module is about functional programming and the object oriented programming
paradigm. You will learn what scope is in JavaScript. You'll explore the differences
between var, let and const. And you'll learn how to use classes and inheritance in
object oriented programming. Additionally, you'll explore how to use write JavaScript
using modern features like spread and rest. You will build code that can manipulate
the DOM and handle events. And you will use JSON in JavaScript.

After completing this module, you will be able to:

● Outline the tenets of the functional programming and object oriented


programming paradigm
● Describe how scope works in JavaScript
● List the differences between var, let, and const
● Use classes and inheritance in OOP in JavaScript
● Write JavaScript code using more modern features like spread, rest, template
strings and modules
● Build code that manipulates the DOM and handles events
● Use JSON in JavaScript
Module 4: Testing and compatibility

Here you will learn about [Link] and npm. And you will explore how to install npm
packages and how to work with [Link]. Furthermore, you will learn about
testing in JavaScript and you'll code a simple unit test in Jest.

After completing this module, you will be able to:

● Describe [Link] and npm


● Explain how to install npm packages
● Describe how to work with [Link]
● Explain the process of testing in JavaScript
● List the three most prevalent kinds of testing
● Demonstrate how to code a simple unit test in Jest

Module 5: Graded assessment

In the final module, you'll learn about the graded assessment. After you complete the
individual units in this module, you'll synthesize the skills you gained from the course
to create code for the "Little lemon receipt maker ".

You'll also have to opportunity to reflect on the course content and the learning path
that lies ahead.

How to uncover job


opportunities
Learning how to program in JavaScript helps you prepare for a wide range of job
opportunities. This is in part because it expands the possibilities of what you can
build as a developer.

JavaScript is one of the most in-demand programming languages, as it is used in


nearly all active websites. Its versatility enables developers to use popular libraries,
plugins, and frameworks such as React, which improves efficiency and productivity.

With all flexibility that programming in JavaScript brings, it is no surprise that there
are different careers that you might want to follow. However, no matter what career
path you choose, you will always want to learn other technologies like HTML, CSS,
React, [Link], or Python, so you are more marketable.

Let’s cover a few of the most common roles you can get if you know how to program
in JavaScript.

Mobile Developer
There has been a constant increase in the demand for mobile developers as mobile
devices’ use for accessing the internet has been on the rise. Mobile developers
specialize in building apps for platforms like Google’s Android and Apple’s iOS.
Many developers choose to use React Native, which allows them to build one
application using JavaScript that works on both Android and iOS devices. Mobile
developers work with UX and UI designers and use React’s UI capabilities to
implement functionalities that customers will use. Mobile developers also make sure
that the front-end and the back-end of the applications work seamlessly. Other skills
that mobile developers may have include HTML, CSS, Java, Kotlin, Objective-C, C+
+, C#, among others.

Front-End Developer
As the name implies, front-end developers build the user-facing parts of websites
and apps. They work closely with designers to implement visual and interactive
elements through coding, using HTML, CSS, and of course, JavaScript. They also
use libraries and frameworks like React to save time and make their work more
efficient. Front-end developers may also be responsible for making sure the final
user has a good user experience and that websites and apps behave as expected
and are free of errors and bugs.

Back-End Developer
Back-end developers work on the back-end of websites and applications. They can
use JavaScript with [Link] to develop back-end functionalities. Among these
functionalities are streaming and chat-based applications, as well as JSON APIs and
serverless functions. Back-end developers possess additional skills, including
professional working knowledge of Python, APIs, cloud infrastructure, and database.

Full-Stack Developer
As you might guess, a full-stack developer works with both the front- and back-end
of building websites and apps. So, these professionals combine the skills in these
two areas. They can use frameworks like React to work on the front-end and [Link]
to work on the back-end. They also apply skills in addition to JavaScript to build
websites and apps.

Your professional journey ahead

As you embark on the exciting career as a professional developer, you will realize
that you will progressively expand your skills to include a wide range of technologies
and programming languages besides JavaScript.

If you want to have an idea of the opportunities available in these areas, you might
want to check your favorite job search website or app and look for jobs related to
JavaScript. You will learn that there is no shortage of opportunities. And as you start
reading more about these roles, you will find that JavaScript is often only one of the
competencies that employers are looking for.

But don’t worry, as you advance in your studies and in your career, you will further
develop your skills to focus on the professional path you want to follow.

Good luck on your professional journey!

Additional resources
Here is a list of resources that may be helpful as you continue your learning journey.

These resources provide some more in-depth information on the topics covered in
this module.

Mozilla Developer Network Expressions and Operators

Mozilla Developer Network Operator Precedence and Associativity

JavaScript Primitive Values

ECMA262 Specification

jQuery Official Website

React Official Website

StackOverflow Developer Survey 2021 Most Popular Technologies

Emojis

Why JavaScript?
In the last few hours or maybe even in the last few minutes, you've probably
interacted with web pages to do things like watch videos, look for locations on maps,
or interact with your social media feeds. In fact you're doing it right now with this
course. But what makes this interactivity possible? The programming language
JavaScript. Let's find out a bit more about the benefits of JavaScript and its
importance to developers. JavaScript is a language that builds interactivity into web
pages. It is literally the language of the web. Almost every website runs JavaScript in
some form or another. The reason for this is the fact that since its very inception In
1995, JavaScript has been the main way to interact with web pages on the client
side, the front and side of websites and web applications. Using JavaScript updates
are displayed in real time on our devices. Some common examples include
interactive maps and client side form validation. Over the years, there have been
some alternatives to JavaScript, such as VBScript and more recently TypeScript. But
even typescript compiles down to JavaScript so browsers can understand it. Since
JavaScript is one of the most widely available and frequently used methods for
interacting with the browser on the client side, the language became immensely
popular. In fact, developer surveys often show that JavaScript remains one of the
most popular programming languages today. So what is it that makes JavaScript so
integral to modern browsers. JavaScript is currently the only computer language that
allows us to directly interact with our web pages dynamically on the client. It's baked
into the browser. Its enduring popularity is down to the rules of backwards
compatibility, which states that all websites that were built in the past still need to
work today. So removing JavaScript from the browser would effectively render
millions of websites completely useless. This means that JavaScript is in the unique
position of being one of several central pillars of web development. You've just
discovered the importance of JavaScript to web development. JavaScript unique
ecosystem is one of the main reasons for its popularity. Simply put, browsers speak
JavaScript. But there are a few other important reasons why we should embrace
JavaScript. One of the main reasons that developers use JavaScript is because of
how easy it is to use. There are many programming languages where a newcomer
needs to do a substantial amount of prep work to even get set up and ready to learn.
However, with JavaScript it's as simple as opening the browser's developer tools and
navigating to the console tab because every browser has a JavaScript engine built in
and you can interact with it using the console. There are still a few small steps
required to get started with JavaScript. These include installing a code editor and
possibly setting up some other things such as [Link] and NPM. But initially as a
beginner, it's enough to just open the developer tools on your web browser.
Play video starting at :3:21 and follow transcript

3:21
Another reason to learn and use JavaScript is because as we saw earlier, it's
everywhere. JavaScript is used in almost every website there is. It's used on the
client side of sites as plain JavaScript also known as vanilla JavaScript. It fuels a
myriad of JavaScript frameworks such as React, Vue, and D3 and it's also used on
the server as [Link] and more recently Deno. Another reason why people often
choose JavaScript is that it's considered one of the more accessible programming
languages. It also has a wide development community to offer help and guidance.
This is especially true when it's compared to other languages. There are many
languages that for a variety of reasons would be very challenging to begin
programming with. But because it's so approachable, JavaScript can be a great way
for new developers to jump into programming. So besides being a useful skill on its
own, JavaScript can also be a stepping stone to other languages and technologies.
Finally, one more reason to learn JavaScript is because JavaScript skills are in
demand. Countless job postings appear for JavaScript developers every day and
these will keep coming for the foreseeable future. So next time you ask why choose
JavaScript remember that it's the foundation of technology of everything you do
online with a huge variety of uses. Plus it's easy to get started with and once you're
up and running there's lots of job offers and projects open to you. Best of luck with
your JavaScript journey.
Writing your first Javascript
code

In this reading, you'll learn about comments in JavaScript. Additionally, you'll learn
about the semi-colon in JavaScript: what it does and why it is used. You will then
download a browser if you don't have one installed and run your first piece of
JavaScript using the Console.

Comments in JavaScript

I've chosen comments as the starting point for two reasons:

1. Their syntax - the way comments are written is easy to understand.


2. Writing comments can empower you as a developer.

First, I'll explain the syntax, and after that, I'll discuss why being able to write
comments is so empowering.

Comments in JavaScript: the syntax

There are two varieties of comments in JavaScript:


1. Single-line comments
2. Multi-line comments

A single-line comment is created when you add two forward-slash characters one
after the other, without spaces.

// this is a comment!

Anything that follows a single-line comment in JavaScript is ignored by the browser.

This means that, essentially, you can write any kind of text, code, characters, emojis,
whatever - and the browser will ignore it.

A multi-line comment, as its name says, spans for several lines of code and is
created with a forward slash and a star. For example:

2
3

/*

this

is

multi-line

comment
*/

You can also use the multi-line comment syntax on a single line of code, as follows:

/* this is a multi-line comment on a single line */

Why writing comments is empowering

In this course, it is assumed that you've never written a single line of JavaScript
code.

With this assumption in mind, consider the effects of what you've just learned, that is,
the effects of learning how to write comments in JavaScript:

1. You can now freely express your ideas about any code that you write.
2. You can add comments to any code that already exists.
3. Those comments can be intended for your future self, or for colleagues on
your development team.

So, comments are empowering because they facilitate communication with your
future self or with your team members, allowing you to ask questions about the code,
mark the code as "to do", or as "to improve", or just simply explain what a given
piece of code does.

Additionally, you can even comment out some working code in a JavaScript file - to
prevent it from running.

Effectively, comments allow you to "switch off" pieces of JavaScript code.

There can be many reasons for that:

1. Trying to understand how a given piece of code works.


2. Testing different solutions to a coding problem - while not having to delete
existing code.
3. Debugging - trying to pin-point why your code is broken or behaving
unpredictably.

The semi-colon in JavaScript

In the English language, the fullstop or period - the . character - is used to separate
thoughts into sentences.

By clearly separating thoughts with the fullstop, you avoid being misunderstood.
In JavaScript, the semi-colon - the ; character - has a similar purpose: it is used to
clearly delimit parts of the code from some other parts of the code.

Automatic Semi-Colon Insertion (ASI)

Interestingly, the browser has a feature known as "Automatic Semi-colon Insertion" -


meaning, it does a pretty good job of "filling in the blanks" in case there is a missing
semi-colon where there should be one.

Effectively, what that means for developers is that most of the time, it makes no
difference if a semi-colon is added or not, since the browser is likely to figure it out
anyway.

That's why some developers say that you shouldn't bother with adding semi-colons
at all.

However, other developers argue that it's better to use it wherever it's needed - for
the sake of clarity.

The truth is that most of the time, you can think of adding semi-colons in JavaScript
as optional - and somewhat of a stylistic preference.

A note on using the console in the developer tools in your


browser
As already mentioned earlier on in this course, one of the reasons why JavaScript is
so popular is because it's so approachable.

To get started with JavaScript, all you need is a browser. In this course I'll be using
Google Chrome.

Once you've installed the browser and run it, right-click on the currently active web
page and click the Inspect command on the right-click contextual menu.

This will open the Developer Tools and then you can click on the Console tab to
open the console, or alternatively, pressing the ESC key will toggle on and off the
console regardless of the currently active Developer Tools panel.

You can type any JavaScript command you like into the DevTools console.

If you need to type multiple lines of code before you run them,
make sure to press the SHIFT + ENTER shortcut key to get
onto the next line.

Notice the distinction between pressing the ENTER key to run the JavaScript code
you've typed, versus pressing the SHIFT + ENTER shortcut to move onto the next
line of code (rather than running the code you've already typed up).

This is all that you need to get started writing JavaScript code!
In the upcoming lessons, feel free to follow along in either of two ways:

1. Using the VS Code editor and the Code Runner extension as previously
described
2. Using the Chrome browser itself, and running the code inside the DevTools
console as described in this reading

Output a greeting into the console

Now that you know how to get to the Developer Tools' Console tab, let's now use it
to run your first piece of real JavaScript code.

In Chrome, with the Developer Tools open, click into the empty space in the console
tab, just to the right of the blue > character. You should see a blinking vertical line
(also referred to as "the cursor"). The cursor indicates that you can type into the
console.

If you type valid JavaScript code, it will be executed, meaning: it will be processed
and it might result in some kind of output.

You'll now use the [Link] function to output the words "Hello, World".

To do so, type the following command into the console:


1

[Link]("Hello, World");

If you've done everything as instructed, the words "Hello, World" should be output in
the console.

Here's another, more complex command, to show you that the [Link]
command comes with a number of tricks.

For example, did you know that you can style the output in the console?
In this code snippet, there are a few additions: the font size is different and the color
is blue:

[Link]("%cHello, World", "color: blue; font-size: 40px");

console log with percentage c authors

If you copy-paste this piece of code, or perhaps, simply type it into the console, once
you press the ENTER key to run it, you'll get the words "Hello, World" output to the
console. This time, however, the color of the letters will be blue, and the font size will
be 40px. So, you've just learned a nice trick with the console.
If you add the %c right after the " character, you can then style the console output by
adding the , character after the second ", and then, inside another pair of " and "
characters, use valid CSS code to style the words you want to output in the console.

The reason for showing you this little trick was to hopefully get you motivated to
practice writing various words into the [Link] command, and to use your
CSS skills to change the styling of these words in the console output. That way, you
might find it fun to practice this newly acquired skill - and learning and fun always go
nicely together.

Output multiple words into the console

To output multiple words into the console, you can join them using the + character,
formally known as the "concatenation operator" when we're joining pieces of text, or
the "addition operator", for performing the mathematical operation of adding two
numbers.

Here is an example of joining three separate pieces of text: [Link]("Hello


" + "there, " + "World"). The output of this command will be: Hello there,
World.

Here is an example of outputting three separate pieces of text using the , character
instead:

[Link]("Hello", "there,", "World")


The output of this command will still be: Hello there, World.

Note: You may observe slight variations in the spacing between words due to default
browser settings.

Using , in [Link] does not combine the arguments into a single string but
outputs them as separate values, automatically adding a space between them. This
behavior contrasts with +, which concatenates all pieces into a single string without
adding spaces unless explicitly included.

Variables
When you start programming in JavaScript, it helps to think of an empty JavaScript
program as the first level of a sandbox game. The world is still empty, but there's
some underlying structure to it to build on. That structure needs to be there so that
you can write custom JavaScript code in the first place. However, besides the
underlying structure, a new JavaScript program is like a blank slate for you to build
on. It's up to you, the programmer using JavaScript, to say, let's build this world. An
important part of this process is knowing how to use variables. In this video, you will
learn how to identify what a variable is and why you need it, distinguish between
variable declaration and variable assignment and describe how to get a variable's
value and reassign it. Let me demonstrate this now, using some code to assign a
value to a variable and output it to the console. Right now, I have the Developer
Tools panel open in my web browser. You can access this by pressing ''F12'' on
Windows and Linux, or command option "I" on Mac then I select the console tab.
This works with any browser, and for this example, I'm using Google Chrome. Now I
want to give JavaScript some idea of what I want to build, and I start by adding a
person's name. I do this by typing John in double quotation marks. JavaScript
receives this person's name and accepts it. There are no errors. This means I've
given it some valid data, something that JavaScript can work with. Now let's say that
I want JavaScript to say, "Hello John". In other words, I want it to use the name that I
gave JavaScript and I want it to greet the person. But how do I do it? If I type, "Hello
John", I'm just typing the whole thing myself. I really want JavaScript to use the
name I provided, so I don't have to keep retyping it. This is where variables come in.
By using a variable, I can save the name John, so that I can reuse it in the future. To
save this name in a variable, I'll start with the keyword, var, and use it to signal to
JavaScript that I'm giving it a value that I wanted to reuse. To declare a variable, I
type the keyword, var. Now, I need to declare a fact about this world that I'm building,
so I type, person semicolon and press "Enter". Great. I've just declared my variable,
person. I've given JavaScript one fact about the world that I'm building. The fact that
there is a value that I'd like to reuse and that this value is accessible using the word
person. Thus I have completed the variable declaration. However, I still haven't given
a name to the person variable. In programming jargon, I'd say that the person
variable hasn't been assigned a value yet. The person variable is still undefined. In
other words, for the person variable to hold the value of John, I need to assign the
value of John to the person variable. To do this, I'll use the assignment operator, the
equals sign. Operators perform certain operations, and the assignment operator's
purpose is to take the value that is on its right and put it into what it's on its left. To
assign the name John to the variable person, I type var person equals John in-
between quotes. I've taken the value John and assigned it to the person variable
using the assignment operator. To confirm that this is really the case, let me inspect
the contents of the person variable by typing, person semicolon. It returns John as
the result. Now that I have this value in a variable, I no longer have to type John
every time I want to use it.
I can have JavaScript output the text, "Hello John" to the console by using the built-
in [Link] method. This is a common approach to outputting values in
JavaScript. Notice that the browser is intelligently trying to guess what programming
statement I want as I type. Don't worry about this now. I just want you to concentrate
on variables and the [Link] method. The [Link] method can accept one or
more values separated by commas. So, I type [Link], open parenthesis then I
type ''Hello'' in quotes, comma, person for the variable and then close parenthesis.
Notice that "Hello John" is now logged to the console.

This is an example of combining static text with a dynamic variable where the value
can change. But why stop here? Why not save the greeting in a variable too? Let's
create another variable and call it, greeting, and assign this new variable the value,
hello, in quotation marks. Now, when I use the [Link] method with both
variables, greeting and person, the words or the values of these variables, ''Hello
John'' are logged to the console. Finally, let me show you why variables are so
useful. Now that I have the person and the greeting variables, I can reassign them,
replacing their stored values. For example, I can change the value of the variable
from hello to hi by typing greeting equals hi in quotation marks. Similarly, I can
change the value of the variable person from John to James by doing the same
thing. I type person for the variable then equals and finally James in quotation marks.
Now, the value of the variable, greeting, is hi, and the value of the variable, person,
is James. Notice that now I haven't used the var keyword when I reassigned the
values to the variables that I created earlier.
That's because JavaScript already knows that these variables exist in the world that
I'm building. But the variables don't have to be static and unchangeable. That would
be a pretty boring world. Now, I run the exact same piece of code as before by typing
[Link] and the name of the variables. Notice that I'll get a completely different
result logged to the console, hi James. This is very important because it allows me to
use the same code and get different results. This is the power of variables. If you
want to find out more, there is an additional reading at the end of this lesson.
Congratulations. You now know how to create a variable in JavaScript. Variables
allow us to make the exact same code produce different results, making our
programs versatile.

Data types

Imagine for a moment that you are faced with the task of moving all your belongings
to a new place. What steps would you take to make the process more efficient? Well,
you probably start by sorting items and packing them into boxes and then labeling
those boxes so that you have an idea of what each one contains. After moving them,
you put each box in the room it belongs to make unpacking quicker and easier. You
can also think of programming in a similar way to packing and moving boxes. You
have many different data types at your disposal but coding efficiently starts with
knowing when and where to use them. In this video you learn to identify the primitive
data types in JavaScript. You will learn about their specific use cases and when to
use each data type. There are seven primitive data types in JavaScript. These are
string, number, Boolean, null, undefined, BigInt and symbol. Let's begin by learning
about the first two which are strings and numbers. Let's say that you are building an
E-commerce app for selling guitars. When a user views the page for the most
popular model, you want them to see the name of the guitar, the description, the best
guitar around and the price of 375. Seems simple enough, right? But how can you
ensure that the information displayed on screen is stored effectively so that the app
can use it? You would do this by using the most appropriate data types but what
does data mean exactly? Well, each piece of information in your app has a different
value and all values are collectively referred to as data but the values differ and
therefore need to be stored differently. For example, you store the name and
description as text values and the price as a numerical value. In JavaScript, text
values are known as the string data type while numerical values are referred to as
the number data type. From a programming perspective, making a distinction
between numbers and text is important because they adhere to different rules. For
example, to build a number, you simply type in the numerical values but to build a
string in JavaScript, the characters must be enclosed in either single or double
quotes. There is also a difference in the number of combinations that the number
and string data types can store. The number data type has a very wide range in JS
enough for most common use cases. However, it is limited up to a point determined
by JavaScript calculation capabilities. The string data type practically has an
unlimited number of combinations of characters. There is almost an infinite number
of ways we can combine different characters into strings. Okay, so back to our app
example, the data must be stored using different types. The price will be stored as a
number while the name and description will be stored as strings with each one
wrapped in double quotes. You now know that the string data type is great for storing
values such as titles and descriptions while the number data type is better suited for
prices or any value that you would like to calculate. However, there are additional
data types in JavaScript to help you tackle different tasks. Next let's explore each of
the remaining data types and their specific use cases to better understand how you
might make good use of them. Let's think of each one as a box. Like I mentioned
earlier, the Boolean data type has only two values, true and false. This means that it
is useful for making decisions. Sometimes it's necessary to know when a variable
does not contain a value. And JavaScript has two data types to express just that.
First, there is the null data type which only has the value null and represents the
absence of value. You also have the undefined data type which can only hold the
value undefined and usually refers to a variable that has not yet been assigned a
value. The capabilities of JavaScript have evolved over time and version ES6
introduced two new primitive data types to help with more complex tasks. One is the
BigInt data type which is like an extra large box that can accommodate a much
greater range of numbers than the number data type. Finally, there is the symbol
data type which can be used as a unique identifier. Think of it as having multiple
boxes with the same label and using different serial numbers to avoid mixing them
up. In this video, you've learned about the various data types available in JavaScript.
Remember that every data type has a specific use case and knowing when to apply
each one will make you a better coder, see you next time.

Operators
Where do you think the name operators come from? Does it have something to do
with an operation of some sort? Well, the answer is yes. Operators are used to
perform operations on variables and values. An operator is used to manipulate
individual data items and return a result. For example, you may already be familiar
with the assignment operator to assign a value to a variable. You use assignment
operators for simple and complex calculations. They provide us with similar options
to those on a calculator. In this video, you will learn about assignment and logical
operators and how to use them in JavaScript. First, let's start with the assignment
operators which you can use to perform simple arithmetic. For example, to add two
numbers, you can use the addition operator, which is represented by the plus
symbol. If you want to subtract values, use the minus operator, which is represented
by the hyphen symbol. If you want to perform division, for example, 35 divided by 5,
use the division operator, which is represented by the forward slash. Finally, to
multiply numbers, use the multiplication operator, which is represented by the star
symbol. In addition to assignment operators, you can also use comparison
operators, which compares and returns a logical value based on whether the
comparison is true. For example, you can compare numbers to check if they are
greater than, less than, equal or not equal to each other. You will learn more about
the various assignment and comparison operators later in this course. But for now,
let me tell you about logical operators. Logical operators are used in JavaScript to
determine if something is true or false. For example, the logical operator named AND
(&), which you can use to check the two or more conditions are true. Imagine you
had a variable named A and you wanted to check that its value is greater than five
and less than 10.
For this to be satisfied, both statements must be true. Alternatively, there is the
operator named R, which checks for at least one of the statements to be true. For
example, A is greater than five, RA is greater than 10. Finally, you can use the
logical operator, NOT, which returns a false value if the result is true. Operators are
used to control the flow of a program that meets certain criteria. Now let me
demonstrate how to use JavaScript, math and logical operators. I've opened VS
Code here. Now, let me demonstrate how you can use arithmetic and comparison
operators in JavaScript.
Recall that comments are used to specify which lines JavaScript should ignore. As
you learned earlier, you can put almost anything inside comments. Notice I have two
multi-line comments. The first one lists some arithmetic operators, and the second
one lists some comparison operators. I also have several single-line comments. You
already learned that JavaScript completely ignores comments, and here's the proof. I
click on the Run code icon. Notice that the output in the right panel will not show any
values other than the expected additional info on the code that was run. Let me clear
that for now and show you how to work with some arithmetic and comparison
operators. I'm going to uncomment all single-line comments from lines 14-21, so that
you can focus on each of these console logs separately. This will then allow me to
demonstrate how each of these operators behaves. Let me delete the two forward
slashes on line 14 and rerun this file. Notice I get the value of four outputted to the
console, resulting from adding the values 2 plus 2. Let me clear the console,
comment line 14 and uncomment line 15. This is an example of adding multiple
numbers using the plus operator. Notice when I run this, I get the output of 15. Let's
do another one using the subtraction operator to subtract 18 from 20. If I run this, I
get the expected output of two. Next is multiplication, which is represented by the
asterisk symbol. Here I will console dot log the values of 2 times 3 to get the value of
six. On line 18, I use the forward slash symbol for the division of eight by one. Notice
when I run this, a value of eight is outputted, success. That's it for performing simple
arithmetic in JavaScript. Let me clear my screen again. Now I want to demonstrate
how to work with comparison operators. Notice on line 19, I use the greater than
symbol to check if three is greater than two, run it and indeed it is, I get an output of
true. On line 20 I use the greater than symbol to check if two is greater than three.
Since it's not, I receive an output of false. These words true and false are special
kinds of values used in JavaScript. Don't worry too much about them now, as you will
learn more about this later. For now, I just want you to focus on the final line of code.
This checks if one value is equal to another value. It's important to remember that
you need to use the equals symbol twice for this comparison operator to be valid.
This is because the single equal symbol is used for the assignment operator, like
when you assign a value to a variable. I would expect the value of 10 to be equal to
10. Let's run it to find out and it is. Notice a value of true is outputted to the console.
Congratulations, you have now learned how to work with operators in JavaScript.
This is a must-have skill in your development toolkit as they are used in many areas
of programming. Great work.

Numbers

In JavaScript, like in other programming languages, there are different data types.
The number of data type is a foundational part of JavaScript as a programming
language because it represents both integer and decimal point numbers. Without it,
you wouldn't be able to code and with such a crucial data type we better get started
right away. Let me demonstrate the number data type. I type the value 123 into the
console and press ''Enter.'' Notice that the output is 123. Next, on a new line, I type a
decimal value, 123.456 which is also a number data type. I press the Enter key again
and get the decimal value 123.456. In JavaScript, we can use numbers to perform
math operations. For example, I can code 2 plus 2 and get the value of 4 returned.
Just like in regular mathematics, we use the plus symbol for addition. Similarly, use
the minus symbol to perform subtraction. For example, 4 minus 2 returns the value
of 2. For multiplication use the asterisk or star key so 4 times 4, will return 16. For
division use the forward-slash key 16 divided by 4 returns the value of 4. You can
use a double star sign to perform exponential calculations for slightly more complex
arithmetic. For example, 10 to the power of 2, 10 times 10 will return 100. A final
example is the remainder or the modulus operator. This checks how many times you
can fit one number into the other and then return the remainder. If I type 9 modulus
8, the value of one is returned, or 16 modulus 8 returns a zero. This is because the
number eight divides into the number 16 evenly. There is no remainder as
represented here by the zero. Besides basic mathematical operations, you can also
use parentheses to group more complex calculations. For example, 2 times 4 plus 8
can return a different answer depending on the order used for calculation. For
example, multiplying 2 times 4 and then adding the value of 8 returns 16 but 2 times
the value of 4 plus 8 returns 24. By using parentheses, I can control the order of
calculations. Without parentheses, JavaScript will follow the standard mathematical
sequence of calculation. In this case, the multiplication would take precedence and
be done first so the 2 times 4 happens first and then the 8 is added returning a value
of 16. Remember I can override that using parentheses and get a different result.
That's an example of using parentheses and JavaScript with numbers and
mathematical operators. Some of the most common JavaScript mathematical
operators are plus, minus, times, division, and modulus. If you'd like to learn more
about mathematical operators, there's an additional reading at the end of this lesson.

Strings
Since you're new to JavaScript, you might not be familiar with strings. Strings are
used to represent and work with a sequence of characters while programming in
JavaScript. Let me explain how they work. To demonstrate the concept of strings, I
have the developer tools open in my browser and the Console tab is selected. What
is a string? A string in JavaScript is a collection of characters enclosed by single
quotes, double quotes. Such a collection of characters is known as a string datatype.
Strings are one of the most common types of data you'll be working with. To code a
string, I type in a pair of single quotation marks. This piece of code with just an
opening and closing single quote is referred to as an empty string. To build an empty
string, I can also use double quotation marks. While empty strings have their place in
JavaScript, they're not very versatile. But strings don't have to be empty, so let me
build a non-empty string with some letters and an exclamation mark. I do this by
typing the words hello there, and an exclamation mark within a pair of single
quotation marks. Besides letters and punctuation symbols, we can add almost any
other character into a string, including numbers. For example, I can type 'hello there!
' and follow it up with several symbols and numbers. This is still a valid string.
There's one thing that strings can't do and that is break onto the next line. When I
type a single quotation mark, the word hello, and then press Enter before typing the
second quotation mark, it results in an error which stops the code from running. The
same happens if I use double quotation marks. When you use single or double
quotes to surround string values, these characters are referred to as delimiters. This
is because I use them to delimit a given string value from the rest of my code. There
are some unusual situations that can trip you up when you first start using strings in
JavaScript. For example, let's say that I want to create a new string. I do this by
typing a single quotation mark, followed by the phrase, it is a lovely day, and I close
the string with a second single quotation mark. Now I want to use the contraction of it
is by using an apostrophe but again, error code. This is because JavaScript reads
the word it, that is the first two letters as forming a string, and then it doesn't
understand the rest of the code because of the apostrophe. To fix this issue, I need
to nest single quotes inside double quotes. I do this by replacing the original single
quotation marks on either side of the phrase with double quotation marks, and now
you'll notice there are no more errors. You can make single and double quotes too
but it's better to stick with one or the other because it can be confusing and lacks
consistency, and there you have it. You have learned what a string datatype is and
what an empty string is. You can also explain what the string datatype is in
JavaScript, I encourage you to try and make some more strings while practicing
coding.

Booleans
The Boolean data type is used to check if a statement is true or false, which makes it
a foundational part of knowing how to use JavaScript. It has many uses, but in this
video, I will focus on how to get the result of a comparison to determine if two values
are the same or not. What does a Boolean datatype? To understand the answer to
this question, let's think about a real life scenario of comparing numbers, such as, for
example, checking if number 1 is smaller than number 2. In JavaScript, I do it like
this, 1 less than sign 2. When I press the Enter key, JavaScript says that this is a
true claim. Let's do some other comparisons. Let's check if one is greater than two, 1
greater than sign 2. This code returns a value of false of the Boolean data type. No
matter how I compare numbers, the result of the comparison will always be either
true or false. There are no maybe's here. That's why the Boolean data type has only
two possible values, true and false. Besides the less than and the greater than
operator, I can also use some other operators to compare numbers. It might help to
think of these various comparison operators, those tests. Let's say I wanted to test if
the comparison of two numbers is correct or incorrect. Now I will run a few tests with
some additional operators, starting with checking for equality, 1 equals equals 2. I'm
claiming that 1 is equal to 2 and JavaScript returns false. No, 1 is not equal to 2. My
claim is false. When first introduced to the syntax with two consecutive equal signs, it
is not uncommon for people to be slightly confused. Why the double equals sign?
After all, you know that in mathematics you only need a single equal sign to signal
equality. But in JavaScript, I use a single equal sign as the assignment operator to
assign a value from the right side of the assignment operator to the variable on the
left side of the assignment operator. For example, I can type var score equals 100 to
declare a variable called score and assign it to the value 100. In other words, I can
now confirm that the value of score is 100 by typing out score in the console. Indeed
100 it is. In contrast, in JavaScript the equality operator has to equal signs and it
checks only for value. Additionally, there's also the strict equality operator that has
three equal signs and it checks for both the value and type. For example, if I use the
equality operator, let me type 100 double equal sign, double quotation, number 100,
and close double quotation, the console will return the Boolean value of true. By
using the double equals sign, I compare only this value and not the type. JavaScript
checks only if 100 is equal to 100 regardless of the datatype. It ignores the fact that
the 100 on the left of the equality operator without the double-quotes is a number,
and that the 100 on the right of the equality operator with the double quotes is a
string. The strict equality operator is more unforgiving. It checks for both the quality
of value and the quality of type. Therefore, comparing the number of 100 without
quotes with a string 100 with double-quotes will return a Boolean value of false. Why
is this false? It is false because although the value is the same, the type is not. The
number 100 does not have the same type as the string 100. There's also an operator
that's the opposite of the equality operator, the inequality operator. It's a combination
of an exclamation mark and an equal sign. Let's test it. I take number 1, exclamation
mark the equals sign and number 1 again. It returns a Boolean value of false
because it is false to say that one is not equal to one. Additionally, just like there's
the strict equality operator, there's also its opposite in the form of the strict inequality
operator. This operator is an exclamation mark with two equal signs. Let's type
number 1 as a number, exclamation mark the equals sign twice, and then number 1
inside double quotes that is as a string. This returns a Boolean value of true because
the number one is not the same as a string 1 by both the value and the type. It's true
that these two values are not the same. There are other operators in JavaScript, and
there are some additional concepts like operator precedence and operator
associativity, but we'll skip this for now. With the examples covered in this video, you
should have a basic grasp of how the Boolean data type works and what it's useful
for. You will encounter Boolean values again because there are other important
ways in which you can use them in your code besides comparing numbers and
strings.

Operators in depth

In this reading, you will learn about additional operators, operator precedence and
operator associativity. I'll also provide you with some examples of logical operators.

1. Additional operators

● Logical AND operator: &&


● Logical OR operator: ||
● Logical NOT operator: !
● The modulus operator: %
● The equality operator: ==
● The strict equality operator: ===
● The inequality operator: !=
● The strict inequality operator: !==
● The addition assignment operator: +=
● The concatenation assignment operator: += (it's the same as the previous one
- more on that later)

The logical AND operator in JavaScript: &&

The logical AND operator is, for example, used to confirm if multiple comparisons will
return true.

In JavaScript, this operator consists of two ampersand symbols together: &&.

Let's say you're tasked with coming up with some code that will check if the
currentTime variable is between 9 a.m. and 5 p.m. The code needs to
[Link] true if currentTime > 9 and if currentTime < 17.

Here's a solution:

2
var currentTime = 10;

[Link](currentTime > 9 && currentTime < 17);

How does this code work?

First, on line one, I set the currentTime variable, and assign the value of 10 to it.

Next, on line two I console log two comparisons:

currentTime > 9

currentTime < 17

I also use the && logical operator to join the two comparisons.

Effectively, my code is interpreted as the following:

[Link](10 > 9 && 10 < 17);


The comparison of 10 > 9 will return true.

Also, the comparison of 10 < 17 will return true.

This means I can further re-write line two of my solution as follows:

[Link](true && true);

In essence, this is how my code works.

Now, the question is, what will be the result of [Link](true && true)?

To understand the answer, you need to know the behavior of the && logical operator.

The && logical operator returns a single value: the boolean true or false, based on
the following rules:

● It returns true if both the values on its right and on its left are evaluated to
true
● It returns false in all the other instances

In other words:

[Link](true && true) will output: true

[Link](true && false) will output: false

[Link](false && true) will output: false

[Link](false && false) will output: false

The logical OR operator in JavaScript: ||

The logical OR operator in JavaScript consists of two pipe symbols together: ||.

It is used when you want to check if at least one of the given comparisons evaluates
to true.

Consider the following task: You need to write a program in JavaScript which will
return true if the value of the currentTime variable is not between 9 and 17. Put
differently, your code needs to [Link] true if the value of the variable
currentTime is either less than 9 or greater than 17.

Here's a solution:

var currentTime = 7;

[Link](currentTime < 9 || currentTime > 17);

In line one of the code I assign the number 7 to the variable currentTime.

On line two, I console log the result of checking if either currentTime < 9 or
currentTime > 17 will evaluate to true.

It's the same as this:

1
2

var currentTime = 7;

[Link](true || false);

Here are the rules of how the || operator evaluates given values:

[Link](true || true) will output: true

[Link](true || false) will output: true

[Link](false || true) will output: true

[Link](false || false) will output: false

The logical OR operator will always return true, except when both sides evaluate to
false. In other words, for the logical OR operator to return false, the results of
both comparisons must return false.
Going back to the example of checking if either currentTime < 9 or currentTime
> 17, this makes sense: the only time you will get false is when the value stored in
the currentTime variable is greater than 9 and less than 17.

The logical NOT operator: !

In JavaScript, the symbol for the logical NOT operator is the exclamation mark: !.

You can think of the ! operator as a switch, which flips the evaluated boolean value
from true to false and from false to true.

For example, if I assign the boolean value of true to the petHungry variable:

var petHungry = true;

...then I can console log the fact that the pet is no longer hungry by using the !
operator to flip the boolean value stored inside of the petHungry variable, like so:

[Link]('Feeding the pet');

[Link]("Pet is hungry: ", !petHungry);

[Link](petHungry);
This is the output of the above code:

Feeding the pet

Pet is hungry: false

true

In the provided code, [Link]("Pet is hungry: ", !petHungry); will


show false for the negated value, but the actual value of petHungry remains
true unless reassigned.
Notice, however, that the code on last line of the example above still outputs true -
that's due to the fact that I didn't reassign the value of the petHungry variable.

Here's how I could permanently change the value stored in the petHungry variable
from true to false:

var petHungry = true;

petHungry = !petHungry;

In this example, I first assign the value of true to the new variable of petHungry.
Then, I reassign the opposite value (!true, or 'not true') to the petHungry variable.

The modulus operator: %

The modulus operator is another mathematical operator in JavaScript. It returns the


remainder of division.
To demonstrate how it works, imagine that a small restaurant has a total of 5 tables,
and each table can seat 4 guests. The restaurant suddenly receives 22 guests.

How many guests will not be able to sit down in the restaurant?

You can use the modulus operator to solve this.

[Link](22 % 5); // 2

The output is 2, because when I divide 22 by 5, I get a 4, and the remainder is 2. So


there are 2 people who couldn't get a place in this restaurant.

The equality operator, ==

The equality operator checks if two values are equal.

For example, this comparison returns true: 5 == 5. Indeed, it is true that 5 is equal
to 5.
Here's an example of the equality operator returning false: 5 == 6. Indeed, it is
true that 5 is not equal to 6.

Additionally, even if one of the compared values is of the number type, and the other
is of the string type, the returned value is still true: 5 == "5".

This means that the equality operator compares only the values, but not the types.

The strict equality operator, ===

The strict equality operator compares for both the values and the data types.

With the strict equality operator, comparing 5 === 5 still returns true. The values
on each side of the strict equality operator have the same value and the same type.
However, comparing 5 === "5" now returns false, because the values are equal,
but the data type is different.

The inequality operator, !=

The inequality operator checks if two values are not the same, but it does not check
against the difference in types.
For example, 5 != "5" returns false, because it's false to claim that the number 5
is not equal to number 5, even though this other number is of the string data type.

The strict inequality operator !==

For the strict inequality operator to return false, the compared values have to have
the same value and the same data type.

For example, 5 !== 5 returns false because it is false to say that the number 5 is
not of the same value and data type as another number 5.

However, comparing the number 5 and the string 5, using the strict inequality
operator, returns true.

[Link](5 !== "5")

2. Using the + operators on strings and numbers

Combining two strings using the + operator


The + operator, when used with number data type, adds those values together.

However, the + operator is also used to join string data type together.

For example:

"inter" + "net" // "internet"

"note" + "book" // "notebook"

If the + operator is used to join strings, then it is referred to as the concatenation


operator, and you'll say that it's used to concatenate strings.

When used with numbers, the + operator is the addition operator, and when used
with strings, the + operator is the concatenation operator.

Combining strings and numbers using the + operator


But what happens when one combines a string and a number using the + operator?

Here's an example:

365 + " days" // "365 days"

12 + " months" // "12 months"

Here, JavaScript tries to help by converting the numbers to strings, and then
concatenating the number and the string together, ending up with a string value.

The process of this "under-the-hood" conversion of values in JavaScript is referred to


as "coercion". JavaScript coerces a number value to a string value - so that it can
run the + operator on disparate data types.
The process of coercion can sometimes be a bit unexpected.

Consider the following example:

1 + "2"

What will be the result of 1 + "2"?

Note that the value of 1 is of the number data type, and the value of "2" is of the
string data type. JavaScript will coerce the number 1 to a string of "1", and then
concatenate it with the string of "2". The result is a string of "12".

The addition assignment operator, +=

The addition assignment operator is used when one wants to accumulate the values
stored in a variable.

Here's an example: You are counting the number of overtime hours worked in a
week.
You don't have to specify the type of work, you just want to count total hours.

You might code a program to track it, like this:

var mon = 1;

var tue = 2;

var wed = 1;
var thu = 2;

var fri = 3;

[Link](mon + tue + wed + thu + fri); // 9

You can simplify the above code by using the addition assignment operator, as
follows:

6
var overtime = 1;

overtime += 2;

overtime += 1;

overtime += 2;

overtime += 3;

[Link](overtime); // 9

Using the addition assignment operator reduces the lines of your code.

The concatenation assignment operator, +=

This operator's syntax is exactly the same as the addition assignment operator. The
difference is in the data type used:

1
2

var longString = "";

longString += "Once";

longString += " upon";

longString += " a";

longString += " time";


longString += "...";

[Link](longString); // "Once upon a time..."

Operator precedence and associativity

Operator precedence is a set of rules that determines which operator should be


evaluated first.

Consider the following example:

1 * 2 + 3

The result of the above code is 5, because the multiplication operator has
precedence over the addition operator.

Operator associativity determines how the precedence works when the code uses
operators with the same precedence.

There are two kinds:


● left-to-right associativity
● right-to-left associativity

For example, the assignment operator is right-to-left associative, while the greater
than operator is left-to-right associative:

var num = 10; // the value on the right is assigned to the variable
name on the left

5 > 4 > 3; // the 5 > 4 is evaluated first (to `true`), then true > 3
is evaluated to `false`, because the `true` value is coerced to `1`

Conclusion

In this reading, we explored the fundamental and advanced aspects of JavaScript


operators, including their types, precedence, and associativity. A deeper
understanding of operator precedence clarified how JavaScript determines the order
of evaluation, while operator associativity explained the behavior of operators with
the same precedence level. Through practical examples, we demonstrated the
importance of knowing how different operators behave, especially when combining
numbers, strings, and boolean values.
Mastering JavaScript operators enables developers to write concise, efficient, and
effective code. With this foundation, you are better equipped to navigate complex
logical and mathematical scenarios in your programs, making your JavaScript skills
more robust and versatile.

Exercise: Advanced use of


operators

Task 1: Using the logical && operator

You are coding an RPG game, where each character has certain skill levels based
on the value saved in their score.
1. Create a variable named score and set it to 8
2. Use [Link]() that includes the string "Mid-level skills:" and
compares the score variable to above 0 and below 10 using the && operator

The expected output in the console should be: "Mid-level skills: true".

1
Note: If the score is set to a value between 1 and 9 (inclusive), the condition
evaluates to true. Otherwise, it would evaluate to false.

Task 2: Using the logical || operator

Imagine you are coding a video game. Currently, you’re about to code some
snippets related to the game over condition.

You need to code a new variable named timeRemaining and set it to 0. You also
need to code a new variable named energy and set it to 10.

Next, you should write a piece of code that could be used to determine if the game is
over, based on whether either the value of the timeRemaining variable is 0 or the
value of the energy variable is 0.

Complete the task using the following steps:


1. Declare the variable timeRemaining, and assign the value of 0 to it.
2. Declare the variable energy, and assign the value of 10 to it.
3. Console log the following parameters: "Game over: ", and timeRemaining
== 0 || energy == 0

Note that the expected output in the console should be: "Game over: true".
Try changing the timeRemaining variable to anything above 0 and then see how it
affects the result.

Note: Logical operators, such as && (AND) and || (OR), allow you to combine
multiple conditions to create more complex comparisons.

Task 3: Using the modulus operator, %, to test if a given number is odd

You need to code a small program that takes a number and determines if it's an
even number (like 2, 4, 6, 8, 10).

To achieve this task, you need to declare six variables, as follows:


1. The first variable, named num1, should be assigned a number value of 2.
2. The second variable, named num2, should be assigned a number value of 5.
3. The third variable, named test1, should be assigned the calculation of num1
% 2. Note: executing this code will return a number. Note: The modulus
operator % returns the remainder when one number is divided by another. If a
number is even, dividing it by 2 will leave no remainder (0).
4. The fourth variable, named test2, should be assigned the calculation of
num2 % 2. Note: executing this code will also return a number.
5. The fifth variable, named result1, should be assigned the result of checking
if the number stored in the test1 variable is equal to 0, in other words:
test1 == 0.
6. The sixth variable, named result2, should be assigned the result of
comparing if the number stored in the test2 variable is equal to 0, in other
words, test2 == 0.

Run console log two times after you've set the variables:

1. The first console log should have the following code between parentheses:
"Is", num1, "an even number?", result1
2. The second console log should have the following code between
parentheses: "Is", num2, "an even number?", result2

Note: The output to the console should be as follows:

Is 2 an even number? true

Is 5 an even number? false

Try it yourself with different values to explore the modulus operator.

Task 4: Add numbers using the + operator

Console log the result of adding two numbers, 5 and 10, using the + operator.
Note: This task should be completed on a single line of code. The output in the
console should be 15.

Task 5: Concatenate numbers and strings using the + operator


Code three variables:
1. The first variable should be a string with the following value: "Now in ".
Name the variable now.
2. The second variable should be a number with the value: 3. Name the variable
three.
3. The third variable should a string with the following value: "D!". Name the
variable d.
4. Console log the following code: now + three + d.

Note: The expected output should be: "Now in 3D!".

Task 6: Use the += operator to accumulate values in a variable


Code a new variable and name it counter, assigning it to the value of 0.
On the next line, use the += operator to increase the value of counter by 5.

On the next line, use the += operator to increase the value of counter by 3.

On the fourth line, console log the value of the counter variable.

Note: The output value should be 8.


JavaScript improvements
In this reading, you will learn about the history of JavaScript and the importance of
ECMA (European Computer Manufacturers Association) and ECMAScript.

JavaScript is a programming language that had humble beginnings.

It was built in only 10 days in 1995 by a single person, Brendan Eich, who was
tasked with building a simple scripting language to be used in version 2 of the
Netscape browser. It was initially called LiveScript, but since the Java language was
so popular at the time, the name was changed to JavaScript - although Java and
JavaScript are in no way related.

For the first few years, after it was built, JavaScript was a simple scripting language
to add mouseover effects and other interactivity. Those effects were being added to
webpages using the <script> HTML element.

Inside each of the script elements, there could be some JavaScript code. Due to the
rule that HTML, CSS, and JavaScript must be backward compatible, even the most
advanced code written in JavaScript today ends up being written between those
script tags.

Over the years, JavaScript grew ever more powerful, and in recent times, it's
continually touted as among the top three commonly used languages.

In 1996 Netscape made a deal with the organization known as ECMA (European
Computer Manufacturers Association) to draft the specification of the JavaScript
language, and in 1997 the first edition of the ECMAScript specification was
published.

ECMA publishes this specification as the ECMA-262 standard.

You can think of a standard as an agreed-upon way of how things should work.
Thus, ECMA-262 is a standard that specifies how the JavaScript language should
work.
There have been 12 ECMA-262 updates - the first one was in 1997.

JavaScript as a language is not a completely separate, stand-alone entity. It only


exists as an implementation. This implementation is known as a JavaScript engine.

Traditionally, the only environment in which it was possible to run a JavaScript


engine, was the browser. More specifically, a JavaScript engine was just another
building block of the browser. It was there to help a browser accomplish its users'
goal of utilizing the internet for work, research, and play.

So, when developers write JavaScript code, they are using it to interact with a
JavaScript engine. Put differently, developers write JavaScript code so that they can
"talk to" a JavaScript engine.

Additionally, the JavaScript engine itself comes with different ways to interact with
various other parts of the browser. These are known as Browser APIs.

Thus, the code that you write in the JavaScript programming language allows you to:
1. Interact with the JavaScript engine inside of the browser 2. Interact with other
browser functionality that exists outside of the JavaScript engine, but is still inside
the browser.

Although traditionally it was possible to interact with the JavaScript engine only
inside of the browser, this all changed in 2009, when [Link] was built by Ryan
Dahl.

He came up with a way to use a JavaScript engine as a stand-alone entity.


Suddenly, it was possible to use JavaScript outside of the browser, as a separate
program on the command line, or as a server-side environment.

Today, JavaScript is ubiquitous and is running in browsers, on servers, actually, on


any device that can run a JavaScript engine.
CONDITIONALS AND LOOPS
Writing statements: Every day from the moment we wake up, you
and I make decisions. From what clothes to wear, whether to have tea or coffee for
breakfast or even what movie to watch. While some decisions are complex, some
can be relatively simple. We make them based on whether some condition is either
true or false. For example, if it's raining outside, we will likely bring an umbrella. The
condition here is the weather. If it's raining, we take an umbrella. If it's not, we don't.
In this video, you will learn about conditional statements in JavaScript using the if
and else statements. In JavaScript, there are pieces of code called conditionals, and
developers can use them to run code conditionally based on whether something is
either true or false. There are many types of conditional statements, but the first one
I want you to learn about is something called the if statement. The if statement
checks a condition and will execute a code block if the condition is met or true. The
condition criteria are essential here. The block of code will only get executed if the
condition is evaluated to the Boolean value of true. You can use many types of
comparison operators to evaluate the condition. These include operators such as
equal to, greater than, less than, and not equal to. You can find a complete list of
comparison operators from the additional reading at the end of this lesson. So far,
you've learned about using conditionals with binary conditions where a thing can be
either true or false. However, in the world of programming, things are often not that
simple. Imagine you are a developer working on a website where a person can
practice for their driving test. Part of the driving test is that they must pass a theory
exam of 50 questions based on the rules of the road. The exam has only two results,
pass or fail. If the student's score is greater than 40, they pass. If not, they fail. You
need to output the exam result to the learner. This is where another conditional
statement can be used, and it's called the if-else statement. This statement handles
both outcomes of our conditional request using the else keyword. If a condition is
true, do something. If it's false, do something else. Recall, a driving test example. We
can store the test result in a variable. Suppose the variable value is greater than 40.
In that case, the true block is executed, and you output a message to the console
telling the learner that they passed. Suppose the variable value is less than 40. In
that case, the false block is executed, and you output a message to the console
telling the learner that they did not pass.
There will be many occasions where you will need to program for more complicated
conditions or scenarios. For example, you may want to test multiple conditions. To
do that, you can add an additional block called the else-if statement.

Working with conditional statements


Recall that conditional statements are used to run pieces of code based on whether
the condition is either true or false. Okay, let me demonstrate this now with a simple
example using a variable and an, if else statement. Additionally, we learn how to
deal with cases where we have multiple, if else, if conditions. For example, the if else
statement can be used when you want to execute code based on a certain condition
being either true or false.

But what if you have five conditions or even ten? Well, you could use multiple lines of
else If. There is another way to do this, using something called a switch statement.
Okay, let me demonstrate this now with an example of when to use else if, and when
to use the switch statement. So, I have VS code open here and noticed that I have
pasted in an example of an if else statement. First, on line three here I've assigned
the value of 50 to the variable result. Then on line five I'm checking if the result Is
greater than 40. If this returns the Boolean value of true, my code will console log the
words you pass the test. After that, on line seven, I specify the else block which will
run when the if condition returns false instead of true. In that case, I use [Link]
to output, you did not pass the test.

Okay, so now let's run this code, and as expected I get the output of you pass the
test. This happened because the statement 50 is greater than 40 in the if condition
returned true, and its associated block of code was executed. Now, let me change
the value of the result variable to say 30 and rerun the code. This time I was notified
that I did not pass the test. This was because the condition 30 is greater than 40 was
evaluated and returned false. The code was skipped inside the if block, instead, the
code inside the else block was run. My code works well because I'm checking a
binary condition here, but what if there are more options? In that case, I'll need to
cover all these possibilities. Let me switch tabs to demonstrate this using else if
statements.

Okay, so notice that I have a variable named place and it's assigned to a string with
the value of first. Next, notice my code contains four conditional statements. The
first, is an if statement that checks if the value of the variable place equals the string
value of first. If this is true then a message of gold will output to the console. As there
are three more conditions, the next one needs to use an else if block. This time I'm
checking if the value stored in the place variable equals the string value of second.
Once again, if this is true a message of silver will output to the console. Notice lines
nine and ten, this code is another else if block that checks for a value of 3rd and
outputs the message of bronze. And this process would keep repeating for as many
conditions as needed. Finally, if no condition is met, I have a catch all else statement
at the end. This is crucial because if the conditional checks for the values first,
second or third are not satisfied, the else block will run and output the text, No
medal. Okay, so this code looks good to me. Let me run it to test the output. Notice
the word gold is outputted, while this method is correct, it can become a bit
unmanageable when there are multiple conditions. For example, say you had to
evaluate ten conditions, luckily, there is another statement at our disposal and this is
called the switch statement. Let me switch tabs again and now notice the code. So,
here I have a switch example, but I want to examine these files side by side.
So, let me click on the tab of the switch statement file and I'll drag it around until I
find a good place for it. That will allow me to compare the code. Let's adjust this a
little bit more and clear the output of the console. Okay, so you may notice that the
syntax is significantly different by Inspecting these two files. If I run the switch
statement code here I get the same result, the word Gold is output. Also, if I change
the value of place variable to say fourth, the default case will be run and the text, No
medal, will output to the console. The if else if, else example code acts precisely the
same. So, here when I update the variable place to fourth, the same thing happens,
the words, No medal are locked. Congratulations, you have now learned about
conditional statements using the if and else. You've also learned how to streamline
multiple conditions using the switch statement. If you would like to learn more about
conditional statements and operators, there is a link to an additional reading at the
end of this lesson.

Conditional examples
In this reading, you will learn when to use the if else statement and when to use
the switch statement.

Both if else and switch are used to determine the program execution flow based
on whether or not some conditions have been met.
This is why they are sometimes referred to as flow control statements. In other
words, they control the flow of execution of your code, so that some code can be
skipped, while other code can be executed.

At the heart of both flow control structures lies the evaluation of one or more
conditions.

Break statement

Before we understand the flow control statements, let us take a minute to understand
the break statement. The break statement is used to exit a loop or stop the execution
of a switch case. Once a break is encountered, the program immediately jumps out
of the current block.

for (let i = 1; i <= 5; i++) {

if (i === 3) {

break; // Stops when i is 3

[Link](i);

// Output: 1, 2

Without break, the loop or switch would continue running, which could lead to
unintended behavior.

Generally, if else is better suited if there is a binary choice in the condition.

For example, in plain English: if it's sunny, wear sunglasses. Otherwise, don't.

In this case, using an if statement is an obvious choice.

When there is a smaller number of possible outcomes of truthy checks, it is still


possible to use an if else statement, such as:
However, if there are a lot of possible outcomes, it is best practice to use a switch
statement because it is less wordy.

Switch statements

Being easier to read, it is easier to follow the logic and thus reduce the cognitive load
of reading multiple conditions.

Take a note that switch uses strict equality (===) for comparisons which means, it
first compares the type and then the values of the operands.

For example:

[Link](1 === "1"); // false (different types)

[Link](null === null); // true (same type and value)

[Link](1 == "1"); // true (type coercion)

Nevertheless, this is not a rule set in stone. It is simply a stylistic choice.

To reinforce this point, here's an example of the earlier if else conditional


statement, using the switch syntax:
Fallthrough behavior:

It's important to note that in JavaScript, switch statements have fallthrough behavior,
meaning that if a break is not included after a case, the code will continue to execute
the next case, regardless of whether it matches. For example:

switch(light) {

case 'green':

[Link]("Drive");

case 'orange': // No break here, so this will also run

[Link]("Get ready");
break;

case 'red':

[Link]("Don't drive");

break;

default:

[Link]('The light is not green, orange, or red');

In this case, if light is "green", both "green" and "orange" cases will run. To avoid
this, always include a break unless intentional fallthrough is desired.

Logical operators

You can also use logical operators like && (AND) and || (OR) to combine multiple
conditions in an if else statement. For example:
if (weather === "sunny" && temperature > 20) {

[Link]("Go for a picnic");

} else if (weather === "rainy" || temperature < 10) {

[Link]("Stay indoors");

Switch

Switch works well with discrete, exact matches (like strings or numbers) but is less
flexible than if else for evaluating complex conditions or ranges. For example this
kind of condition cannot be expressed in a switch:

if (age > 18 && age < 60) {

[Link]("Eligible for the program");

}
Conclusion

Choosing between if-else and switch is primarily a matter of readability, not


performance, for most use cases, especially for a small number of conditions.

Exercise: Practice conditional


statements
Introduction

In this exercise, you will practice working with if else statements. By the end of
this exercise, you will be able to write an if else statement that determines your
source of income based on your age. You will also be able to write a switch
statement that determines your evening routine based on the day of the week.

Guidelines

While writing JavaScript code, it's important to check for common syntax errors that
can prevent the program from running correctly. Key mistakes to avoid include:

Missing Parentheses: Always ensure parentheses are correctly placed around


conditions in if, else, and switch statements.

Mismatched Curly Braces: Ensure each opening { has a corresponding closing } to


define code blocks properly.
Extra Semicolons: Avoid placing semicolons after if, else, or else if conditions
as it ends the statement prematurely.

Incorrect Use of Operators: Double-check logical operators (&&, ||, etc.) and
comparison operators (>, <, ==) for correct syntax.

Improper Keyword Usage: Ensure proper use of JavaScript keywords such as let,
const, and var for variable declarations.

Complete the following steps to create: Are You Old Enough?

1. Declare a variable age using the var keyword and set it to the number 10.
2. Add an if statement that checks if the value of the age variable is greater
than or equal to the number 65. Inside the if block, [Link] the
sentence: "You get your income from your pension". (We will be using
[Link] throughout the code to display output in the console, helping to
show the results of conditions and track the program's behavior during
execution.)
3. Add an "else if", where you'll check if the value of the age is less than 65
and greater than or equal to 18. Inside this "else if" block, type
"[Link]" and then "Each month you get a salary".
4. Add another "else if", and this time check if the value of the age is under
18. Inside the "else if" block, type "[Link]" and then "You get an
allowance".
5. Add an "else" statement to capture any other value. Inside the block, type
"[Link]" and then "The value of the age variable is not numerical".

Try adjusting the age and executing the program to see how it will affect the output.

Note: The code in the Are You Old Enough? example does not check if 'age' is a
valid number. To prevent errors during runtime in real-world applications, it's
important to verify that an input is of the expected type (for instance a number). Error
checking is covered in another lesson.
Code the days of the week program as a switch statement

1. On the next line, define a new variable, name it day, and set its value to
"Sunday".
2. Start coding a switch statement, passing the day variable as the expression
to evaluate.
3. Inside the switch, add cases for every day of the week, starting with
'Monday', and ending with 'Sunday'. Make sure to use string values for days.
Inside each case, for now, just add a [Link]('Do something'), and
add a break; on the line below.
4. At the very bottom of the switch statement, add the default case and add a
[Link]('There is no such day').
5. Finally, update the [Link] calls for each case, based on whatever
activity you have on each of the days.

Note: In the days of the week code example the 'else' block handles unexpected
cases. However, it only applies if no conditions match. It assumes a valid 'age'
input. Proper validation of input types, like ensuring 'age' is a number, is explored in
other lessons.

Tips

● If you need to make sure that multiple conditions are true in an if statement,
you can do so using the && operator
● In JavaScript, the correct syntax of the "greater than or equal to" operator is:
>=.
● Don't forget to add a break at the very end of each case in a switch
statement.

Note: You can find solutions in a separate reading (following this one)

You might also like