JavaScript In Depth Part 1

JavaScript In Depth Part 1

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 with var 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 to const, the let 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 one
  • indexOf() — Returns the first position at which a given element appears in an array
  • join() — Combine elements of an array into a single string and return the string
  • lastIndexOf() — Gives the last position at which a given element appears in an array
  • pop() — Removes the last element of an array
  • push() — Add a new element at the end
  • reverse() — Sort elements in a descending order
  • shift() — Remove the first element of an array
  • slice() — Pulls a copy of a portion of an array into a new array
  • sort() — Sorts elements alphabetically
  • splice() — Adds elements in a specified way and position
  • toString() — Converts elements to strings
  • unshift() —Adds a new element to the beginning
  • valueOf() — 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 window
  • confirm() — Opens up a yes/no dialog and returns true/false depending on user click
  • console.log() — Writes information to the browser console, good for debugging purposes
  • document.write() — Write directly to the HTML document
  • prompt() — 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 by encodeURI or similar
  • decodeURIComponent() — Decodes a URI component
  • encodeURI() — Encodes a URI into UTF-8
  • encodeURIComponent() — Same but for URI components
  • eval() — Evaluates JavaScript code represented as a string
  • isFinite() — Determines whether a passed value is a finite number
  • isNaN() — Determines whether a value is NaN or not
  • Number() —- Returns a number converted from its argument
  • parseFloat() — Parses an argument and returns a floating-point number
  • parseInt() — 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 JavaScript
  • while — Sets up conditions under which a loop executes
  • do while — Similar to the while loop but it executes at least once and performs a check at the end to see if the condition is met to execute again
  • break —Used to stop and exit the cycle at certain conditions
  • continue — 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 string
  • charCodeAt() — Gives you the Unicode of a character at that position
  • concat() — Concatenates (joins) two or more strings into one
  • fromCharCode() — Returns a string created from the specified sequence of UTF-16 code units
  • indexOf() — Provides the position of the first occurrence of a specified text within a string
  • lastIndexOf() — Same as indexOf() but with the last occurrence, searching backward
  • match() — Retrieves the matches of a string against a search pattern
  • replace() — Find and replace specified text in a string
  • search() — Executes a search for a matching text and returns its position
  • slice() — Extracts a section of a string and returns it as a new string
  • split() — Splits a string object into an array of strings at a specified position
  • substr() — Similar to slice() but extracts a substring depending on a specified number of characters
  • substring() — Also similar to slice() but can’t accept negative indices
  • toLowerCase() — Convert strings to lower case
  • toUpperCase() — Convert strings to upper case
  • valueOf() — 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 replacement
  • i — Perform case-insensitive matching
  • g — Perform global matching
  • m — Perform multiple line matching
  • s — Treat strings as a single line
  • x — Allow comments and whitespace in the pattern
  • U — 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 n
  • n* — Any string that contains zero or more occurrences of n
  • n? — A string that contains zero or one occurrence of n
  • n{X} — String that contains a sequence of X n’s
  • n{X,Y} — Strings that contain a sequence of X to Y n’s
  • n{X,} — Matches any string that contains a sequence of at least X n’s
  • n$ — 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 JavaScript
  • MIN_VALUE — Smallest positive numeric value representable in JavaScript
  • NaN — The “Not-a-Number” value
  • NEGATIVE_INFINITY — The negative Infinity value
  • POSITIVE_INFINITY — Positive Infinity value

Number Methods

  • toExponential() — Returns the string with a rounded number written as exponential notation
  • toFixed() — Returns the string of a number with a specified number of decimals
  • toPrecision() — String of a number written with a specified length
  • toString() — Returns a number as a string
  • valueOf() — Returns a number as a number

Math Properties

  • E — Euler’s number
  • LN2 — The natural logarithm of 2
  • LN10 — Natural logarithm of 10
  • LOG2E — Base 2 logarithm of E
  • LOG10E — Base 10 logarithm of E
  • PI — The number PI
  • SQRT1_2 — Square root of 1/2
  • SQRT2 — The square root of 2

Math Methods

  • abs(x) — Returns the absolute (positive) value of x
  • acos(x) — The arccosine of x, in radians
  • asin(x) — Arcsine of x, in radians
  • atan(x) — The arctangent of x as a numeric value
  • atan2(y,x) — Arctangent of the quotient of its arguments
  • ceil(x) — Value of x rounded up to its nearest integer
  • cos(x) — The cosine of x (x is in radians)
  • exp(x) — Value of Ex
  • floor(x) — The value of x rounded down to its nearest integer
  • log(x) — The natural logarithm (base E) of x
  • max(x,y,z,...,n) — Returns the number with the highest value
  • min(x,y,z,...,n) — Same for the number with the lowest value
  • pow(x,y) — X to the power of y
  • random() — Returns a random number between 0 and 1
  • round(x) — The value of x rounded to its nearest integer
  • sin(x) — The sine of x (x is in radians)
  • sqrt(x) — Square root of x
  • tan(x) — The tangent of an angle