0% found this document useful (0 votes)
175 views42 pages

JavaScript: History, Basics, and Console Use

JavaScript was created in 1995 by Brendan Eich for Netscape Navigator to enable dynamic web pages and was originally named LiveScript. It has evolved into a popular programming language, standardized as ECMAScript, with a consistent release cycle since its inception. The document covers various aspects of JavaScript, including its history, data types, console usage, variables, and best practices for coding.

Uploaded by

mihret
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)
175 views42 pages

JavaScript: History, Basics, and Console Use

JavaScript was created in 1995 by Brendan Eich for Netscape Navigator to enable dynamic web pages and was originally named LiveScript. It has evolved into a popular programming language, standardized as ECMAScript, with a consistent release cycle since its inception. The document covers various aspects of JavaScript, including its history, data types, console usage, variables, and best practices for coding.

Uploaded by

mihret
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

Course 4: JavaScript

Where Did JavaScript Come From?


The first version of JavaScript was created in just ten days 1995 by Brendan
Eich(opens in a new tab). Eich was working on Netscape Navigator, one of
the Internet's first web browsers. Eich's goal was to add the capability for
dynamic web pages, which, at that time, were simple pages of HTML and
CSS.

Why Is It Called Javascript?

JavaScript was originally called LiveScript, but it was changed back to


JavaScript as a marketing decision to piggyback off Java's popularity. Despite
the name, JavaScript is not related to Java in any way.

The Evolution of JavaScript

As the language evolved, competing versions of the language emerged. To


standardize the language, JavaScript was brought to Ecma
International(opens in a new tab), an industry association "dedicated to the
standardization of information and communication systems." That's why you
might hear JavaScript referred to as ECMAScript.

The standards body has transitioned to a year-based number to promote a


more consistent release cycle. So we have ES2016, ES2017, and so on. You
can see current specifications on the ECMA website. ECMA-262(opens in a
new tab), and you can even look over drafts of proposed
updates ECMAScript® 2022 Language Specification(opens in a new tab)

JavaScript Today

JavaScript has grown to be one of the most popular programming languages


globally and is considered one of the foundational pillars of front-end web
development.

You can read more about the current standards for JavaScript in MDN Web
Docs: JavaScript
TIP: HTML and CSS are markup languages*. Markup languages are used to describe and
define elements within a document. JavaScript is a* programming language*. Programming
languages are used to communicate instructions to a machine. Programming languages can be
used to control the behavior of a machine and to express algorithms.*

[Link]

The Console Is Your Coding Sandbox


The console is a great place to mess around with your code without any long-
term consequences. The console will tell you if there are any warnings or
errors on the page, display any output, or print it with [Link].

Using [Link] statements

[Link] used to display content to the JavaScript console. Run the


following code in the console:

[Link]("hiya friend!");
Prints: "hiya friend!"
This can be very helpful in figuring out what is going on when you are
debugging your code.

NOTE: You may see some errors or warnings in the console from the site
you're visiting -- and that's okay! Warnings are very common and will not
affect the code you write in this course.

Troubleshooting

For Chrome users, if you don't see the output, click “Default levels” in the
console and make sure that "Info" is checked. Congratulations! You
performed the log action on the debugging console.

The message you’ve logged is "hiya friend!". hiya friend! is a string (a


sequence of characters).

Give It a Try!
Let’s use [Link] to do something a little more interesting. Here’s a block of
JavaScript code that loops through the numbers 0 through 9 and prints them
out to the console:

for (var i = 0; i < 10; i++) {


[Link](i);
}
Prints:
0
1
2
3
4
5
6
7
8
9
This is called a loop.

Based on this loop's settings, any code written inside the curly
brackets {...} will be repeated ten times. In this case, [Link] prints out the
value of i each time the loop runs. Don't worry if you're not sure about what
the syntax means at this point. Later in this course, you will learn more about
how and when to use loops.
[Link] Demo

Other console methods

Browser console has other methods that can be very useful when poking
around. For example, try typing [Link](["orange", "strawberry", "banana"]) in
the console. This method will create a table and display the data in it.

What We've Learned So Far


We've covered a lot already! You have:

 Learned that all major browsers come with built-in JavaScript engines that
allow browsers to run and execute JavaScript code.
 Practiced running JavaScript code in the browser console
 Added styles to a webpage just by running code in the console

Data types

Data is Everywhere!

All of these things can be represented as data:


 The grade you received on your first math test.
 The conversation you had earlier today.
 The decision you made to sit down and watch this video.
 And more...

Data is Important

It helps us:

 Understand the world


 Recognize trends
 Make educated guesses and
 Inform our decisions

Data and data types are the building blocks of any programming language
because they help us organize information and determine how our programs
will run.

In this lesson we will learn how to define and manipulate the primitive data
types of JavaScript.

 numbers
 strings
 booleans
 undefined
 null

Once you're familiar with these data types, you'll see how you can store data
in variables that you can reuse to manipulate data with your code.

Numbers
Defining a number in JavaScript is actually pretty simple. The Number data
type includes any positive or negative integer, as well as decimals. Entering a
number into the console will return it right back to you.

3
Returns: 3
There, you did it.
Arithmetic operations
You can also perform calculations with numbers pretty easily. Basically, type
out an expression the way you would type it in a calculator.

