if(condition_1) {
// Statements
} else if(condition_2) {
// Statements
} else(condition_3) {
// Statements
}
switch(variable) {
case label1:
// Statements
break;
case label2:
// Statements
break;
default:
// Statements
}
There are 6 primative types in JavaScript.
string
number
bigint
boolean
undefined
symbol
null
is a special primative like type.
object
is a more complex data structure.
BigInt
is used to hold large integer values.
const a = 123456789012345n;
const b = BigInt(678967896789678678);
Boolean
has two values true
or false
.
null
means "nothing" or "empty".
var num = null;
Number
in html is a 64-bit floating point number.
var x = 3.14;
There are three special numeric values for Numbers: Infinity
, -Infinity
, and Nan
An object
in JavaScript is similar to a class in C++.
var person = {
firstName: "Dalton",
middleName: "Russell",
lastName: "Cole",
fullName: function() {
return `${firstName:} ${middleName:} ${lastName:}`;
}
}; // <- DON'T FORGET THE ;
There are three string quote options in JavaScript:
"Hello"
'Hello'
`Hello`
Double and single quotes behave identically. Backticks allow code to be embedded into a string via ${...}
wrapping.
var str = "Hello World";
var str2 = 'Hola Mundo';
var str3 = `English: ${str}, Spanish: ${str2}`
var str4 = `${1 + 2}`; // '3'
Escape sequences:
'\xA9'
'\u00A9'
or '\uP00A9'
undefined
means "value is not assigned". Variables are undefined
before they are assigned.
var num; // undefined
Arrow functions is a more compact and limited version of a function expression.
var func = (arg1, arg2, ..., argN) => expression
var sum = (a, b) => a + b;
console.log(sum(5, 2);)
If only one argument exists, parentheses can be omitted:
var square = n => n ** 2
When there are no arguments, parentheses are still required.
Multi-line arrow functions require {}
var sum_square = (a, b) => {
let sum = a + b;
return sum ** 2;
}
Javascript allows default parameter values
function func(apple="Apple") {return apple;}
Default parameters can be more complex, for example, a function can be call when a value is not given and the returned value will become the variable.
function func(apple=apples())
Things to keep in mind:
undefined
Function expressions are like lambda functions in other languages.
var sum = function(a, b) {
return a + b;
}
var s = sum(5, 2);
function name(param1, param2, param3) {
// Code
// C++ like return statement
}
The following are equivalent:
var arr = new Array(0, 1, 2, 3);
var arr = Array(0, 1, 2, 3);
var arr = [0, 1, 2, 3]; // If single Number value, bracket syntax is required
Properties:
length
: arr.length
or arr['length']
Methods:
arr.forEach(n => console.log(n));
Map keeps track of key/value pairs in insertion order
let yum = new Map();
// Set key-value pairs
yum.set('apple': 8);
yum.set('banana': 10);
yum.set('chicken': 0);
// Get value
yum.get('apple'); // 8
// Check if value exists
yum.has('apple'); // true
// Delete key-value pair
yum.delete('chicken');
// Check size
yum.size; // 2
for(let [key, value] of yum) {
console.log(key + value);
}
// Delete EVERYTHING
yum.clear();
Collects of values. Keeps track of insertion order. Elements may only occur once.
let mySet = new Set();
// Insert elements
mySet.add(1);
mySet.add('bob');
mySet.add('apple');
// Check if set as an element
mySet.has(1); // true
// Remove element
mySet.delete('bob');
// Size
mySet.size; // 2
for(let v of mySet) {
console.log(v); // 1, 'apple'
}
do {
console.log(i);
} while(i < 10);
for...in
statements iterates over all the enumerable properties of an object.
var fruit = ['apple', 'banana', 'cherry']
for(var i in fruit) {
console.log(i); // '0', '1', '2'
console.log(fruit[i]); // 'apple', 'banana', 'cherry'
}
for(var i; i < 10; i++) {
console.log(i);
}
for...of
loops through iterable objects, similar to python for..in
loops.
var fruit = ['apple', 'banana', 'cherry']
for(var f of fruit) {
console.log(f); // 'apple', 'banana', 'cherry'
}
break_both_loops: for(var i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(i + j >) {
break break_both_loops;
}
}
}
while(i < 10) {
console.log(i);
}
Objects in JavaScript are essentially key-value pairs. These pairs are called properties. Methods are properties that are functions. JavaScript is a prototype-based language. There is no distinction between classes and instances of those classes. This page does a good job of explaining the differences between a class-based (C++) and prototype-based (JavaScript) language.
var person = {
fname: 'Dalton',
lname: 'Cole',
fullName: function() {
return this.fname + ' ' + this.lname;
},
printName: function(func=console.log) {
func(this.fullName());
}
};
console.log(person.fullName()); // Dalton Cole
person.printName(); // Dalton Cole
var person2 = new Object();
person2.fname = 'Dalton';
person2.lname = 'Cole';
// Shallow Copy
var person3 = Object.assign({}, person);
person.fname = 'Colton';
person['lname'] = 'Dal';
person.printName(); // Colton Dal
person2.printName(); // Dalton Cole
function Person(first, last) {
this.firstname = first;
this.lastname = last;
this.fullName = function() {
console.log(this.firstname + ' ' + this.lastname);
}
}
let dalton = new Person('Dalton', 'Cole')
let colton = new Person('Colton', 'Dal')
dalton.fullName()
colton.fullName()
The prototype
property allows you to add new methods to object constructors.
function Person(first, last) {
this.firstName = first;
this.lastName = last;
}
Person.prototype.fullName = function() {
return this.firstName = ' ' + this.lastName;
}
Person.property.fullName2 = () => this.firstName + ' ' + this.lastName; // Won't work as expected
let dalton = new Person('Dalton', 'Cole');
console.log(dalton.fullName()); // "Dalton Cole"
console.log(dalton.fullName2()); // "undefined undefined"
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
** | Exponentation |
/ | Division |
% | Mod |
++ | Increment |
-- | Decrement |
Operator | Description |
---|---|
== | Equal to, does not check type |
=== | Equal value and equal type |
!= | Not equal, does not check type |
!== | Not equal value or not equal type |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
?: | Ternary operator |
Operator | Description |
---|---|
&& | And |
|| | Or |
! | Not |
Operator | Description | Example |
---|---|---|
typeof | Returns the type of a variable |
|
instanceof | Returns true if an object is an instance of an object type |
|
Promises combine asynchronous execution with callbacks! Promises run asynchronously and have optional success and failure function arguments.
async
causes a function to return a promise. For example, the following functions are equivalent:
async function myFunc() {
return 'Daltie';
}
async function myFunc2() {
// return Promise.reject('Bad Daltie!'); // Call error function
return Promise.resolve('Daltie'); // Call success function
}
myFunc().then(value =< console.log(value));
myFunc2().then(
value => console.log(value),
error => console.log(error)
);
// Output
// Daltie
// Daltie
await
is used inside of an async
function.
await
waits for Promise
to be fulfilled and returns the results.
Examples here.
Promises can be chained:
async function myFunc() {
return 'Apples!';
}
let success = function (value) {
console.log(value)
return value;
}
myFunc()
.then(success)
.then(success)
.then(success)
.catch(x => console.log(x))
// Output:
// Apples!
// Apples!
// Apples!
Basic syntax:
let myPromise = new Promise(success_func, failure_func) {
// Do stuff, call func(s)
}
myPromise.then(
function(value) { /* Code if successful */ }.
function(error) { /* Code if some error occurs */ }
);
Both the successful and error function are optional.
Basic example:
// Wait 3 seconds, then call myResolve()
let firstPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve('Yay!'); }, 3000);
});
firstPromise.then(function(value) {
console.log(value);
})
// Second promise. Will finish first
let secondPromise = new Promise(function(success, failure) {
if(true) {
success('Success');
} else {
failure('Failure');
}
});
secondPromise.then(
function(value) {console.log(value);},
function(error) {console.log(error);}
);
// Output:
// Success
// Yay!
Strict mode forces the programmer to code properly (in a matter of speaking). It removes some older parts of JavaScript. Check this for more details.
To enable strict mode, add this to the top of the JavaScript file or function body:
'use strict';
var value = 1;
value = String(value); // "1"
value = Number(value); // 1
value = Boolean(value); // true
const
variables are variables that behave like let
but cannot be reassigned.
let
declares a block-scope variable.
var
variables are function-scoped or globally-scoped variables. A var
variable can be declared anywhere, including after it is used, for example, at the bottom of a function that uses the variable.