Show Menu
Cheatography

Javascript Fundamentals Cheat Sheet (DRAFT) by

This one is just for me, sorry.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Introd­uction

Javascript was designed to run only in browsers so every browser uses a Javascript Engine. Node combines C++ and JS so JS can run outside of browsers.
ECMASC­RIPT, Specif­ica­tion, defines JS standards.
The Javascript Console can be found in Chrome > Inspect > Console.
Just like browsers, Node includes the v8 JavaScript engine, so it can read and execute JavaScript scripts

Operator's precedence

The precedence is as follows: multip­lic­ation *, sum +

Bitwise operators

A little less practical.
1 = 00000001, 2 = 00000010
Bitwise are similar to Logical operators, but they operate on the singular bits of a number: each bit/8 is compared.
Bitwise OR
consol­e.log(1 | 2); //3
With OR, each individual bit is compared, if any of them is 1, the result is zero, like:
00000001 //1
 
00000010 //2
 
00000011 //(1 | 2)
Bitwise AND
consol­e.log(1 & 2); //
With AND, each individual bit is compared, if both bits are 1, the result is one, otherwise 0:
00000011 //(1 & 2)

Logical operators with non-bo­oleans

If the operan­d/'­con­dition' is not 'true' or 'false­'(b­oolean) JS will try to interpret it as 'truey' or 'falsey'.
"­Fal­sey­" values:
undefined, null, 0, false, '', "­", NaN
"­Tru­thy­" values:
anything else - Strings, natural numbers

Logical operators

Logical AND (&­&)
Returns 'true' if both operands or conditions are 'true'
true && true => true; true && false => false
Logical OR (||)
Returns 'true' if one of the operan­ds/­con­ditions are 'true'
true || false => true; true || true => true; false || true => true; false || false => false
Logical NOT (!)
Will turn the operand /condition into false if true, true if false
let happy = !sad

Ternary operators

// Ternary operators

// If a costumer has over 10 points they're a GOLD costumer, otherwise they're silver.

let points = 110;
// Condition (produces boolean), if true, set to 'gold', otherwise, 'silver'
let customerType = points > 100 ? 'gold' : 'silver';

console.log(customerType);

There's a better way to shorten this if the condition's result is true or false:
return width > height;
instead of : return width > height ? true : false;
These conditions use booleans to return a value depending on the boolean type.

Operators

Operators are used alongside variables to create expres­sions. With these we can create logic and algori­thms.
In JavaScript we have Arithm­etic, Assigment, Compar­ison, Bitwise and Logical Operators.
Arithmetic
Assignment

Arithmetic Operators

let x = 10;
let y = 3;

console.log(x + y);
console.log(x - y);
console.log(x * y);
console.log(x / y);
console.log(x % y);
console.log(x ** y);

//// Increment and Decrement Operators
// 10
console.log(x);

// 11+1 (operation applied first)
console.log(++x);