3 + 2.1
Returns: 5.1

Arithmetic Operators in JavaScript

Operat
Name Meaning
or

Addition a+b Adds a and b

Subtraction a-b Subtracts b from a

Multiplication a * b Multiplies a and b

Division a/b Divides a by b

Modulo a%b Returns the remainder of a / b

Exponent a ** b Raises a to the power of b

The Modulo Operator


You are probably familiar with the basic operators, but you might not have
seen the % operator yet.

We use the modulo operator to return the remainder of a division operation.


This can be very helpful in a lot of programming tasks.

Comparing numbers
What about comparing numbers? Can you do that? Well of course you can!

Just like in mathematics, you can compare two numbers to see if one’s
greater than, less than, or equal to the other.

5 > 10
Returns: false
5 < 10
Returns: true
5 == 10
Returns: false
Comparisons between numbers will either evaluate to true or false. Here are
some more examples, so you can try it out!

Comparison Operators

Operat
Meaning
or

< Less than

> Greater than

<= Less than or Equal to

>= Greater than or Equal to

== Equal to

!= Not Equal to

Comparison Operator Practice

COMMENTS

Show TranscriptSummarize Video


Video Transcript
0:00
A programming language is used for a computer to understand.
0:03
But as your code gets more and more complex, it can get harder and harder
0:06
for you and other humans to read your code and to understand what it does.
0:10
Comments are often used by developers to help clarify the meaning of your
code
0:14
in a human-friendly language.
0:16
In JavaScript, a comment is any text after a double forward slash
0:20
if you want to write comments one line at a time like this, or
0:23
any text in between a slash star and
0:25
star slash if you know you're going to be writing a block of comments.
0:30
Comments are not executed by the JavaScript interpreter, so
0:32
you could pretty much say anything you want in the comment.
0:35
But usually you try to make them a little more useful than this.
0:38
For example, here's some code I wrote a while ago, and
0:41
it's not really obvious to me what I was doing with this code.
0:44
There's seems to be a function, a for loop,
0:47
some variables with really bad variable names.
0:50
Don't worry if you don't know what any of these means just yet.
0:53
What you need to know right now is that if I had used comments like this,
0:58
I would, and you probably would too,
1:00
have an easier time remembering what this code was originally for.
1:04
See, now I can tell that this function reverses the order of characters in
1:07
a word, and it does this by looping over the characters in reverse order and
1:12
adding them to a new word.
1:14
Some of the quizzes in this course might include comments that give you hints
or
1:18
instructions to complete a quiz.
1:20
We encourage you to use comments in your own code
1:22
to explain any non-obvious code you write in your quizzes.
1:26
Not only will you develop good coding habits, but
1:28
you will also improve the readability of your code
1:31
if you ever need to refer back to these quizzes for review.
1:34
All right, now it's time to go on to your first quiz.
1:38
Good luck.
// You're about to take your first programming quiz!

Before you move onto the quiz, we want to talk about something you'll see
quite often throughout this course: comments!

You can use comments to help explain your code and make things clearer. In
JavaScript, comments are marked with a double forward-slash //. Anything
written on the same line after the // will not be executed or displayed. To have
the comment span multiple lines, mark the start of your comment with a
forward-slash and star, and then enclose your comment inside a star and
forward-slash / *…* /.

[Link](opens in a new tab) is an open-source backend JavaScript runtime environment. That


basically means that it will run your JavaScript code in the terminal and return any output that is
generated. We'll be using Node to run the code in our workspaces for many of the quizzes in
this course.

STRINGS
Key Points to Remember About Strings

 Strings can be any combination of characters -- letters, numbers and even


emojis
 You must use matching quotes at the beginning or end of the string --
otherwise JavaScript thinks you are referring to a variable

String concatenation
Strings are a collection of characters enclosed inside double or single quotes.
You can use strings to represent data like sentences, names, addresses, and
more. Did you know you can even add strings together? In JavaScript, this is
called concatenating. Concatenating two strings together is actually pretty
simple!

Variables
Variables Allow Us to Store Data!
With variables, you no longer need to work with one-time-use data.

At the beginning of this course, you declared the value of a string, but you
didn't have a way to access or reuse the string later.

"Hello"; // Here's a String "Hello"


"Hello" + " World"; // Here's a new String (also with the
value "Hello") concatenated with " World"
Storing the value of a string in a variable is like packing it away for later use.

var greeting = "Hello";


Now, if you want to use "Hello" in a variety of sentences, you don't need to
duplicate "Hello" strings. You can just reuse the greeting variable.

greeting + " World!";


Returns: Hello World!
greeting + " Mike!";
Returns: Hello Mike!
You can also change the start of the greeting by reassigning a new string
value to the variable greeting.

greeting = "Hola";
greeting + " World!";
Returns: Hola World!
greeting + " Mike!";
Returns: Hola Mike!
JavaScript Has Three Ways to Declare Variables
- var, let, and const
In the example and video above, we used the keyword var to declare our
variable. When we use var we create a variable that is available in the global
scope -- which means it can be used anywhere in our program. We'll talk
more about scope later, but for now, keep in mind that globally scoped
variables are not a good practice.

