Introduction To Javascript
Introduction To Javascript
What is JavaScript?
Last year, millions of learners from our community started with JavaScript.
Why? JavaScript is primarily known as the language of most modern web
browsers, and its early quirks gave it a bit of a bad reputation. However, the
language has continued to evolve and improve. JavaScript is a powerful,
flexible, and fast programming language now being used for increasingly
complex web development and beyond!
Since JavaScript remains at the core of web development, it’s often the first
language learned by self-taught coders eager to learn and build. We’re excited
for what you’ll be able to create with the JavaScript foundation you gain here.
JavaScript powers the dynamic behavior on most websites, including this one.
In this lesson, you will learn introductory coding concepts including data types
and built-in objects—essential knowledge for all aspiring developers. Make
sure to take notes and pace yourself. This foundation will set you up for
understanding the more complex concepts you’ll encounter later.
Console
The console is a panel that displays important messages, like errors, for
developers. Much of the work the computer does with our code is invisible to
us by default. If we want to see things appear on our screen, we can print,
or log, to our console directly.
console.log(5);
This example logs 5 to the console. The semicolon denotes the end of the line,
or statement. Although in JavaScript your code will usually run as intended
without a semicolon, we recommend learning the habit of ending each
statement with a semicolon so you never leave one out in the few instances
when they are required.
You’ll see later on that we can use console.log() to print different kinds of
data.
Instructions
1. Use the console.log code in the editor to log your age to the console.
Run your code when you are ready to see the result
2. On the next line, write another console.log to print out a different
number representing the number of weeks you’ve been programming.
Comments
As we write JavaScript, we can write comments in our code that the computer
will ignore as our program runs. These comments exist just for human readers.
Comments can explain what the code is doing, leave instructions for
developers using the code, or add any other useful annotations.
1. A single line comment will comment out a single line and is denoted
with two forward slashes // preceding it.
// Prints 5 to the console
console.log(5);
You can also use a single line comment to comment after a line of code:
console.log(5); // Prints 5
2. A multi-line comment will comment out multiple lines and is denoted
with /* to begin the comment, and */ to end the comment.
/*
This is all commented
console.log(10);
None of this is going to run!
console.log(99);
*/
You can also use this syntax to comment something out in the middle of
a line of code:
Instructions
To the right, we’ve provided you with the beginning of the book Catch-
22 by Joseph Heller.
Data Types
Data Types are the classifications we give to the different kinds of data that we
use in programming. In JavaScript, there are seven fundamental data types:
The first 6 of those types are considered primitive data types. They are the
most basic data types in the language. Objects are more complex, and you’ll
learn much more about them as you progress through JavaScript. At first,
seven types may not seem like that many, but soon you’ll observe the world
opens with possibilities once you start leveraging each one. As you learn more
about objects, you’ll be able to create complex collections of data.
But before we do that, let’s get comfortable with strings and numbers!
Next, we printed the number 40, notice we did not use quotes.
Instructions
1. Add: +
2. Subtract: -
3. Multiply: *
4. Divide: /
5. Remainder: %
Instructions
1. Inside of a console.log(), add 3.5 to your age.
This is the age you’ll be when we start sending people to live on Mars.
4. Create one last console.log(). Inside the parentheses, multiply 0.2708 by 100.
String Concatenation
Operators aren’t just for numbers! When a + operator is used on two strings, it
appends the right string to the left string:
The computer will join the strings exactly, so we needed to make sure to
include the space we wanted between the two strings.
2. We left off the space last time. Create a second console.log() statement
in which you concatenate the strings 'Hello' and 'World', but this time
make sure to also include a space (' ') between the two words.
Properties
When you introduce a new piece of data into a JavaScript program, the
browser saves it as an instance of the data type. All data types have access to
specific properties that are passed down to each instance. For example, every
string instance has a property called length that stores the number of
characters in that string. You can retrieve property information by appending
the string with a period and the property name:
console.log('Hello'.length); // Prints 5
The . is another operator! We call it the dot operator.
In the example above, the value saved to the length property is retrieved from
the instance of the string, 'Hello'. The program prints 5 to the console,
because Hello has five characters in it.
Methods
Remember that methods are actions we can perform. Data types have access
to specific methods that allow us to handle instances of that data type.
JavaScript provides a number of string methods.
Does that syntax look a little familiar? When we use console.log() we’re calling
the .log() method on the console object. Let’s see console.log() and some real
string methods in action!
You can find a list of built-in string methods in the JavaScript documentation.
Developers use documentation as a reference tool. It describes JavaScript’s
keywords, methods, and syntax.
In addition to console, there are other objects built into JavaScript. Down the
line, you’ll build your own objects, but for now these “built-in” objects are full
of useful functionality.
The great thing about objects is that they have methods! Let’s call
the .random() method from the built-in Math object:
To generate a random number between 0 and 50, we could multiply this result
by 50, like so:
Math.random() * 50;
The example above will likely evaluate to a decimal. To ensure the answer is a
whole number, we can take advantage of another useful Math method
called Math.floor().
Math.floor(Math.random() * 50);
In this case:
If you wanted to see the number printed to the terminal, you would still need
to use a console.log() statement:
console.log(Math.floor(Math.random() * 50)); // Prints
a random whole number between 0 and 50
To see all of the properties and methods on the Math object, take a look at the
documentation here.
VARIABLES
4. 'Arya' is the value assigned (=) to the variable myName. You can also say
that the myName variable is initialized with a value of 'Arya'.
5. After the variable is declared, the string value 'Arya' is printed to the
console by referencing the variable name: console.log(myName).
In the next exercises, we will learn why ES6’s let and const are the preferred
variable keywords by many programmers. Because there is still a ton of code
written prior to ES6, it’s helpful to be familiar with the pre-ES6 var keyword.
If you want to learn more about var and the quirks associated with it, check
out the MDN var documentation.
As mentioned in the previous exercise, the let keyword was introduced in ES6.
The let keyword signals that the variable can be reassigned a different value.
Take a look at the example:
let price;
console.log(price); // Output: undefined
price = 350;
console.log(price); // Output: 350
Notice in the example above:
The const keyword was also introduced in ES6, and is short for the word
constant. Just like with var and let you can store any value in a const variable.
The way you declare a const variable and assign a value to it follows the same
structure as let and var. Take a look at the following example:
If you’re trying to decide between which keyword to use, let or const, think
about whether you’ll need to reassign the variable later on. If you do need to
reassign the variable use let, otherwise, use const.
1. Create a constant variable named entree and set it to equal to the
string 'Enchiladas'.
2. Just to check that you’ve saved the value of 'Enchiladas' to entree, log the
value of entree to the console.
3. Great, let’s see what happens if you try to reassign a constant variable.
Paste the following code to the bottom of your program.
4. entree = 'Tacos'
This code throws the following error when you run your code:
TypeError: Assignment to constant variable.
After you clear this checkpoint, if you want to see about another quirk
of const in action open the hint!
Hint! Since our program stops running after encountering an error, we need to
delete the line of code from the previous step:
entree = 'Tacos'
Now, let’s test what happens when you try to declare a const variable without a
value. Paste in the following code to your program:
const testing;
You should see a different error this time:
Let’s consider how we can use variables and math operators to calculate new
values and assign them to a variable. Check out the example below:
let w = 4;
w = w + 1;
console.log(w); // Output: 5
In the example above, we created the variable w with the number 4 assigned to
it. The following line, w = w + 1, increases the value of w from 4 to 5.
let w = 4;
w += 1;
console.log(w); // Output: 5
In the second example, we used the += assignment operator to reassign w.
We’re performing the mathematical operation of the first operator + using the
number to the right, then reassigning w to the computed value.
let y = 50;
y *= 2; // Can be written as y = y * 2
console.log(y); // Output: 100
let z = 8;
z /= 2; // Can be written as z = z / 2
console.log(z); // Output: 4
Let’s practice using these mathematical assignment operators!
The increment operator will increase the value of the variable by 1. The
decrement operator will decrease the value of the variable by 1. For example:
5. let a = 10;
a++;
console.log(a); // Output: 11
6. let b = 20;
b--;
console.log(b); // Output: 19
Just like the previous mathematical assignment operators ( +=, -=, *=, /=), the
variable’s value is updated and assigned as the new value of that variable.
The + operator can be used to combine two string values even if those values
are being stored in variables:
String Interpolation
typeof operator
While writing code, it can be useful to keep track of the data types of the
variables in your program. If you need to check the data type of a variable’s
value, you can use the typeof operator.
The typeof operator checks the value to its right and returns, or passes back, a
string of the data type.
Nice work! This lesson introduced you to variables, a powerful concept you
will use in all your future programming endeavors.
Check what happens when you try concatenating strings using variables of
different data types.
console.log(test1);
Find the data type of a variable’s value using the typeof keyword on a
variable.
Use typeof to find the data type of the resulting value when you
concatenate variables containing two different data types.
Kelvin Weather
Deep in his mountain-side meteorology lab, the mad scientist Kelvin has
mastered weather prediction.
If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project
walkthrough video.
Tasks:
1. The forecast today is 293 Kelvin. To start, create a variable named kelvin,
and set it equal to 293.
The value saved to kelvin will stay constant. Choose the variable type with
this in mind.
2. Write a comment above that explains this line of code.
3. Celsius is similar to Kelvin — the only difference is that Celsius
is 273 degrees less than Kelvin.
Let’s convert Kelvin to Celsius by subtracting 273 from the kelvin variable.
Store the result in another variable, named celsius.
4. Write a comment above that explains this line of code.
5. Use this equation to calculate Fahrenheit, then store the answer in a
variable named fahrenheit.
Fahrenheit = Celsius * (9/5) + 32
In the next step we will round the number saved to fahrenheit. Choose the
variable type that allows you to change its value.
6. Write a comment above that explains this line of code.
7. When you convert from Celsius to Fahrenheit, you often get a decimal
number.
Use the .floor() method from the built-in Math object to round down the
Fahrenheit temperature. Save the result to the fahrenheit variable.
8. Write a comment above that explains this line of code.
9. Use console.log and string interpolation to log the temperature
in fahrenheit to the console as follows:
The temperature is TEMPERATURE degrees Fahrenheit.
Use string interpolation to replace TEMPERATURE with the value saved
to fahrenheit.
10. Run your program to see your results! If you want to check your work,
open the hint.
11. By using variables, your program should work for any Kelvin temperature
— just change the value of kelvin and run the program again.
What’s 0 Kelvin in Fahrenheit?
12. Great work! Kelvin can now publish his forecasts in Celsius and
Fahrenheit.
If you’d like extra practice, try this:
Code:
//Forecast today
const kelvin = 273;
//Kelvin - 273 celsius
Celsius = kelvin - 273;
Fahrenheit = Celsius * (9/5) + 32;
//Fahrenheit
fahrenheit = ('The fahrenheit is about ', ' ', Math.floor(Fahrenheit));
Newton = Celsius * (33/100);
console.log(Math.floor(Newton));
console.log(fahrenheit)
let ey = Celsius * (33/100);
ey = Math.floor(ey);
console.log(`The temperature is ${ey} degrees Newton.`);
Dog Years
Dogs mature at a faster rate than human beings. We often say a dog’s age can be
calculated in “dog years” to account for their growth compared to a human of
the same age. In some ways we could say, time moves quickly for dogs — 8 years
in a human’s life equates to 45 years in a dog’s life. How old would you be if you
were a dog?
Here’s how you convert your age from “human years” to “dog years”:
The first two years of a dog’s life count as 10.5 dog years each.
Each year following equates to 4 dog years.
Before you start doing the math in your head, let a computer take care of it! With
your knowledge of math operators and variables, use JavaScript to convert your
human age into dog years.
Tasks:
1. Create a variable named myAge, and set it equal to your age as a number.
Write a comment that explains this line of code.
2. Create a variable named earlyYears and save the value 2 to it. Note, the
value saved to this variable will change.
Write a comment that explains this line of code.
3. Use the multiplication assignment operator to multiply the value saved
to earlyYears by 10.5 and reassign it to earlyYears.
4. Since we already accounted for the first two years, take the myAge variable,
and subtract 2 from it.
Set the result equal to a variable called laterYears. We’ll be changing this
value later.
Write a comment that explains this line of code.
5. Multiply the laterYears variable by 4 to calculate the number of dog years
accounted for by your later years. Use the multiplication assignment
operator to multiply and assign in one step.
Write a comment that explains this line of code.
6. If you’d like to check your work at this point,
print earlyYears and laterYears to the console. Are the values what you
expected?
7. Add earlyYears and laterYears together, and store that in a variable
named myAgeInDogYears.
8. Let’s use a string method next.
Write your name as a string, call its built-in method .toLowerCase(), and
store the result in a variable called myName.
9. Write a console.log statement that displays your name and age in dog
years. Use string interpolation to display the value in the following
sentence:
My name is NAME. I am HUMAN AGE years old in human years which is DOG
AGE years old in dog years.
Replace NAME with myName, HUMAN AGE with myAge, and DOG
AGE with myAgeInDogYears in the sentence above.
10. Great work! You can convert any human age to dog years. Try
changing myAge and see what happens.
If you’d like extra practice, try writing this project without the *= operator.
Code:
You might have seen the term “ES6” or “JavaScript ES6” and wondered what it
actually means. Well wonder no further, because we’re going to dive into what
ES6 is and how it relates to JavaScript!
First, let’s bring in some history. JavaScript was introduced in 1995 by the
company Netscape Communications as a scripting language for web
designers and programmers to interact with web pages. The next year,
Netscape submitted JavaScript to a standards developing organization called
Ecma International to create standards for a scripting language (a type of
programming language). In 1997, Ecma International released ECMA-262
which sets standards for the first version of a scripting language called
ECMAScript, shortened to ES.
Well, despite the release of newer versions, ES6 is actually the biggest update
made to ECMAScript since the first edition released in 1997! Some developers
even refer to ES6 as “Modern JavaScript” because of all the major additions.
There were so many great features added to help JavaScript developers that
include:
Up-to-date browsers now support most of the ES6 features which allow
developers to take advantage of these new additions. ES6 ultimately allows
programmers to save time and write more concise code. Take for example
pre-ES6 syntax for function expressions:
var greeting = function() {
console.log('Hello World!');
};
With ES6 arrow functions, we can transform the expression above into:
However, arrow functions are not just simply syntactical re-writes. As with
other ES6 features, there are other underlying benefits and tradeoffs to
consider. Nonetheless, there has been a strong adoption of ES6 in the
development community. Benefits such as new ES6 syntax, make it easier to
utilize a popular programming paradigm, Object Oriented Programming
(OOP). With this change, developers in other languages who are used to OOP
have a smoother transition into learning and using JavaScript. Another reason
for the popularity of ES6 is correlated with the usage of ES6 in popular
frameworks like React. So, if you want to learn the newest tools and
frameworks, you will have to pick up ES6 along the way.
This being said, we shouldn’t disregard legacy code, i.e. older versions of
JavaScript. In fact, there are still many projects that are built and maintained
with legacy code! If you want the ability and freedom to work on any sort of
JavaScript project, you should familiarize yourself with pre-ES6 and ES6
JavaScript syntax. But don’t worry, we cover both pre-ES6 and ES6 in our
JavaScript course. Check it out to become a rockstar at JavaScript basics and
learn fundamental programming skills!
CONDITIONAL STATEMENTS
comparison operators
logical operators
ternary operators
switch statement
So if you’re ready to learn these concepts go to the next lesson— else, read
over the concepts, observe the diagram, and prepare yourself for this lesson!
If Statement
if (true) {
console.log('This message will print!');
}
// Prints: This message will print!
Notice in the example above, we have an if statement. The if statement is
composed of:
Instructions:
1. Using the let keyword, declare a variable named sale. Assign the
value true to it.
2. Now create an if statement. Provide the if statement a condition
of sale.
Inside the code block of the if statement, console.log() the string 'Time
to buy!'.
3. Notice that the code inside the if statement ran, since 'Time to
buy!' was logged to the console.
Code:
let sale = true;
sale = false;
if (sale) {
console.log('Time to buy!');
}
If...Else Statements
if (false) {
console.log('The code in this block will not run.');
} else {
console.log('But the code in this block will!');
}
// Prints: But the code in this block will!
An else statement must be paired with an if statement, and together they are
referred to as an if...else statement.
The code inside the else statement code block will execute when
the if statement’s condition evaluates to false.
1. Add an else statement to the existing if statement. Inside the code block
of the else statement, console.log() the string 'Time to wait for a sale.'
Code:
let sale = true;
sale = false;
if(sale) {
console.log('Time to buy!');
}
else {
console.log('Time to wait for a sale.')
Comparison Operators
Comparison operators compare the value on the left with the value on the
right. For instance:
We can also use comparison operators on different data types like strings:
All comparison statements evaluate to either true or false and are made up of:
Logical Operators
When we use the && operator, we are checking that two things are true:
If we only care about either condition being true, we can use the || operator:
After you press “Run”, play around with the || operator and the ! operator!
What happens if you negate the value of the entire statement with ! and
switch to || instead of &&?
Code:
let mood = 'sleepy';
mood = 'not sleepy'
let tirednessLevel = 1;
if (mood === 'sleepy' && tirednessLevel > 8) {
console.log('time to sleep');
}
else {
console.log('not bed time yet');
}
let excitement = false;
console.log(!excitement);
Truthy and Falsy
Let’s consider how non-boolean data types, like strings or numbers, are
evaluated when checked inside a condition.
Sometimes, you’ll want to check if a variable exists and you won’t necessarily
want it to equal a specific value — you’ll only check to see if the variable has
been assigned a value.
Here’s an example:
let myVariable = 'I Exist!';
if (myVariable) {
console.log(myVariable)
} else {
console.log('The variable does not exist.')
}
The code block in the if statement will run because myVariable has
a truthy value; even though the value of myVariable is not explicitly the
value true, when used in a boolean or conditional context, it evaluates
to true because it has been assigned a non-falsy value.
0
Empty strings like "" or ''
null which represent when there is no value at all
undefined which represent when a declared variable lacks a value
NaN, or Not a Number
let numberOfApples = 0;
if (numberOfApples){
console.log('Let us eat apples!');
} else {
console.log('No apples left!');
}
1. Change the value of wordCount so that it is truthy. This value should still
be a number.
After you make this change and run your code, 'Great! You've started
your work!' should log to the console.
2. Change the value of favoritePhrase so that it is still a string but falsy.
After you make this change and run your code, 'This string is definitely
empty.' should log to the console.
Code:
let wordCount = 8;
if (wordCount) {
console.log("Great! You've started your work!");
} else {
console.log('Better get to work!');
}
let favoritePhrase = '';
if (favoritePhrase) {
console.log("This string doesn't seem to be empty.");
} else {
console.log('This string is definitely empty.');
}
Say you have a website and want to take a user’s username to make a
personalized greeting. Sometimes, the user does not have an account, making
the username variable falsy. The code below checks if username is defined and
assigns a default string if it is not:
if (username) {
defaultName = username;
} else {
defaultName = 'Stranger';
}
Ternary Operator
if (isNightTime) {
console.log('Turn on the lights!');
} else {
console.log('Turn off the lights!');
}
We can use a ternary operator to perform the same functionality:
Code:
isLocked ?
console.log('You will need a key to open the door.') :
console.log('You will not need a key to open the door.');
isCorrect ?
console.log('Correct!') :
console.log('Incorrect!');
Else If Statements
1. Let’s create a program that keeps track of the way the environment changes
with the seasons. Write a conditional statement to make this happen!
Inside the code block of the else if statement, add a console.log() that
prints the string 'It\'s winter! Everything is covered in snow.' .
Make sure that the structure uses if, else if, and else.
2. Add another else if statement that checks if season is equal to 'fall'.
Inside the code block of the else if statement you just created, add
a console.log() that prints the string 'It\'s fall! Leaves are falling!'
3. Add a final else if statement that checks if season is equal to 'summer'.
Inside the code block of the else if statement you just created, add
a console.log() that prints the string 'It\'s sunny and warm because it\'s
summer!'.
Code:
let season = 'summer';
switch (groceryItem) {
case 'tomato':
console.log('Tomatoes are $0.49');
break;
case 'lime':
console.log('Limes are $1.49');
break;
case 'papaya':
console.log('Papayas are $1.29');
break;
default:
console.log('Invalid item');
break;
}
Inside the block, { ... }, there are multiple cases. The case keyword
checks if the expression matches the specified value that comes after it.
The value following the first case is 'tomato'. If the value
of groceryItem equaled 'tomato', that case‘s console.log() would run.
The value of groceryItem is 'papaya', so the third case runs— Papayas are
$1.29 is logged to the console.
The break keyword tells the computer to exit the block and not execute
any more code or check any other cases inside the code block. Note:
Without break keywords, the first matching case will run, but so will
every subsequent case regardless of whether or not it matches—
including the default. This behavior is different from if/else conditional
statements that execute only one block of code.
Remember to add the break keyword at the end of the default case.
Code:
switch (athleteFinalPosition) {
case 'first place':
console.log('You get the gold medal!');
break
case 'second place':
console.log('You get the silver medal!');
break
case 'third place':
console.log('You get the bronze medal!');
break
default:
console.log('No medal awarded.');
break
}