The Complete JavaScript Reference Guide
### How to learn effectively
Learning: The acquisition of skills and the ability to apply them in the future.
What makes an Effective learner?
- They are active listeners.
- They are engaged with the material.
- They are receptive of feedback.
- They are open to difficulty.
Why do active learning techniques feel difficult?
- It feels difficult because you are constantly receiving feedback, and so you are constantly adapting and perfecting the material.
Desirable Difficulty
- The skills we wish to obtain is often a difficult one.
- We want challenging but possible lessons based on current level of skill.
Effective learners space their practice
- Consistent effort > cramming => for durable knowledge
Getting visual feedback in your programs
The first command we’ll learn in JavaScript is console.log
. This command is used to print something onto the screen. As we write our first lines of code, we’ll be using console.log
frequently as a way to visually see the output of our programs. Let’s write our first program:
console.log("hello world");
console.log("how are you?");
Executing the program above would print out the following:
hello world
how are you?
Nothing too ground breaking here, but pay close attention to the exact way we wrote the program. In particular, notice how we lay out the periods, parentheses, and quotation marks. We’ll also terminate lines with semicolons (;).
Depending on how you structure your code, sometimes you’ll be able to omit semicolons at the end of lines. For now, you’ll want to include them just as we do.
Syntax
We refer to the exact arrangement of the symbols, characters, and keywords as syntax. These details matter — your computer will only be able to “understand” proper JavaScript syntax. A programming language is similar to a spoken language. A spoken language like English has grammar rules that we should follow in order to be understood by fellow speakers. In the same way, a programming language like JavaScript has syntax rules that we ought to follow!
As you write your first lines of code in this new language, you may make many syntax errors. Don’t get frustrated! This is normal — all new programmers go through this phase. Every time we recognize an error in our code, we have an opportunity to reinforce your understanding of correct syntax. Adopt a growth mindset and learn from your mistakes.
Additionally, one of the best things about programming is that we can get such immediate feedback from our creations. There is no penalty for making a mistake when programming. Write some code, run the code, read the errors, fix the errors, rinse and repeat!
Code comments
Occasionally we’ll want to leave comments or notes in our code. Commented lines will be ignored by our computer. This means that we can use comments to write plain english or temporarily avoid execution of some JavaScript lines. The proper syntax for writing a comment is to begin the line with double forward slashes (//
):
// let's write another program!!!
console.log("hello world");
// console.log("how are you?");
console.log("goodbye moon");
The program above would only print:
hello world
goodbye moon
Comments are useful when annotating pieces of code to offer an explanation of how the code works. We’ll want to strive to write straightforward code that is self-explanatory when possible, but we can also use comments to add additional clarity. The real art of programming is to write code so elegantly that it is easy to follow.
The Number Data Type
The number data type in JS is used to represent any numerical values, including integers and decimal numbers.
Basic Arithmetic Operators
Operators are the symbols that perform particular operations.
- + (addition)
- - (subtraction)
- asterisk (multiplication)
- / (division)
- % (modulo)
JS evaluates more complex expressions using the general math order of operations aka PEMDAS.
- PEMDAS : Parentheses, Exponents, Multiplication, Division, Modulo, Addition, Subtraction.
- To force a specific order of operation, use the group operator ( ) around a part of the expression.
Modulo : Very useful operation to check divisibility of numbers, check for even & odd, whether a number is prime, and much more! (Discrete Math concept, circular problems can be solved with modulo)
- Whenever you have a smaller number % a larger number, the answer will just be the initial small number.
console.log(7 % 10) // => 7;
The String Data Type
The string data type is a primitive data type that used to represent textual data.
- can be wrapped by either single or double quotation marks, best to choose one and stick with it for consistency.
If your string contains quotation marks inside, can layer single or double quotation marks to allow it to work.
“That’s a great string”; (valid)‘Shakespeare wrote, “To be or not to be”’; (valid)
‘That’s a bad string’; (invalid)
- Alt. way to add other quotes within strings is to use template literals.
`This is a temp’l’ate literal ${function}` // use ${} to invoke functions within. - .length : property that can be appended to data to return the length.
- empty strings have a length of zero.
- indices : indexes of data that begin at 0, can call upon index by using the bracket notation [ ].
console.log(“bootcamp”[0]); // => “b”
console.log(“bootcamp”[10]); // => “undefined”
console.log(“boots”[1 * 2]); // => “o”
console.log(“boots”[“boot”.length-1]); // => “t” - we can pass expressions through the brackets as well since JS always evaluates expressions first.
- The index of the last character of a string is always one less than it’s length.
- indexOf() : method used to find the first index of a given character within a string.
console.log(“bagel”.indexOf(“b”)); // => 0
console.log(“bagel”.indexOf(“z”)); // => -1 - if the character inside the indexOf() search does not exist in the string, the output will be -1.
- the indexOf() search will return the first instanced index of the the char in the string.
- concatenate : word to describe joining strings together into a single string.
The Boolean Data Type
The Boolean data type is the simplest data type since there are only two values: true and false.
- Logical Operators (Boolean Operators) are used to establish logic in our code.
- ! (not) : reverses a Boolean value.
console.log(!true); // => false
console.log(!!false); // => false - Logical Order of Operations : JS will evaluate !, then &&, then ||.
- Short-Circuit Evaluation : Because JS evalutes from left to right, expressions can “short-circuit”. For example if we have true on the left of an || logical comparison, it will stop evaluating and yield true instead of wasting resources on processing the rest of the statement.
console.log(true || !false) // => stops after it sees “true ||”
Comparison Operators
All comparison operators will result in a boolean output.
The relative comparators
- > (greater than)
- < (less than)
- >= (greater than or equal to)
- <= (less than or equal to)
- === (equal to)
- !== (not equal to)
Fun Fact: “a” < “b” is considered valid JS Code because string comparisons are compared lexicographically (meaning dictionary order), so “a” is less than “b” because it appears earlier!
If there is ever a standstill comparison of two string lexicographically (i.e. app vs apple) the comparison will deem the shorter string lesser.
Difference between == and ===
===
Strict Equality, will only return true if the two comparisons are entirely the same.
==
Loose Equality, will return true even if the values are of a different type, due to coercion. (Avoid using this)
Variables
Variables are used to store information to be referenced and manipulated in a program.
- We initialize a variable by using the let keyword and a = single equals sign (assignment operator).
let bootcamp = “App Academy”;
console.log(bootcamp); // “App Academy” - JS variable names can contain any alphanumeric characters, underscores, or dollar signs (cannot being with a number).
- If you do not declare a value for a variable, undefined is automatically set.
let bootcamp;
console.log(bootcamp); // undefined - We can change the value of a previously declared variable (let, not const) by re-assigning it another value.
- let is the updated version of var; there are some differences in terms of hoisting and global/block scope
Assignment Shorthand
let num = 0;
num += 10; // same as num = num + 10
num -= 2; // same as num = num — 2
num /= 4; // same as num = num / 4
num *= 7; // same as num = num * 7
- In general, any nonsensical arithmetic will result in NaN ; usually operations that include undefined.
Functions
A function is a procedure of code that will run when called. Functions are used so that we do not have to rewrite code to do the same thing over and over. (Think of them as ‘subprograms’)
- Function Declaration : Process when we first initially write our function.
- Includes three things:
- Name of the function.
- A list of parameters ()
- The code to execute {}
- Function Calls : We can call upon our function whenever and wherever* we want. (*wherever is only after the initial declaration)
- JS evaluates code top down, left to right.
- When we execute a declared function later on in our program we refer to this as invoking our function.
- Every function in JS returns undefined unless otherwise specified.
- When we hit a return statement in a function we immediately exit the function and return to where we called the function.
- When naming functions in JS always use camelCase and name it something appropriate.
Greate code reads like English and almost explains itself. Think: Elegant, readable, and maintainable!
Parameters and Arguments
- Parameters : Comma seperated variables specified as part of a function’s declaration.
- Arguments : Values passed to the function when it is invoked.
- If the number of arguments passed during a function invocation is different than the number of paramters listed, it will still work.
- However, is there are not enough arguments provided for parameters our function will likely yield Nan.
Including Comments
Comments are important because they help other people understand what is going on in your code or remind you if you forgot something yourself. Keep in mind that they have to be marked properly so the browser won’t try to execute them.
In JavaScript you have two different options:
- Single-line comments — To include a comment that is limited to a single line, precede it with
//
- Multi-line comments — In case you want to write longer comments between several lines, wrap it in
/*
and*/
to avoid it from being executed
Variables in JavaScript
Variables are stand-in values that you can use to perform operations. You should be familiar with them from math class.
var, const, let
You have three different possibilities for declaring a variable in JavaScript, each with their own specialties:
var
— The most common variable. It can be reassigned but only accessed within a function. Variables defined withvar
move to the top when the code is executed.const
— Can not be reassigned and not accessible before they appear within the code.let
— Similar toconst
, thelet
variable can be reassigned but not re-declared.
Data Types
Variables can contain different types of values and data types. You use =
to assign them:
- Numbers —
var age = 23
- Variables —
var x
- Text (strings) —
var a = "init"
- Operations —
var b = 1 + 2 + 3
- True or false statements —
var c = true
- Constant numbers —
const PI = 3.14
- Objects —
var name = {firstName:"John", lastName:"Doe"}
There are more possibilities. Note that variables are case sensitive. That means lastname
and lastName
will be handled as two different variables.
Objects
Objects are certain kinds of variables. They are variables that can have their own values and methods. The latter are actions that you can perform on objects.
var person = {
firstName:”John”,
lastName:”Doe”,
age:20,
nationality:”German”
};
The Next Level: Arrays
Next up in our JavaScript cheat sheet are arrays. Arrays are part of many different programming languages. They are a way of organizing variables and properties into groups. Here’s how to create one in JavaScript:
var fruit = [“Banana”, “Apple”, “Pear”];
Now you have an array called fruit
which contains three items that you can use for future operations.
Array Methods
Once you have created arrays, there are a few things you can do with them:
concat()
— Join several arrays into oneindexOf()
— Returns the first position at which a given element appears in an arrayjoin()
— Combine elements of an array into a single string and return the stringlastIndexOf()
— Gives the last position at which a given element appears in an arraypop()
— Removes the last element of an arraypush()
— Add a new element at the endreverse()
— Sort elements in a descending ordershift()
— Remove the first element of an arrayslice()
— Pulls a copy of a portion of an array into a new arraysort()
— Sorts elements alphabeticallysplice()
— Adds elements in a specified way and positiontoString()
— Converts elements to stringsunshift()
—Adds a new element to the beginningvalueOf()
— Returns the primitive value of the specified object
Operators
If you have variables, you can use them to perform different kinds of operations. To do so, you need operators.
Basic Operators
+
— Addition-
— Subtraction*
— Multiplication/
— Division(...)
— Grouping operator, operations within brackets are executed earlier than those outside%
— Modulus (remainder )++
— Increment numbers--
— Decrement numbers
Comparison Operators
==
— Equal to===
— Equal value and equal type!=
— Not equal!==
— Not equal value or not equal type>
— Greater than<
— Less than>=
— Greater than or equal to<=
— Less than or equal to?
— Ternary operator
Logical Operators
&&
— Logical and||
— Logical or!
— Logical not
Bitwise Operators
&
— AND statement|
— OR statement~
— NOT^
— XOR<<
— Left shift>>
— Right shift>>>
— Zero fill right shift
Functions
JavaScript functions are blocks of code that perform a certain task. A basic function looks like this:
function name(parameter1, parameter2, parameter3) {
// what the function does
}
As you can see, it consists of the function
keyword plus a name. The function’s parameters are in the brackets and you have curly brackets around what the function performs. You can create your own, but to make your life easier – there are also a number of default functions.
Outputting Data
A common application for functions is the output of data. For the output, you have the following options:
alert()
— Output data in an alert box in the browser windowconfirm()
— Opens up a yes/no dialog and returns true/false depending on user clickconsole.log()
— Writes information to the browser console, good for debugging purposesdocument.write()
— Write directly to the HTML documentprompt()
— Creates a dialogue for user input
Global Functions
Global functions are functions built into every browser capable of running JavaScript.
decodeURI()
— Decodes a Uniform Resource Identifier (URI) created byencodeURI
or similardecodeURIComponent()
— Decodes a URI componentencodeURI()
— Encodes a URI into UTF-8encodeURIComponent()
— Same but for URI componentseval()
— Evaluates JavaScript code represented as a stringisFinite()
— Determines whether a passed value is a finite numberisNaN()
— Determines whether a value is NaN or notNumber()
—- Returns a number converted from its argumentparseFloat()
— Parses an argument and returns a floating-point numberparseInt()
— Parses its argument and returns an integer
JavaScript Loops
Loops are part of most programming languages. They allow you to execute blocks of code desired number of times with different values:
for (before loop; condition for loop; execute after loop) {
// what to do during the loop
}
You have several parameters to create loops:
for
— The most common way to create a loop in JavaScriptwhile
— Sets up conditions under which a loop executesdo while
— Similar to thewhile
loop but it executes at least once and performs a check at the end to see if the condition is met to execute againbreak
—Used to stop and exit the cycle at certain conditionscontinue
— Skip parts of the cycle if certain conditions are met
If — Else Statements
These types of statements are easy to understand. Using them, you can set conditions for when your code is executed. If certain conditions apply, something is done, if not — something else is executed.
if (condition) {
// what to do if condition is met
} else {
// what to do if condition is not met
}
A similar concept to if else
is the switch
statement. However, using the switch you select one of several code blocks to execute.
Strings
Strings are what JavaScript calls to text that does not perform a function but can appear on the screen.
var person = “John Doe”;
In this case, John Doe
is the string.
Escape Characters
In JavaScript, strings are marked with single or double-quotes. If you want to use quotation marks in a string, you need to use special characters:
\'
— Single quote\"
— Double quote
Aside from that you also have additional escape characters:
\\
— Backslash\b
— Backspace\f
— Form feed\n
— New line\r
— Carriage return\t
— Horizontal tabulator\v
— Vertical tabulator
String Methods
There are many different ways to work with strings:
charAt()
— Returns a character at a specified position inside a stringcharCodeAt()
— Gives you the Unicode of a character at that positionconcat()
— Concatenates (joins) two or more strings into onefromCharCode()
— Returns a string created from the specified sequence of UTF-16 code unitsindexOf()
— Provides the position of the first occurrence of a specified text within a stringlastIndexOf()
— Same asindexOf()
but with the last occurrence, searching backwardmatch()
— Retrieves the matches of a string against a search patternreplace()
— Find and replace specified text in a stringsearch()
— Executes a search for a matching text and returns its positionslice()
— Extracts a section of a string and returns it as a new stringsplit()
— Splits a string object into an array of strings at a specified positionsubstr()
— Similar toslice()
but extracts a substring depending on a specified number of characterssubstring()
— Also similar toslice()
but can’t accept negative indicestoLowerCase()
— Convert strings to lower casetoUpperCase()
— Convert strings to upper casevalueOf()
— Returns the primitive value (that has no properties or methods) of a string object
Regular Expression Syntax
Regular expressions are search patterns used to match character combinations in strings. The search pattern can be used for text search and text to replace operations.
Pattern Modifiers
e
— Evaluate replacementi
— Perform case-insensitive matchingg
— Perform global matchingm
— Perform multiple line matchings
— Treat strings as a single linex
— Allow comments and whitespace in the patternU
— Ungreedy pattern
Brackets
[abc]
— Find any of the characters between the brackets[^abc]
— Find any character which is not in the brackets[0-9]
— Used to find any digit from 0 to 9[A-z]
— Find any character from uppercase A to lowercase z(a|b|c)
— Find any of the alternatives separated with|
Metacharacters
.
— Find a single character, except newline or line terminator\w
— Word character\W
— Non-word character\d
— A digit\D
— A non-digit character\s
— Whitespace character\S
— Non-whitespace character\b
— Find a match at the beginning/end of a word\B
— A match not at the beginning/end of a word\0
— NUL character\n
— A new line character\f
— Form feed character\r
— Carriage return character\t
— Tab character\v
— Vertical tab character\xxx
— The character specified by an octal number xxx\xdd
— Character specified by a hexadecimal number dd\uxxxx
— The Unicode character specified by a hexadecimal number XXXX
Quantifiers
n+
— Matches any string that contains at least one nn*
— Any string that contains zero or more occurrences of nn?
— A string that contains zero or one occurrence of nn{X}
— String that contains a sequence of X n’sn{X,Y}
— Strings that contain a sequence of X to Y n’sn{X,}
— Matches any string that contains a sequence of at least X n’sn$
— Any string with n at the end of it^n
— String with n at the beginning of it?=n
— Any string that is followed by a specific string n?!n
— String that is not followed by a specific string ni
Numbers and Math
In JavaScript, you can also work with numbers, constants and perform mathematical functions.
Number Properties
MAX_VALUE
— The maximum numeric value representable in JavaScriptMIN_VALUE
— Smallest positive numeric value representable in JavaScriptNaN
— The “Not-a-Number” valueNEGATIVE_INFINITY
— The negative Infinity valuePOSITIVE_INFINITY
— Positive Infinity value
Number Methods
toExponential()
— Returns the string with a rounded number written as exponential notationtoFixed()
— Returns the string of a number with a specified number of decimalstoPrecision()
— String of a number written with a specified lengthtoString()
— Returns a number as a stringvalueOf()
— Returns a number as a number
Math Properties
E
— Euler’s numberLN2
— The natural logarithm of 2LN10
— Natural logarithm of 10LOG2E
— Base 2 logarithm of ELOG10E
— Base 10 logarithm of EPI
— The number PISQRT1_2
— Square root of 1/2SQRT2
— The square root of 2
Math Methods
abs(x)
— Returns the absolute (positive) value of xacos(x)
— The arccosine of x, in radiansasin(x)
— Arcsine of x, in radiansatan(x)
— The arctangent of x as a numeric valueatan2(y,x)
— Arctangent of the quotient of its argumentsceil(x)
— Value of x rounded up to its nearest integercos(x)
— The cosine of x (x is in radians)exp(x)
— Value of Exfloor(x)
— The value of x rounded down to its nearest integerlog(x)
— The natural logarithm (base E) of xmax(x,y,z,...,n)
— Returns the number with the highest valuemin(x,y,z,...,n)
— Same for the number with the lowest valuepow(x,y)
— X to the power of yrandom()
— Returns a random number between 0 and 1round(x)
— The value of x rounded to its nearest integersin(x)
— The sine of x (x is in radians)sqrt(x)
— Square root of xtan(x)
— The tangent of an angle