Here's why: in a small program with just a few variables, it's easy to keep
track of the variables and avoid collisions. But when you are working on a
complex project or with a large team. It is very easy to inadvertently overwrite
an existing variable that is hidden in another part of the
program. let and const avoid this issue because they are only available in the
scope where they are declared. Again, more on scope later. For now,
remember:

Best Practice #1

Always use let or const instead of var

Which to Use - let or const ?


 Use let when we think that the value of a variable might change
let lets us to assign a new value to the variable name when needed.
 Use const when we think that the value of a variable is fixed
A variable declared with const cannot be assigned a new value. It's value
is constant.

So which should be your default choice? That's easy. Pick the one that gives
you more control: const. Using const means that your program will throw an
error if there is an attempt to change the value of the variable when the code
runs. If that is an intended outcome, you can go back and revise your code to
declare the variable with let. If you did not intend for the value to change,
congratulations! You've just discovered a bug that you can fix before it causes
any problems.

var still works and will remain working for the foreseeable future! 🤔
You'll see that we use var instead of let and const in some of the demo videos
in this course. While all of the modern browsers support let and const, var is
still part of the language. You'll see it quite often in legacy code.

Naming conventions
When you create a variable, you should write the name of the variable using
camelCase: the first word is lowercase, and all following words begin with a
capital letter. Additionally, aim to use a variable name that accurately yet
succinctly describes what the data represents.

// uses camelCase if the variable name is multiple words


const totalAfterTax = 53.03;

// uses lowercase if the variable name is one word


const tip = 8;
Not using camelCase for your variables names is not going to
necessarily break anything in JavaScript. But there are recommended style
guides used in all programming languages that help keep code consistent,
clean, and easy-to-read. This is especially important when working on larger
projects that will be accessed by multiple developers.

Indexing
Did you know that you can access individual characters in a string? To access
an individual character, you can use the character's location in the string,
called its index. Just put the index of the character inside square brackets
(starting with [0] as the first character) immediately after the string. For
example:

"James"[0];
Returns: "J"
or more commonly, you will see it like this, using a variable:

const name = "James";


name[0];
Returns: "J"
Escaping strings
There are some cases where you might want to create a string that contains
more than just numbers and letters. For example, what if you want to use
quotes in a string?

"The man whispered, "please speak to me.""


Uncaught SyntaxError: Unexpected identifier
If you try to use quotes within a string, you will receive a SyntaxError like the
one above.

Because you need to use quotes to denote the beginning and end of strings,
the JavaScript engine misinterprets the meaning of your string by thinking "The
man whispered, " is the string. Then, it sees the remaining please speak to
me."" and returns a SyntaxError .

If you want to use quotes inside a string, and have JavaScript not
misunderstand your intentions, you’ll need a different way to write quotes.
Thankfully, JavaScript has a way to do this using the backslash character ( \ ).

Escaping characters
In JavaScript, you use the backslash to escape other characters.

Escaping a character tells JavaScript to ignore the character's special


meaning and just use the literal value of the character. This is helpful for
characters that have special meanings like in our previous example with
quotes "…".

Because quotes are used to signify the beginning and end of a string, you can
use the backslash character to escape the quotes in order to access the literal
quote character.

"The man whispered, \"please speak to me.\""


Returns: The man whispered, "please speak to me."
This guarantees that the JavaScript engine doesn’t misinterpret the string and
result in an error.
💡 By using the backslash to escape characters, the JavaScript engine can
understand the meaning of your strings.

Special characters
Quotes aren’t the only special characters that need to be escaped, there’s
actually quite a few(opens in a new tab). However, to keep it simple, here’s
a list of some common special characters in JavaScript.

Cod
Character
e

\\ \ (backslash)

" '' (double quote)

' ' (single quote)

\n newline

\t tab

The last two characters listed in the table, newline \n and tab \t, are unique
because they add additional whitespace to your Strings. A newline character
will add a line break and a tab character will advance your line to the next tab
stop(opens in a new tab).

"Up up\n\tdown down"


Returns:
Up up
down down

Booleans
A boolean variable can take either of two values - true or false. For example,

const studentName = "John";


const haveEnrolledInCourse = true;
const haveCompletedTheCourse = false;
A boolean variable is mainly essential in evaluating the outcome of
conditionals (comparisons). The result of a comparison is always a
boolean variable. We'll study conditionals in our upcoming lesson, but let's
look at our previous example to understand the role of boolean in conditional:

if (haveEnrolledInCourse) {
[Link]("Welcome "+studentName+" to Udacity!");
// Will run only if haveEnrolledInCourse is true
}
Let's look at an example that will explain the role of a boolean variable in
comparison.

