JavaScript: History, Basics, and Console Use
JavaScript: History, Basics, and Console Use
JavaScript Today
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]
[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.
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:
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
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.
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!
Data is Important
It helps us:
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
Operat
Name Meaning
or
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
== Equal to
!= Not Equal to
COMMENTS
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 / *…* /.
STRINGS
Key Points to Remember About Strings
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.
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
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.
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:
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.
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.
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)
\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).
Booleans
A boolean variable can take either of two values - true or false. For example,
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");
}
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.
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.
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.
"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.
"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.
Think about the steps you need to take to decide whether to purchase an
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.
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.
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.
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.
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
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.
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"
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.
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.
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.
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.
Increment Operator
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
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.
// 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!
Printing a value to the JavaScript console only displays the value but the
value can't be used anywhere else.
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.
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
}
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.
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.
global scope
function scope
block scope
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.
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.
What is a Block?
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.
"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.
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.
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.
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;
}
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.
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.
ARRAYS
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 [].
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.