Codecademy: Learn JavaScript - Evanto/qna GitHub Wiki
1. Introduction
1.1 Introduction to JS
Print values to the console
console.log("Hello!");
Put any data type inside the parentheses to print it to the console.
The code usually runs as intended without a semicolon, but the best practice is to always include one to ensure your code works as expected in situations when it does need one.
JavaScripts Data Types
- String — any grouping of keyboard characters (letters, spaces, numbers, or symbols) surrounded by single quotes ('Hello') or double quotes ("World!").
- Number — any number, including numbers with decimals: 4, 1516, .002, 23.42.
- Boolean — true or false, with no quotations.
- Null — can only be null, it represents the absence of value.
Examples:
console.log("JavaScript"); // string
console.log(33.7); // number
console.log(true); // boolean
console.log(null); // null
JavaScript Math Operators
JS supports the following math operators:
- Add:
+
- Subtract:
-
- Multiply:
*
- Divide:
/
Examples:
console.log(3 + 4); // 7
console.log(5 - 1); // 4
console.log(4 * 2); // 8
console.log(9 / 3); // 3
Properties of JavaScript Data Types
Data type instances have additional information attached to them (properties), that you can retrieve. The property is calculated when an instance is created?
Example: every string instance has a length property that stores the number of characters in it.
To retrieve a property of an instance, add .propertyname:
console.log('Hello'.length);
JavaScript Built-in Methods
Example:
.toUpperCase()
While data type properties are calculated when an instance is created, instance built-in methods calculate new information on-demand (when called). Built-in methods are called on an instance after a period (like properties), but also have ()
in the end.
Examples:
console.log('Hello'.toUpperCase()); // 'HELLO'
console.log('Hey'.startsWith('H')); // true
console.log(' Remove whitespace '.trim()); // Remove whitespace
A list of built-in string methods can be found in the JavaScript documentation. Developers use it as a reference tool.
JavaScript Libraries
Instance methods, by definition, require that you create an instance before you can use them. Want to call a method without an instance? That's where JavaScript libraries come in - like JavaScript Math Library , that offers methods that you can call without creating an instance.
Let's call the .random()
method from the Math library (returns a random number between 0 and 1):
// returns a random number between 0 and 1:
console.log(Math.random());
Here we call a .random()
method on a library name (Math) and log the result.
To generate a random number between 0 and 50, we can multiply this result by 50:
Math.random() * 50;
The answer will most likely be a decimal. Let's ensure the answer is a whole number, using a JS built-in method Math.floor()
, which rounds a given decimal down to the nearest whole number:
Math.floor(Math.random() * 50);
Here:
Math.random
generates a random number between 0 and 1- We multiply that number by 50, and have a new number between 0 and 50.
Math.floor
rounds it down to the nearest whole number
To log the result:
console.log(Math.floor(Math.random() * 100));
Math.ceil(x)
built-in method returns the smallest integer (whole number) greater than or equal to a decimal number:
console.log(Math.ceil(43.8)); // 44
Number.isInteger(value)
checks if a number is an integer (not a decimal):
console.log(Number.isInteger(2017));
JavaScript Comments
There are two types of code comments in JavaScript:
- A single line comment: put
//
in the beginning of a line:
// The first 5 decimals of pi
- A multi-line comment: put a piece of code between
/*
and*/
:
/*
console.log('All of this code');
console.log('Is commented out');
*/
Review Types and Operators
Let's take one more glance at the concepts we just learned:
- Four essential data types in JavaScript include strings, numbers, booleans, and null.
- Data is printed, or logged, to the console with
console.log()
. - Four built-in mathematical operators include
+
,-
,*
, and/
. - JavaScript associates certain properties with different data types.
- JavaScript has built-in methods for different data types.
- Libraries are collections of methods that can be called without an instance.
- You can write single-line comments with
//
and multi-line comments between/*
and*/
.
1.2 Variables
Introduction to Variables
Here first 3 examples do not print anything to the console (they only assign values to the variables), then we use the last 3 lines to print each of these variables:
// Sets the variable location to the string New York City:
const location = 'New York City';
// Sets the variable latitude to the number 40.7:
let latitude = 40.7;
// Sets the variable inNorthernHemisphere to true:
let inNorthernHemisphere = true;
console.log(location);
console.log(latitude);
console.log(inNorthernHemisphere);
Create a variable: const
Constant variables, as their name implies, are constant — you cannot assign them a different value later.
To declare a constant variable, put const
before its name:
const myName = 'Arya';
console.log(myName);
// Output: Arya
Here:
const
is a JS keyword that creates a new variable with a value that cannot change.myName
is the variable's name (NB: no spaces, camelCased)=
is the assignment operator, which assigns the value'Arya'
to the variablemyName
'Arya'
is the value assigned via=
to the variablemyName
After the variable is declared, we print 'Arya' to the console with: console.log(myName)
.
If you try to assign a new value to a constant variable, you'll get an error:
// throws an error:
const entree = 'Tacos';
entree = 'Tacos';
Create a rewritable variable: let
Let variables can be reassigned:
let meal = 'Enchiladas';
console.log(meal);
meal = 'Tacos';
console.log(meal);
// output: Enchiladas
// output: Tacos
Here the keyword let
is used to create a rewritable variable meal
. On line 3, the meal variable value is changed from 'Enchiladas' to 'Tacos'.
When to use const
vs let
?
Generally, only use const
if the value saved to a variable does not change in your program.
Undefined
JS assigns the undefined
data type to variables that are declared without a value.
If you create a variable, but don't assign it a value, JS will create space for this variable in memory and set it to undefined
. Undefined
is the 5th and final JS primitive data type.
Example:
let whatAmI;
Here we created the variable whatAmI
without any value assigned to it. JS creates the variable and sets it equal to the value undefined
.
let notDefined;
let valueless;
console.log(valueless);
// Output: undefined
Mathematical Assignment Operators
If you need to add 1 to the value saved in a variable x
and save the result in that variable, you can do:
let x = 4;
x = x + 1;
But there is a better way of doing this:
let x = 4;
x += 1; // now x equals 6
This is possible thanks to the JS collection of built-in mathematical assignment operators that make it easy to calculate a new value and assign it to the same variable without writing the variable twice:
let x = 4;
x += 1; // now x equals 6
let y = 4;
y -= 2; // y equals 2
let z = 4;
z *= 2; // z equals 8
let r = 4;
r++; // r equals 5
let t = 4;
t--; // t equals 3
The first 3 operators (+=
, -=
, *=
) execute the given mathematical operation (+
, -
, or *
) between a variable value and the given number, then assign the result to the variable.
The last 2 operators are the increment (++
) and decrement (--
) operators. They increase or decrease a number variable by 1.
String Interpolation 1
You can insert a variable's string content into a string (interpolation) with the +
operator:
variable + 'string'
let myPet = 'armadillo';
console.log('I own a pet ' + myPet + '.');
// Output: 'I own a pet armadillo.'
Here the +
operator is used to combine 3 strings: 'I own a pet'
, the string value saved to myPet
, and .
Example 2:
var favoriteAnimal = 'Cat';
console.log('My favorite animal: ' + favoriteAnimal);
String Interpolation 2
In the newest version of JavaScript (ES6) offers a new way to interpolate (without +
), by doing 2 things:
- Frame your string with backtics (``) instead of quotes ("")
- Wrap your variable like this: ${myVariable}, followed by a sentence. No +s necessary. Example:
let myPet = 'armadillo'
console.log(`I own a pet ${myPet}.`)
// Output: 'I own a pet armadillo.'
Here we wrap the entire string in the backticks (``) and the variable myPet
is inserted using `${}`.
ES6 string interpolation is easier and allows to insert variables directly into your text.
Example 2:
let myName = "Name";
let myCity = "Mos";
console.log(`My name is ${myName}. My favorite city is ${myCity}.`);
Review Variables
Let's review what we learned:
- Variables hold reusable data in a program.
- JS will throw an error if you try to reassign
const
variables. - You can reassign variables that you create with the
let
keyword. - Unset variables store the primitive data type
undefined
. - Mathematical assignment operators make it easy to calculate a new value and assign it to the same variable.
- The
+
operator is used to interpolate (combine) multiple strings. - In JavaScript ES6, backticks (
) and
${}` are used to interpolate values into a string.
2. Control Flow
Introduction to Control Flow
Introduction to Control Flow
Let's see how to use the building blocks of JS to write programs that make decisions.
Control flow statements enable JS programs to make decisions by executing code based on a condition. If a given condition is true, we execute one block of code. If the statement is false, we execute another block of code. For instance, if we were making a game in which the user had to choose which door to enter, we'd need a way for the program to know what to do once the user was in the next room.
In this lesson, we'll learn how to make decisions with JavaScript and how it can control the program's flow.
Example:
let userName = 'A';
let knowsJavaScript = true;
if (knowsJavaScript && userName) {
console.log('Great, ' + userName + '! Get ready to practice your JavaScript!');
} else if (knowsJavaScript) {
console.log('Great! Get ready to practice your JavaScript!');
} else if (userName) {
console.log('Great, ' + userName + '! Get ready to learn something new!');
} else {
console.log('Great! Get ready to learn something new!');
}
// Output: Great, A! Get ready to practice your JavaScript!
if/else Statements
Example:
let needsCoffee = true;
if (needsCoffee === true) {
console.log('Finding coffee');
} else {
console.log('Keep on!');
}
- Code pieces in curly braces
{}
are called blocks (so above we have 2 blocks). If the statement is true, the first block of code will run, otherwise, the 2nd. - Put the condition inside the if's parentheses
()
. - Put pieces of code that can b executed in the
{}
.
Example 2:
let isSoccerFan = true;
if (isSoccerFan === true) {
console.log("Goal!");
} else {
console.log("No goal!");
}
// Output: Goal!
True and False Values 1
In JS, all variables and conditions have a truthy or falsy value. We can check if a variable true or false by writing only its name as the condition:
let variableOne = 'I Exist!';
if (variableOne) {
// This code will run because variableOne contains a truthy value.
} else {
// This code will not run.
}
If we change if (variableOne)
to say if (variableTwo)
, that condition would evaluate to false because we have not created a variable called variableTwo in this program (so variableOne
is truthy and variableTwo
is falsy).
All variables that have been created and set are truthy (and will evaluate to true if they are the condition of a control flow statement) unless they contain one of these 7 falsy values:
false
0
and-0
""
and''
(empty strings)null
undefined
NaN
(Not a Number)document.all
(something you will rarely encounter)
There is an important distinction between a variable's value and its truthiness: variableOne
's value is 'I exist' because that is the data saved to the variable. variableOne
is truthy because it exists and does not contain any of the seven falsy values listed above.
True and False Values 2
We often need to evaluate whether or not an expression is true, and JS has a shorthand notation for this:
let isRaining = true;
if (isRaining) {
console.log('Carry an umbrella!');
} else {
console.log('Enjoy the sun!');
}