// 11+1 (operation applied later)
console.log(x++);
Used for performing calcul­ations, like mathem­atics. Usually variables with numeric values are used (operands) to produce new values (expre­ssion - something that produces a value.
For increment and decrement operators, if applied before the variable, the operation will be performed before the action. If applied after, after the action is executed.

Assignment operators

Comparison operators

// Relational operators
let xx = 1;
console.log(xx > 0);
// true, 1 is bigger than 0
console.log(xx >= 1);
// true, 1 is equal or bigger than 1
console.log(xx < 1);
// false, 1 is no less than 1
console.log(xx <= 1);
// true, 1 is equal or smaller to 1


// Equality operators
console.log(xx === 1);
// true, x is the same value and type as 1
console.log(xx !== 1);
// false,  x is no different to 1
We use them to compare the value of a variable with something else.
The result of an expression that includes a comparison operator is a boolean (true or false).

Equality operators

// Equality operators
console.log(xx === 1);
// true, x is the same value and type as 1
console.log(xx !== 1);
// false,  x is no different to 1

//// Lose equality operators
console.log( xx == y);

//// Strict equality operators
console.log( xx === y);

// true
console.log( '1' == 1 );
// false
console.log( '1' === 1 );
Lose equality operators ensure that two variables share value, Strict equality operators ensure that two variables share value and type. Type such as number, string, etc.

Lose equality will take the first variable's type and convert the second to that type automa­tically when compared.
 

Boiler­plate project

To start off, create an HTML document. Set a <sc­rip­t> tag on the head or body, but best practice is at the end of the <bo­dy> element because the browser will parse the content the DOM first.
// This is a comment.
consol­e.l­og(­"This is a sequence. It logs this message from the consol­e.")
<script src="in­dex.js­"­/>
From the terminal, launch "node index.j­s" to run the JavaScript script
From VSCode, run View > Terminal to run the JavaScript script

Reference types

Objects
A type that holds properties - when multiple properties are related we can fit them inside an Object.
let person = {}
 
Inside an object tehre's value and keys:
{ name: 'Mosh', age: 27 }
 
Objects can also be printed
consol­e.l­og(­per­son);
 
Object properties can be changed. (Dynamic typing, remember?)
person.name = 'Sara'
   
person­['n­ame'] = "­Mar­y"
Arrays
A type used to store other types in a list-like manner. Techni­cally an Object.
let select­edC­olors = [];
   
let select­edC­olors = ['red', 'blue'];
 
Array elements each have an index, in this case: red is 0, blue is 1. To access them
select­edC­olo­rs[0]; // red
 
Because JavaScript is a dynamic language, variables can be set, added, deleted at runtime or any time. And they can be of any type
select­edC­olo­rs[2] = 'yellow';
   
select­edC­olo­rs[3] = 8;
 
Because Arrays are Objects, they have their own inherited properties like indexOf, length...
Functions
A set of statements that perform a task or calculates a value
 
The variable we parse into the function is an 'argum­ent'.
greet(­'Ma­ría');
 
If we don't parse a second variable, it will print undefined.
greet(­"­Jua­na",­las­tName);
 
All functions in JavaScript are objects, so they have properties and methods that we can access using the dot notation (I.e.: Object.keys

JavaScript is a Dynamic Typing language

Primitive variable types

To check a primitive variable type typeof is used:
typeof n !== 'number'

Control flow

- If ... Else
- Switch ... Case
switch­(case) {
 
case 'guest':
 
consol­e.l­og(­'Gu­est');
 
break;
 
case 'moder­ator':
 
consol­e.l­og(­'Mo­der­ator');
 
default:
 
consol­e.l­og(­'Un­kno­wn');
 
}
 
Note 1: If break is not added, the condition doesn't skip and case doesn't work, it just executes the next statement within the first case read.
 
Note 2: An expression is any valid unit of code that resolves to a VALUE. Case is an expres­sion, whether it is 2, 'a', or true. When case matches the variables, wether with a given variable or a set expression like 'true', code will execute, check the condition and if matching, execute and break.
- For ...
'for' includes 3 statem­ents: Initial expres­sion, where a variable is initia­lized, it's usually set like 'i', short for Index. Condition, where we usually compare the value of the Index to something else; the loop will continue unless this condition is false. If we want the loop to go on 5 times, we make it likeso: 1 < 5 and add the next expres­sion. Increm­ent­Exp­ression will be next, so for each time the statements under for are executed it will sum one to the initial expression , check for the condition, and when i is no longer less than 5 it will stop.
 
for (let i = 0; i < 5; i++;)
 
for (let i = 5; i >= 1; i--;)
- While ...
while(­con­dit­ion­){s­tat­ement}
- Do ... while
Do-whiles are always executed once even if the condition is not true.
 
do { sentence } while ( condition )
Infinite loops
You can create them accide­ntally, causing a system break. Check for them on the console
- For ... in
for( let key in person ){}
 
For each iteration the key variable will hold the name of one of the properties of the oobject.
 
To access object's values: person.name, person­["na­me"] or person­[key] if we don't know the properties name beforehand and we need to calculate it at runtime. Here, 'key' inside the brackets is the throwaway name for the proper­ties' value. 'key' on its own will print the property name (name, age...)
- For ... of
for (let color of colors)
 
In this type of loop, the property's value is selected instead of the whole object
 
Objects are not iterable, only Arrays and Maps. To force an Object into an array, use Object.ke­ys(­object) like For ... in or Object.en­tri­es(­object)
Break and continue
They can be used in any kind of loop. 'break;' interrupts the code, 'continue' jumps to the beginning of the loop on its breakpoint and the next execution happens.

Arrays

Adding elements
Even on const declar­ations, arrays can be written onto.
const numbers = [3,4]
But not like
numbers = [3,4,5]
; Because Arrays are Objects, we can use their function proper­ties, like: push (adding to the end), .unshift (pushes existing elements to the right, adds new elements to beginn­ing), .splice (access a specific position and add or remove elements - args: start, amount of numbers to delete, items to add )
numbers.push(5,6)
numbers.unshift(1,2)
numbers.splice(2,0,2.5,'b')
consol­e.l­og(­num­bers) -> 1, 2, 2.5, 'b', 3, 4, 5, 6
Finding elements
- Primit­ives:
numbers = [1,2,3­,4,1]
.indexOf() -> number­s.i­nde­xOf(1) -> 0
Looks for a given input inside the array and, if existing, will return the index number of said array. If not, it will return -1.
.lastI­nde­xOf() -> number­s.l­ast­Ind­exOf(1) -> 4
Looks for a given input inside the array and, if existing, will return the index number of said array. If not, it will return -1.
.inclu­des() -> number­s.i­ncl­udes(3) -> true
Checks for a given element existing in the array. Returns true or false.
'fromI­ndex': A second argument available for all last 3 methods. It starts the search from the given index number.
consol­e.l­og(­app­les.in­dex­Of(1)) //0
console.log(apples.indexOf(1,1)) //4
console.log(apples.lastIndexOf(1)) //4
console.log(apples.lastIndexOf(1,1)) //0
- Reference types:
const courses = [ {id: 1, name: 'a'}, {id: 2, name: 'b'} ]
.find() ->c­our­ses.fi­nd(­fun­cti­on(­cou­rse){ return course.name === 'a' }) -> true
Here because the reference is allocated in another memory slot, '.incl­udes()' can't be used.
Arrow functions
Used to call functions, pre-ex­istant or not
 
const course = course­s.find( course =>{ return course.name === 'a'; })
 
const courseB = course­s.find( course => course.name === 'a');
 
const courseC = course­s.find( (course) =>{ return course.name === 'a'; })
 

Functions

// Functions

// Performing a task:
function greet (name, lastName){
    console.log('Hello ' + name + ' ' + lastName + '!!!')
}

greet("Juana");
let lastName = "la Loca"
greet("Juana",lastName);

// Calculating a value:

function square (Number) {
    return Number * Number;
}

let n = square(2);

console.log(n);
//4

console.log(4/2);

Basic concepts

Variables
Variables are data stored somewhere in memory tempor­arly. When adressed, the variable adress will be accesed by the variable's name. Like a box. The name will describe its content, the contents will be stored in the box.
Declar­ing­/in­iti­alizing variables (as of ES6)
let name = 'raposa';
 
Variables cannot be reserved keywords. They should be concise and meanin­gful, meaning they give us a clue of the contents. They cannot start with a number. They can't contain spaces or hyphens. Camel notation should be used (first­Name)). They're case sensitive. They can be declared in the same line (let name, firstName, lastName;)
Constant variables
They are used when we don't want the values to ever change. If you don't want to redefine constant should be the default.
Types
There are primitive and reference types.
Primitive types:
String, number, boolean, undefined, null

Objects

Declaring an object
const = circle { 
radius:1,
location : {
x: 1,
y : 1
}
draw: functi­on(){ consol­e.l­og(­'draw'}
}
Factory functions
Functions that create objects in order to not repeat code everytime you need a new one
 
function create­Cir­cle­(ra­dius, x, y){  
return {
radius: radius,
location: {
x: x,
y: y
},
draw() {
console.log('draw')
}
};
}
Constr­uctor functions
Written in Pascal Notation. These are also functions to generate objects.
 
function Object() {} is an example of a Constr­uctor function. Whenever we create an object using the Object literal syntax, a call is made into that object­con­str­uctor function
 
The keyword 'this' is used instead of return, it's a reference to the object executing this code.
 
When using the 'new' operator a new empty object is created, then the properties used with 'this' are set dinami­cally, then the object is returned.
 
function Address (street, city, zipcode) { this.s­treet = street; this.city = city; this.z­ipcode = zipcode; this.s­how­Address = function showAd­dress() { for (let key in Address){ consol­e.l­og(key, Addres­s[key]) } } }
Dynamic
Objects in JavaScript are dynamic, which means that once created you can always add new properties or methods, or remove existing ones.
Functions are objects, they have constr­uctors
Circle.co­nst­ructor -> f
Circle.call({},1) and const circle7 = new Circle(1) are the same, .call is a function prebuilt metjod.
{}
stands for the first argument, an empty object - then
this
will reference the new empty object instead of the base object, window. The rest of the arguments will be passed explicitly (like -> this.r­adius = radius; Circle­(ra­diu­s);­cir­cle­7({­},5). Which is to mean that if the 'new' keyword isn't used, 'this' will point to window object.
The apply method can also be used the same as ''call'', but the explicit argument are parsed through an array, like Circle.ap­ply({}, [1,2])
In JavaSc­ript,
radius: radius,
and 'radius,` is the same when defining an object.
camelC­ase­Not­ation, Pascal­Not­ation

Objects

Cloning
for (let key in circle) anothe­r1[key] = circle­[key]
 
Object.as­sig­n(a­not­her2, circle)
 
const another3 = Object.as­sign({ color: 'yellow' }, circle)
 
const another4 = {...ci­rcle}

Garbage collection

In low level languages when creating an object we have to allocate memory for it then deallocate it, not with JS. This is where the Garbage Collector comes in. It finds the variables and constants that are not used and deallocate the memory

Math Object

It's a built-in Object.
The Math namespace object contains static properties and methods for mathem­atical constants and functions.
It's designed for mathem­atical calcul­ations and so are its Properties and Functions (Math.PI, Math.f­loor(), ...)
Math.r­and­om(), Math.r­ound(), Math.m­ax(­1,2,3), Math.m­in(­1,2,3) (...)

String Objects

String is a primitive type, primitive types don't have properties and methods, only objects. But a String Object also exists for JavaSc­ript.
const message = new String­('hi');
It's typeof will be 'object'
However, the internal JavaScript engine will automa­tically convert a String primitive type onto a String Object if we use the dot notation
String.le­ngth, String[3], String.in­clu­des­('my'), String.st­art­sWi­th(­'a'), String.in­dex­Of(­'my')

Strings

\n adds a new line within a String
Template literals
With these, ``, the text formats prints as it's written

Date Object (Built-in)

const now = new Date()
Creates the current date and time when object is created
Has get, set methods