const a = 10;
const b = 20;
// a comparison - we will study this in detail in
upcoming lesson
if (a>b) { // The outcome of a>b will be a boolean
[Link]("Variable `a` has higher value"); // if
a>b is true
} else {
[Link]("Variable `b` is greater than or equal to
`a`"); // if a>b is false
}
In general cases (regular equality check), a true corresponds to number 1,
whereas false represents a number 0. For example:

if (1) {
[Link]("This statement will always execute
because conditional is set to 1 i.e., true");
}

if (0) {
[Link]("This statement will NEVER execute
because conditional is set to 0 i.e., false");
}

What is the Difference Between null and undefined ?

nullrefers to the "value of nothing", while undefined refers to the "absence of


value".
Example: var x; returns undefined but var x=null; returns null.
What is NaN?
NaNstands for "Not-A-Number" and it's often returned indicating an error with
number operations. For instance, if you wrote some code that performed a
math calculation, and the calculation failed to produce a valid
number, NaN might be returned.

// calculating the square root of a negative number will


return NaN
[Link](-10)

// trying to divide a string by 5 will return NaN


"hello"/5

Equality
So far, you’ve seen how you can use == and != to compare numbers and
strings for equality. However, if you use == and != in situations where the
values that you're comparing have different data-types, it can lead to some
interesting results. For example,

"1" == 1
Returns: true
and

0 == false
Returns: true. The == operator is unable to differentiate 0 from false.
' ' == false
Returns: true. Both the operands on either side of the == operator are first
converted to zero, before comparison.
All of the above three evaluate to true. The reason for such interesting
outcomes is Type Conversion. In the case of regular comparison, the
operands on either side of the == operator are first converted to numbers,
before comparison. Therefore, a ' ', false, and 0 are all considered equal.
Similarly, a '1' and 1 are also considered equal. If we don't want to convert the
operands, before comparison, we have to use a strict comparison ===, that
is explained below.

Implicit Type Coercion


JavaScript is known as a loosely typed language.

Basically, this means that when you’re writing JavaScript code, you do not
need to specify data types. Instead, when your code is interpreted by the
JavaScript engine it will automatically be converted into the "appropriate" data
type. This is called implicit type coercion and you’ve already seen examples
like this before when you tried to concatenate strings with numbers.

"julia" + 1
Returns: "julia1"
In this example, JavaScript takes the string "julia" and adds the number 1 to it
resulting in the string "julia1". In other programming languages, this code
probably would have returned an error, but in JavaScript the number 1 is
converted into the string "1" and then is concatenated to the string "julia".

It’s behavior like this which makes JavaScript unique from other programming
languages, but it can lead to some quirky behavior when doing operations and
comparisons on mixed data types.

Strongly Typed vs Loosely Typed


A strongly typed language is a programming language that is more likely to
generate errors if data does not closely match an expected type.

Example of strongly typed programming language code

int count = 1;
string name = "Julia";
double num = 1.2932;
float price = 2.99;
With a loosely typed language like JavaScript, you don’t need to specify
data types; this provides a lot more flexibility and is often faster to write.
However, loose typing can lead to errors that are hard to diagnose due to
implicit type coercion.

Equivalent code in JavaScript

// equivalent code in JavaScript


let count = 1;
const name = "Julia";
const num = 1.2932;
const price = 2.99;

Strict vs. Loose Equality


In the example below, JavaScript takes the string "1", converts it to true, and
compares it to the boolean true.

"1" == true
Returns: true
When you use the == or != operators, JavaScript first converts each value to
the same type (if they’re not already the same type); this is why it's called
"type coercion"! This is often not the behavior you want, and it’s actually
considered bad practice to use the == and != operators when comparing
values for equality.

Instead, in JavaScript it’s better to use strict equality to see if numbers,


strings, or booleans, etc. are identical in type and value without doing the type
conversion first. To perform a strict comparison, simply add an additional
equals sign = to the end of the == and != operators.

"1" === 1
Returns: false
This returns false because the string "1" is not the same type and value as the
number 1.

0 === false
Returns: false
This returns false because the number 0 is not the same type and value as
the boolean false. Just like strict equality operator, there is also a strict non-
equality operator !== that can be used instead of != if you don't want a type-
conversion, before comparison. For example,

0 !== true
Returns: true
and

'1' !== 1
Returns: true
We Write Code to Solve Problems
When you write code, you break down problems into steps that are executed
by a computer. These steps are known as an algorithm.

Example: Purchase Algorithm

Think about the steps you need to take to decide whether to purchase an
item.

1. Do I want the item?


2. Do I have enough money to purchase the item?

If the answer to both questions is yes, you will purchase the item. The process
you went through to solve that problem, and the steps you took in order to do
so, is at the heart of writing code.

In this lesson we'll learn about the conditional statements we can use in
JavaScript to execute the algorithms we need to solve problems.

What We Will Cover in This Lesson

You will learn how to:

 Write if...else and else...if conditionals.


 Use logical operators to handle more complex logic.
 Identify truthy and falsy values.
 Use ternary operators for more concise conditional logic.
 Use a switch statement to chain multiple else if statements.
 DEFINITION: A flowchart is a visual diagram that outlines the solution to
a problem through a series of logical statements. The order in which
statements are evaluated and executed is called the control flow.
 Flowcharts are a great way to visualize a problem before you start
writing code.
 Question 1 of 2

If...else Statements
If...else statements allow you to execute certain pieces of code based on a
condition, or set of conditions, being met.

if (/ *this expression is true* /) {


// run this code
} else {
// run this code
}
This is extremely helpful because it allows you to choose which piece of code
you want to run based on the result of an expression. For example,

const a = 1;
const b = 2;

if (a > b) {
[Link]("a is greater than b");
} else {
[Link]("a is less than or equal to b");
}
Prints: "a is less than or equal to b"
A couple of important things to notice about if...else statements.

The value inside the if statement is always converted to true or false.


Depending on the value, the code inside the if statement is run or the code
inside the else statement is run, but not both. The code inside
the if and else statements are surrounded by curly braces {...} to separate the
conditions and indicate which code should be run.

TIP: When coding, sometimes you may only want to use an if statement.
However, if you try to use only an else statement, then you will receive the
error SyntaxError: Unexpected token else . You’ll see this error
because else statements need an if statement in order to work. You can’t have
an else statement without first having an if statement.

Test Your if else Intuition

Are curly braces always necessary?


Curly braces are not necessary if you have only one line of code to execute
following an if or else statement. They are necessary if you have more than
one line of code to execute.

That being. said, in most cases, even though it is not required, it is a better
practice to use curly braces whenever you are using a conditional
statement.

const weather = "sunny";

if (weather === "snow") {


[Link]("Bring a coat.");
} else if (weather === "rain") {
[Link]("Bring a rain jacket.");
} else {
[Link]("Wear what you have on.");
}
Prints: Wear what you have on.
By adding the extra else if statement, you're adding an extra conditional
statement.

If it’s not going to snow, then the code will jump to the else if statement to see if
it’s going to rain. If it’s not going to rain, then the code will jump to
the else statement.

The else statement essentially acts as the "default" condition in case all the
other if statements are false.

LOGICAL OPERATORS

The && symbol is the logical AND operator, and it is used to combine two logical expressions
into one larger logical expression. If both smaller expressions are true, then the entire
expression evaluates to true. If either one of the smaller expressions is false, then the whole
logical expression is false.

Logical expressions
Logical expressions are similar to mathematical expressions, except logical
expressions evaluate to either true or false.
Logical operators
Logical operators can be used in conjunction with boolean values
(true and false) to create complex logical expressions.

By combining two boolean values together with a logical operator, you create
a logical expression that returns another boolean value. Here’s a table
describing the different logical operators:

Operat Meanin
Example How it works
or g

Logical value1 &&


&& Returns true if both value1 and value2 evaluate to true.
AND value2

value1 || Returns true if either value1 or value2 (or even both!)


|| Logical OR
value2 evaluates to true.

Logical Returns the opposite of value1. If value1 is true, then !


! !value1
NOT value1 is false.

By using logical operators, you can create more complex conditionals like
Julia’s weekend example.

Before you advance any further in the lesson, here’s the truth tables for logical
AND ( && ) and logical OR ( || ).

Truth Tables
&& (AND)

A &&
A B
B

tru tru
true
e e

tru fals
false
e e

fals tru
false
e e
A &&
A B
B

fals fals
false
e e

|| (OR)

A ||
A B
B

tru tru
true
e e

tru fals
true
e e

fals tru
true
e e

fals fals
false
e e

Truth tables are used to represent the result of all the possible combinations
of inputs in a logical expression. A represents the boolean value on the left-
side of the expression and B represents the boolean value on the right-side of
the expression.

Truth tables can be helpful for visualizing the different outcomes from a logical
expression. However, do you notice anything peculiar about the truth tables
for logical AND and OR?

Short-circuiting
In some scenarios, the value of B in logical AND and OR doesn't matter.
In both tables, there are specific scenarios where regardless of the value of B,
the value of A is enough to satisfy the condition.

For example, if you look at A AND B, if A is false, then regardless of the value B,
the total expression will always evaluate to false because both A and B must
be true in order for the entire expression to be true.

This behavior is called short-circuiting because it describes the event when


later arguments in a logical expression are not considered because the first
argument already satisfies the condition.

Truthy and Falsy


Every value in JavaScript has an inherent boolean value. When that value is
evaluated in the context of a boolean expression, the value will be
transformed into that inherent boolean value.

The paragraph above is pretty dense with information. You should probably
re-read it again! ☝️

Falsy values
A value is falsy if it converts to false when evaluated in a boolean context. For
example, an empty String "" is falsy because, "" evaluates to false. You already
know if...else statements, so let's use them to test the truthy-ness of "".

if ("") {
[Link]("the value is truthy");
} else {
[Link]("the value is falsy");
}
Returns: "the value is falsy"

Here’s the list of all of the falsy values:

1. the Boolean value false

 the null type


 the undefined type
 the number 0
 the empty string ""
 the odd value NaN (stands for "not a number", check out the NaN MDN
article(opens in a new tab))

That's right, there are only six falsy values in all of JavaScript!

Truthy values
A value is truthy if it converts to true when evaluated in a boolean context. For
example, the number 1 is truthy because, 1 evaluates to true. Let's use an
if...else statement again to test this out:

if (1) {
[Link]("the value is truthy");
} else {
[Link]("the value is falsy");
}
Returns: "the value is truthy"
Here are some other examples of truthy values:

true
42
"pizza"
"0"
"null"
"undefined"
{}
[]
Essentially, if it's not in the list of falsy values, then it's truthy!

TIP: Using if(isGoing) is the same as using if(isGoing === true). Alternatively,
using if(!isGoing) is the same as using if(isGoing === false) .

Ternary operator
The ternary operator provides you with a shortcut alternative for writing
lengthy if...else statements.

conditional ? (if condition is true) : (if condition is


false)
To use the ternary operator, first provide a conditional statement on the left-
side of the ?. Then, between the ? and : write the code that would run if the
condition is true and on the right-hand side of the : write the code that would
run if the condition is false. For example, you can rewrite the example code
above as:

const isGoing = true;


const color = isGoing ? "green" : "red";
[Link](color);
Prints: "green"
Switch statement

Switch Statement
A switch statement is an another way to chain multiple else if statements that
are based on the same value without using conditional statements.
Instead, you just switch which piece of code is executed based on a value.

Switch Looks for Matching Values

When the switch statement evaluates, it starts at the top and looks for
a case clause whose expression evaluates to the same value as the result of
the expression passed to the switch statement.

When it finds a match, it transfers control to that case clause to executed the
code for that case.

Use Break to Avoid Falling Through


After the code in the matching case is run, the switch statement continues to
run all of the code below that statement too! This is called falling through.

We can prevent the code from falling through by adding a break statement at
the end of each case.

The break statement will terminate the switch statement and transfer control to
the code following the switch statement which prevents the switch statement
from falling through and running the code in the other case clauses.
LOOPS:
Loops Repeat Blocks of Code
Conditional statements are one way to control the flow of code -- if a certain
condition is true, execute this block of code, otherwise, execute that other
block of code.

Loops are another way to control the flow of code by allowing us to execute a
block of code multiple times.

for Loops Require a Start, Stop and Step


The for loop explicitly forces you to define the start point, stop point, and each
step of the loop. In fact, you'll get an Uncaught SyntaxError: Unexpected token ) if
you leave out any of the three required pieces.

for ( start; stop; step ) {


// do this thing
}
Here's an example of a for loop that prints out the values from 0 to 5. Notice
the semicolons separating the different statements of the for loop: var i = 0; i <
6; i = i + 1

for (let i = 0; i < 6; i = i + 1) {


[Link]("Printing out i = " + i);
}
Prints:
Printing out i = 0
Printing out i = 1
Printing out i = 2
Printing out i = 3
Printing out i = 4
Printing out i = 5

How the Loop is Interpreted


i< [Link]
i
6 output
0 true Printing out i = 0
1 true Printing out i = 1
2 true Printing out i = 2
3 true Printing out i = 3
4 true Printing out i = 4
5 true Printing out i = 4
fals
6
e

Nested Loops Add Complexity


Nested loops are just loops inside of other loops. Take a look at our demo
code:

for (let x = 0; x < 3; x = x + 1) {


for (let y = 0; y < 2; y = y + 1) {
[Link](x + ", " + y);
}
}
This is how the loop is interpreted in the browser:

x < y < [Link]


x y
3 2 output
0 true 0 true 0, 0
0 true 1 true 0, 1
0 true 2 false
1 true 0 true 1, 0
1 true 1 true 1, 1
1 true 2 false
2 true 0 true 2, 0
2 true 1 true 2, 1
2 true 2 false
3 false
Increment and Decrement Operators
Increment and decrement operators are shortcuts that are often used in the
step part of a for loop.

Increment Operator

The increment operator ++ adds one a to variable, returns a value and


assigns the incremented value to the variable.

x++ is the postfix operator, which means that it returns the


value before incrementing it:

let x = 2;
x++ //returns 2 then assigns 3 as the value of x
[Link](x); // logs out 3
++x is the prefix operator, which means that it returns the
value after incrementing it:

let x = 2;
++x // assigns 31 as the value of x then returns 3
[Link](x); // logs out 3
Try it in the the console!

Decrement Operator

a The decrement operator -- subtracts one from a variable, returns a value


and assigns the decremented value to the variable.

Similiar to the increment operator, x-- is the postfix operator, which means
that it returns the value before incrementing it:

let x = 2;
x-- //returns 2 then assigns 1 as the value of x
[Link](x); // logs out 1
--x is the prefix operator, which means that it returns the
value after incrementing it:

let x = 2;
--x // assigns 1 as the value of x then returns 1
[Link](x); // logs out 1
Try it in the the console!

Assignment Operators
An assignment operator is a shorthand way to peform a mathematical
operation on a variable and assigns that value to the variable.

You can use assignment operators for addition, subtraction, multiplication,


and division.

// Add y to x
x += y // x = x + y

// Subtract y from x
x -= y // x = x - y

// Multiply x by x
x *= y // x = x* y

// Divide x by y
x /= y // x = x / y
These assignment operators will come in handy as you create more loops!

FUNCTIONS:
What Are Functions?
Functions are reusable chunks of code.

Functions are very helpful as the problems we need to solve with our code get
more complex. We'll often need to repeat steps on different inputs -- and
functions let us do that!

***Analogy: Microwaving pizza***


The microwave Pizza Reheat button uses a function to calculate the optimal
power level and time to reheat pizza so James doesn't have to calculate the
settings from scratch every time he is hungry.

 The input is the number of slices that need to be reheated


 The output is reheated pizza
 function reverseString(reverseMe) {
 let reversed = "";
 for (let i = [Link] - 1; i >= 0; i--) {
 reversed += reverseMe[i];
 }
 return reversed;
 }

 [Link](reverseString("Julia"));
Let's break it down:

 The function has one parameter -- a variable named reverseMe.


 reverseMewill store the argument -- the value of the string that we want the
function to operate on.
 The variable reversed is intialized as an empty string. It will be used to store the
reversed string as as it is being constructed.
 The function loops through each character the reverseMe string using string
indexes, from the end to the beginning and adds each character to reversed.
 When the loop is complete, reversed is returned.

Parameters vs. Arguments


At first, it can be a bit tricky to know when something is either a parameter or
an argument. The key difference is in where they show up in the code.
A parameter is always going to be a variable name and appears in the
function declaration. On the other hand, an argument is always going to be
a value (i.e. any of the JavaScript data types - a number, a string, a boolean,
etc.) and will always appear in the code when the function is called or invoked.

The function body is enclosed inside curly brackets:


Return statements explicitly make your function return a value:
You invoke or call a function to have it do something:

Output from a Function


There are two ways to get output from a function:
1. [Link] is used to print a value to the JavaScript console.
2. The return keyword is used to stop execution of a function and *return the
value back to the caller.

Points to Remember About Returning and Printing

 Returning is different from printing

Printing a value to the JavaScript console only displays the value but the
value can't be used anywhere else.

 Printing is great for debugging code

Using [Link] to test your code in the JavaScript console or to print out
values as your code runs can be extremely helpful in pinpointing where
something has gone wrong in your code.

 All function calls return something

If a return value is not specified, the function will return undefined .

 The return keyword will stop the execution of a function

Any code after a return statement will be ignored.


Demo Code: Function to determine if a number is a prime number

Math Review:
A prime number is an integer that is not a product of two smaller integers.
The modulo operator(opens in a new tab) % returns the remainder left over
when one operand is divided by a second operand.
You can check for prime numbers by dividing them by smaller integers. If the
number can be divided without remainder by any integer greater than 1 it is
not a prime number.
function isPrime(integer) {
for (let x = 2; x < integer; x++ ) {
if(integer % x === 0) {
[Link](integer + " is divisible by " +
x);
return false
}
}
return true
}

Exploring [Link] and return Statements


Paste the following function declaration and function invocation into the
JavaScript console to see the difference between logging (printing) and
returning:

function isThisWorking(input) {
[Link]("Printing: isThisWorking was called and " +
input + " was passed in as an argument.");
return "Returning: I am returning this string!";
}

isThisWorking(3);
Prints: "Printing: isThisWorking was called and 3 was passed in as an
argument"
Returns: "Returning: I am returning this string!"
If you don't explicitly define a return value, the function will return undefined by
default.

function isThisWorking(input) {
[Link]("Printing: isThisWorking was called and " +
input + " was passed in as an argument.");
}

isThisWorking(3);
Prints: "Printing: isThisWorking was called and 3 was passed in as an
argument"
Returns: undefined

Understanding Scope
Scope is the part of the program where a particular identifier, such as a
variable or a function name, is visible or accessible.

As a programmer, you'll run into a lot of situations where understanding scope


will be critical to writing effective and error-free code.
***Analogy: Finding a Book***
When James is inside the library he is in scope to find out where the
book Great Expectations is shelved. The librarian has that information is able
to share it with James.

When James is outside of the library, the person he asked about Great
Expectations didn't have any information about library or the books inside of it.
In this case, James's question is out of scope.

The Three Types of Scope in JavaScript


JavaScript has three types of scope.

 global scope
 function scope
 block scope

The first two are pretty simple:

 Variables declared in the global scope are accessible to any other part of the
program.
 Variables declared inside a function are in the function scope which means
they are only accessible inside that function.

Block scope is more complicated. We'll learn more about that later in this
lesson.

How Does Javascript Find a Variable? It Uses the


Scope Chain
When the JavaScript engine is looking for a variable, it starts from the current
scope and moves outward:

1. The JavaScript engine will start looking in the scope where the variable is
requested.
2. If it can't find it in the current scope, it moves out one level and checks again.
3. It keeps moving to the outer scope until it has reached the global scope.
4. If the JavaScript engine checks all of the outer functions and global scope,
and it still can't find the identifier then it will return a Reference error.
Block Scope Only Works with let And const
Unlike with function scope, if you declare a variable inside
a block using var the variable will be accessible both inside the block and in
the block's outer scope.

A New Type of Scope


With the ES6 version of JavaScript, a new type of scope was created: block
scope which limits the scope of a variable to the block of code where it is
declared.

What is a Block?

A block is a group of statements in between curly braces. You've seen blocks


in conditional statements:

When you declare a variable using var inside a block (such as within an
if statement, loop, or function), the scope of that variable is not
limited to the block. Instead, var has function-level scope or global
scope, meaning it is accessible outside of the block, but still within the
function (if declared inside a function).
var does not respect block scope: If you declare a var inside a block,
it will be accessible outside of that block, as long as it’s within the
same function or global scope.

When Should I Use var Instead of let or const ?


NEVER!

You might be wondering:

"Why wouldn't I always use global variables? Then, I would never need to use
function arguments since ALL my functions would have access to
EVERYTHING!"
Well... Global variables might seem like a convenient idea at first, especially
when you're writing small scripts and programs, but there are many reasons
why you shouldn't use them unless you have to. For instance, global variables
can conflict with other global variables of the same name. Once your
programs get larger and larger, it'll get harder and harder to keep track and
prevent this from happening.

There are also other reasons you'll learn more about in more advanced
courses. But for now, just work on minimizing the use of global variables as
much as possible.

💡 Always use let and const instead of var.

Scope Can Be Tricky!


Scope can be a tricky subject, especially when you're working in both global
and function scope.

Shadowing occurs when variables in different scopes have the same name.
When this happens the variable in the inner scope overrides the variable in
the outer scope.

What You’ve Learned So Far:


 If an identifier is declared in global scope, it's available everywhere.
 If an identifier is declared in function scope, it's available in the function it
was declared in (even in functions declared inside the function).
 If an identifier is declared in block scope with var, it is available in the block
and in the outer scope of the block it was declared in.
 If an identifier is declared in block scope with let or const, it is only available in
the block it was declared in.
 When trying to access an identifier, the JavaScript Engine will first look in the
current function. If it doesn't find anything, it will continue to the next outer
function to see if it can find the identifier there. It will keep doing this until it
reaches the global scope.
 Global identifiers are a bad idea. They can lead to bad variable names,
conflicting variable names, and messy code.

Function Expression

Once you know how to declare a function, a whole new set of possibilities will
open up to you.
For instance, remember how you can store anything you want in a variable?
Well, in JavaScript, you can also store functions in variables. When a function
is stored inside a variable it's called a function expression.

const catSays = function(max) {


let catMessage = "";
for (let i = 0; i < max; i++) {
catMessage += "meow ";
}
return catMessage;
};
Notice how the function keyword no longer has a name.

const catSays = function(max) {


// code here
};
It's an anonymous function, a function with no name, and you've stored it in
a variable called catSays.

And, if you try accessing the value of the variable catSays, you'll even see the
function returned back to you.

catSays;
Returns:
function(max) {
let catMessage = ""
for (let i = 0; i < max; i++) {
catMessage += "meow ";
}
return catMessage;
}

Function Expressions vs Function Declarations


Deciding when to use a function expression and when to use a function
declaration can depend on a few things, and you will see some ways to use
them in the next section. But, one thing you'll want to be careful of is hoisting.
We'll look at that next.

Hoisting
Sometimes your JavaScript code will produce errors that may seem
counterintuitive at first. Hoisting is another one of those topics that might be
the cause of some of these tricky errors you're debugging.

Hoisting is a result of how JavaScript is interpreted by your browser.


Essentially, before any JavaScript code is executed, all function declarations
and variables declared with var are hoisted, which means they're raised to the
top of the function scope.

in JavaScript we can call a function before we declare it due to hoisting. Before any JavaScript
code is executed, all function declarations and variables declared with var are hoisted to the
top of their current scope.

What You’ve Learned So Far:


 JavaScript hoists function declarations and variables declared with var to the
top of the current scope.
 Hoisting doesn't happen when variables are declared with let or const.
 Variable assignments are not hoisted so function expressions are not hoisted.

ARRAYS

Hurray for Arrays!


 An array is a data structure we can use to store multiple values.
 Values in an array are ordered (like a numbered list).
 The numbering of the array order starts at 0 -- not at 1

Arrays
An array is useful because it stores multiple values into a single, organized
data structure. You can define a new array by listing values separated with
commas between square brackets [].

You can even store an array in an array to create a nested array!

// creates a `arraysInArrays` array with three arrays


const arraysInArrays = [[1, 2, 3], ["Julia", "James"],
[true, false, true, false]];

Using the Array Constructor


You may also see arrays created this way:

// creates a new empty array


const emptyArray = new Array();

// creates a `donuts` array with three strings


const donuts = new Array("glazed", "powdered", "jelly");
This syntax is valid, but it is preferred to use the literal constructor because
the syntax is simpler and more intuitive.

// creates a new empty array


const emptyArray = [];

// creates a `donuts` array with three strings


const donuts = ["glazed", "powdered", "jelly"];

Elements and Indexes


 An element is an individual piece of data in an array.
 Each element in the array is numbered, starting with 0. This number is called
the index.
 The index allows us to access the element's position in the array.

const donuts = [
Primitive vs. Object Types in JavaScript
String, Number, Boolean, undefined and null are considered Primitive
Types(opens in a new tab) in JavaScript. These relatively simple data types
represent just one value which makes it easy for JavaScript to store that
value. So when you assign a primitive value to a variable, JavaScript actually
assigns that value.

Arrays are more complicated because they consist of a list of values which
makes storage much more complicated. Arrays are actually Object
types(opens in a new tab) which means that instead of assigning all of the
values of the list to the array, JavaScript simply assigns a reference to where
to find the values in the array. Even if the values inside the object change, the
reference address doesn't.

Here's an analogy that might help. Think of a JavaScript array as if it were a


house. The house has a group of people who live inside it. If those people
move out, and a new group of people moves in, the names of the people
inside the house changes, but the house's postal address won't.
Array Properties and Methods

Arrays are Powerful Data Structures


Arrays have a number of properties and built-in methods.

Array properties includelengthwhich is similar to the length method for String


types.

Common Array methods include:

 reverse: reverses the order of the elements in an array


 sort: sorts the elements in an array
 push: adds elements to an array
 pop: removes elements from an array

You might also like