JavaScript is specified by the European Association for Standardizing Information and Communication Systems (ECMA 5, 6) and the World Wide Web Consortium (W3C).
v8 is the C++ JavaScript interpreter used by Google Chrome.
Data types are String, Number, Boolean, Null, Undefined, and Object (typeof function() {} yields function).
Falsy values in JavaScript are: false, null, undefined, 0, NaN, "", document.all.
e.g. Boolean(document.all) == false; // Yields true
Simple equality ( == ) attempts to convert operands that are of different types before checking equality (for objects, returns true only if both reference the same object).
Strict equality operator ( === ) always considers operands of different types to be different.
Scope is divided into Global Scope, Local Scope, Function Scope and Block Scope.
Eloquent JavaScript by Marijn Haverbeke.
var myString = '<p>The quick brown fox jumps over the lazy dog. The \
quick brown fox jumps over the lazy dog. The quick brown fox jumps over \
the lazy dog.</p>';
const myString2 = '<p>The quick brown fox jumps over the lazy dog. The quick ' +
'brown fox jumps over the lazy dog. The quick brown fox jumps over the ' +
'lazy dog.</p>';
// Template Literals (ES6)
const myStringFoo = `foo is set to ${foo}. Let's say hello: ${sayHello()}`;
const templateString = (
`<p>How to draw an owl:</p>
<ul>
<li>Draw a circle</li>
<li>Draw the rest of the owl</li>
</ul>`
);
// String Methods
.bold() // Depricated
.fontcolor() // Depricated
.fontsize() // Depricated
.italics() // Depricated
.link() // Depricated
.small() // Depricated
.strike() // Depricated
.sub() // Depricated
.sup() // Depricated
.substr() // Deprecated
.length // (property) Returns the number of characters in string
.substring() Returns new string
.slice() // Faster than substring
const someString = 'The quick brown fox jumps over the lazy dog.';
someString.slice(4, 19) === 'quick brown fox'
someString.slice(-9, -5) === 'lazy'
.replace() // Returns a new string with some or all matches of a pattern replaced
console.log(someString.replace('lazy', 'playful'));
.split() // Returns an array of substrings divided by a pattern - if no pattern is supplied will return an array of one element
.test() // Returns a Boolean after searching for a match of a regular expression and a string
/^foobar/.test(someString);
.charAt(index)
.trim()
.toUpperCase()
.toLowerCase()
.startsWith(searchString, startPos) // Returns a Boolean (ES6)
.endsWith(searchString, length) // Returns a Boolean (ES6)
.repeat(numCopies) // Returns a new string of numCopies copies, concatenated (ES6)
myInt.toString(2); // '111'
const biggestNum = Number.MAX_VALUE;
const smallestNum = Number.MIN_VALUE;
const infiniteNum = Number.POSITIVE_INFINITY;
const negInfiniteNum = Number.NEGATIVE_INFINITY;
const notANum = Number.NaN;
const biggestInt = Number.MAX_SAFE_INTEGER // (2**53 - 1) => 9007199254740991
const smallestInt = Number.MIN_SAFE_INTEGER // -(2**53 - 1) => -9007199254740991
// Convert numeric strings and null to numbers
Number('12.00'); // 12
Number('123e-1'); // 12.3
Number(''); // 0
Number(null); // 0
Number('0x11'); // 17
Number('-Infinity'); // -Infinity
parseInt(string, radix);
parseInt(1111, 2) // 15
parseInt('3.14 is close to Pi'); // 3
Number('3.14 is close to Pi'); // NaN
parseFloat(string);
parseFloat('3.14 is close to Pi'); // 3.14
// Function declaration
function myFunction() {
console.log('myFunction');
}
// Function expression
function someMaths(a, b) {
return [a + b, a * b];
}
// Default function default parameters (ES6)
function exponential2(num1, num2 = 2) {
return num1 ** num2;
}
// Destructuring (ES6)
const [sum, multiple] = someMaths(3, 6);
function printVisit({name, owner, reason = 'a check-up'}) {
console.log(`${owner}\'s pet ${name} is here for ${reason}.`)
}
// Arrow functions (ES6)
const add = (num1, num2) => {
return num1 + num2;
};
const add = (num1, num2) => num1 + num2;
const isEven = num => num % 2 === 0
.length // (property) Sets or returns number of elements in array
.toString() // Returns a string representing the object
.concat() // Merge two or more arrays
.pop() // Remove and return last element
.push() // Add to end and return new array length
.shift() // Remove and return first element
.unShift() // Add to beginning and return new length
.slice(begin, end) // Return new array e.g myArray.slice(-3) returns new array containing last 3 elements
.splice(start, deleteCount, item1, item2, itemN)) // Changes array in place
.sort() // Sorts array in place (ES6)
myNumbers.sort(function(a, b) { return a - b });
myNumbers.sort((a, b) => b - a);
.reverse() // Sorts array in place
.map(callback) // Returns a new array after applying a function to each element (ES6)
const squaredNumbers = myNumbers.map(exponential2);
.forEach(callback) // Applies a function to each array element (ES6)
.filter(callback) // Returns a new array(ES6)
const evenNumbs = myNumbers.filter(num => num % 2 === 0);
.reduce(callback) // Iterates over array while maintaining an accumulation object (ES6)
myNumbers.reduce((total, n) => total + n);
.find(callback) // Returns the value of the first element that satisfies the callback function (ES6)
const found = myNumbers.find(element => element < 2);
.includes() // Returns a Boolean based on whether array includes a value among its elements (ES6)
Array.of() // Returns an array from a variable number of arguments (ES6)
Array.from(object, mapFunction, thisValue) // Returns array from any object with a length property (ES6)
const sources = Array.from(images, image => image.src);
const secureSources = sources.filter(link => link.startsWith('https://'))
if (cookieJar < 1) {
greeting = 'Who stole the cookie?';
} else if (cookieJar > 3) {
greeting = 'The cookies are low!';
} else {
greeting = 'Have a cookie.';
}
// Ternary operator
var driverLicense = (age >= 17) ? 'full license' : 'learner permit';
switch (expression) {
case 'condition1':
myProgram();
break;
case 'condition2': // Falls through
case 'condition3':
myOtherProgram();
break;
default:
myDefaultProgram();
}
// For
for (let i = 0; i < myArray.length - 1; i++) {
numberOfStates++;
}
// For...in - loops over enumerable property names of an object
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// forEach (ES6)
myArray.forEach(state => console.log(`The postal code is ${state}.`));
// For...of - uses object-specific iterator & loops over values generated by that (ES6)
for (const element of myIterable) {
console.log(element);
}
// While
while (condition) {
runAfterCheck();
}
// Do...while
do {
alwaysRunOnce();
}
while (condition);
function myFunction(index) {
if(index < 0) throw new RangeError('index must be positive');
}
try {
myFunction(-1);
}
catch (e) {
console.error(e);
if (e instanceof RangeError) console.log(e.message)
}
finally {
console.log('Try again?');
}
function myDisplayer(someText) {
document.getElementById("demo").innerHTML = someText;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
document.createElement(tagName [, options])
document.querySelector()
document.getElementById()
document.getElementsByTagName()
document.childNodes[0].nodeType
document.childNodes[1].childNodes[0].nodeName
document.childNodes[1].childNodes[1].nodeValue
.appendChild()
.insertBefore()
.removeChild()
.createTextNode()
.hasAttribute()
.getAttribute()
.setAttribute()
document.getElementsByTagName('p')[0].style.backgroundColor = 'green';
.backgroundImage
.borderWidth
.borderColor
.focus()
// Event Properties and Methods
event.which // Returns key or mouse button pressed
event.currentTarget // Returns element whose event listeners triggered the event
event.target // Returns the element that triggered the event
event.preventDefault() // Cancels event if cancelable
event.stopPropagation() // Prevents further propagation of an event during event flow
document.body.onmousemove = function(e) { e = e || window.event; event.preventDefault(); console.log(e.clientX, e.clientY); }
document.body.scrollLeft
document.body.scrollTop
.onclick
.onmouseover
.onmouseout
.ondblclick
.onblur
.onmousedown
.onmouseup
.onchange
.onkeypress
.onfocus
.onselect
window.location.hostname
window.location.href
window.location.pathName
window.location.reload()
window.history.forward()
window.history.back()
window.history.go(-2)
|
|
|
If an object is used as an argument to a function, a reference to the original value is passed. If that argument is mutated the object is also changed.
// Object Literals are basically singletons with variables / methods that are public
// Appropriate for when the object is just a container for data/state
const myContact = {
fName: 'Joe',
lName: 'Doe',
address: '1234 5th Street',
'home phone': '555-555-5555'
}
// Changing Object
delete myContact['home phone'];
myContact.email = 'joedoe@gmail.com';
myContact['emergency contact'] = 'Merle 555-555-1234';
myContact.getInfo = function() {
Object.keys(myContact).forEach(function(key) {
console.log(`${key}: ${myContact[key]}`);
});
}
// Factory Function
function automobile(make, model) {
return {
make: make,
model: model,
tires: 4,
flatten: function() {
console.log(`${this.make} ${this.model} just got a flat tire!);
if (this.wheels > 1) this.wheels--;
},
info: function() {
console.log(`${this.make} ${this.model} with ${this.tires} working wheels.`);
},
};
}
class Mammal {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(name) {
this._name = name;
}
static makeMammal(name) {
return new Mammal(name);
}
getInfo() {
return `${this.name} is a mammal`;
}
}
let monkey = new Mammal('Fred');
monkey.name = 'Mark';
let chipmunk = Mammal.makeMammal('Chipper');
// Inheritance
class Marsupial extends Mammal {
constructor(name, hasPouch) {
super(name);
this._hasPouch = hasPouch;
}
get hasPouch() {
return this._hasPouch;
}
set hasPouch(hasPouch) {
this._hasPouch = hasPouch;
}
// Overriding getInfo() method
getInfo() {
return `${this.name} is a marsupial`;
}
}
let kangaroo = new Marsupial('Paul', true);
// Dynamically inherit class
function getClass(classType) {
if (classType === 1) {
return Mammal;
} else {
return Marsupial
}
}
class Koala extends getClass(2) {
constructor(name) {
super(name);
}
}
let carl - new Koala('Carl');
// Prototyping
Customer.prototype.isCreditable = true;
String.prototype.insertAt = function (index, input) {
return this.slice(0, index) + input + this.slice(index);
}
String.prototype.removeAt = function (startPos, endPos) {
return this.slice(0, startPos) + this.slice(endPos);
}
// Object Methods
Object.create() // Create object with an existing object as prototype
Object.assign(target, ...sources) // Returns target object after copying properties from sources (shallow copy)
delete foo.bar;
Object.defineProperty(object, property, descriptor) // Adding or changing an object property
Object.defineProperties(object, descriptors) // Adding or changing object properties
Object.getOwnPropertyDescriptor(object, property) // Accessing Properties
Object.getOwnPropertyNames(object) // Returns an array of all properties
Object.keys(object) // Returns array of object's property names
Object.values()
Object.entries() // Returns array of object's key, value pairs (same as for...in)
.hasOwnProperty(); // Returns Boolean indicating if the object has the property
Object.preventExtensions(object) // Prevents adding properties to an object
Object.isExtensible(object) // Returns true if properties can be added to an object
Object.seal(object) // Prevents changes of object properties
Object.isSealed(object)
Object.freeze() // Prevents any changes to an object
Object.isFrozen(object)
JSON.parse() // Parses JSON into JS object
JSON.stringify() // Converts object into JSON string
let capital = Symbol('State Capital');
let pennsylvania = {};
pennsylvania[capital] = 'Harrisburg';
console.log(`Capital of PA: ${pennsylvania[capital]}`);
console.log(`Symbol Capital: ${capital.toString()}`);
let employNum = Symbol.for('Employee Number');
let bobSmith = {};
bobSmith[employNum] = 10;
let sallyMarks = {};
sallyMarks[employNum] = 11;
console.log(`Bob: ${bobSmith[employNum]}, Sally: ${sallyMarks[employNum]}`);
let mySet = new Set();
mySet.add(10);
mySet.add('Word');
console.log(`Has 10: ${mySet.has(10)}`);
console.log(`Has \'Word\': ${mySet.has('Word')}`);
console.log(`Set Size: ${mySet.size}`);
mySet.delete(10);
for (let m of mySet) console.log(`Set value: ${m}`);
let myMap = new Map();
myMap.set('key1', 'Hallo World');
myMap.set('key2', '3.14');
console.log(`key1: ${myMap.get('key1')}, key2: ${myMap.get('key2')}`);
console.log(`Map size: ${myMap.size}`);
myMap.forEach((value, key) => console.log(key, value));
setTimeout(function, milliseconds) // Executes a function after specified number of milliseconds
setInterval(function, milliseconds) // Repeats the execution of the function continuously
clearTimeout(timeoutVar) // Uses the variable returned from setTimeout()
let p1 = Promise.resolve('Resolve Me');
p1.then((res) => console.log(`${res}`));
let p2 = new Promise(function(resolve, reject) {
setTimeout(() => resolve('Resolve Me 2'), 2000);
});
p2.then((res) => console.log(`${res}`));
let myNum = 18;
let p3 = new Promise(function(resolve, reject) {
if (myNum === 18) {
resolve('Good number');
} else {
reject('Bad');
}
});
p3.then((val) => console.log(val),
(err) => console.log(err));
let p4 = new Promise((resolve, reject) => {
if (myNum <= 17) {
throw new Error('Can\'t vote');
} else {
resolve('Can vote')
}
});
p4.then((val) => console.log(val))
.catch((err) => console.log(err.message));
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
// var is hoisted
a = 1;
console.log(a);
var a; // 1
// let is not hoisted
b = 2;
console.log(b);
let b; // Error
// Initializations are not hoisted
console.log(c);
var c = 3; // undefined
console.log(d);
const d = 4; // Error
hallo();
var hallo = function() {
console.log('Hi, there.');
} // Error