Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
1459 lines (1024 loc) · 20.5 KB

File metadata and controls

1459 lines (1024 loc) · 20.5 KB
titleJavaScript
date2020-12-24 09:12:25 -0800
iconicon-javascript
backgroundbg-yellow-500
tags
js
web
categories
Programming
introA JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.

Getting started {.cols-3}

Introduction

JavaScript is a lightweight, interpreted programming language.

console.log()

alert('Hello world!');console.log('Hello world!');// => Hello world!

Numbers

letamount=6;letprice=4.99;

Variables

letx=null;letname="Tammy";constfound=false;// => Tammy, false, nullconsole.log(name,found,x);vara;console.log(a);// => undefined

Strings

letsingle='Wheres my bandit hat?';letdouble="Wheres my bandit hat?";// => 21console.log(single.length);

Arithmetic Operators

5+5=10// Addition10-5=5// Subtraction5*10=50// Multiplication10/5=2// Division10%5=0// Modulo

Comments

// This line will denote a comment/* The below configuration must be changed before deployment. */

Assignment Operators

letnumber=100;// Both statements will add 10number=number+10;number+=10;console.log(number);// => 120

String Interpolation

letage=7;// String concatenation'Tommy is '+age+' years old.';// String interpolation`Tommy is ${age} years old.`;

let Keyword

letcount;console.log(count);// => undefinedcount=10;console.log(count);// => 10

const Keyword

constnumberOfColumns=4;// TypeError: Assignment to constant...numberOfColumns=8;

JavaScript Conditionals {.cols-3}

if Statement

constisMailSent=true;if(isMailSent){console.log('Mail sent to recipient');}

Ternary Operator

varx=1;// => trueresult=(x==1) ? true : false;

Operators {.row-span-2}

true||false;// true10>5||10>20;// truefalse||false;// false10>100||10>20;// false

Logical Operator &&

true&&true;// true1>2&&2>1;// falsetrue&&false;// false4===4&&3>1;// true

Comparison Operators

1>3// false3>1// true250>=250// true1===1// true1===2// false1==='1'// false

Logical Operator !

letlateToWork=true;letoppositeValue=!lateToWork;// => falseconsole.log(oppositeValue);

else if

constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small

switch Statement

constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}

JavaScript Functions {.cols-3}

Functions

// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9

Anonymous Functions

// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}

Arrow Functions (ES6) {.row-span-2}

With two arguments

constsum=(param1,param2)=>{returnparam1+param2;};console.log(sum(2,5));// => 7 

With no arguments

constprintHello=()=>{console.log('hello');};printHello();// => hello

With a single argument

constcheckWeight=weight=>{console.log(`Weight : ${weight}`);};checkWeight(25);// => Weight : 25 

Concise arrow functions

constmultiply=(a,b)=>a*b;// => 60 console.log(multiply(2,30));

return Keyword

// With returnfunctionsum(num1,num2){returnnum1+num2;}// The function doesn't output the sumfunctionsum(num1,num2){num1+num2;}

Calling Functions

// Defining the functionfunctionsum(num1,num2){returnnum1+num2;}// Calling the functionsum(2,4);// 6

Function Expressions

constdog=function(){return'Woof!';}

Function Parameters

// The parameter is namefunctionsayHello(name){return`Hello, ${name}!`;}

Function Declaration

functionadd(num1,num2){returnnum1+num2;}

JavaScript Scope {.cols-3}

Scope

functionmyFunction(){varpizzaName="Volvo";// Code here can use pizzaName}// Code here can't use pizzaName

Block Scoped Variables

constisLoggedIn=true;if(isLoggedIn==true){conststatusMessage='Logged in.';}// Uncaught ReferenceError...console.log(statusMessage);

Global Variables

// Variable declared globallyconstcolor='blue';functionprintColor(){console.log(color);}printColor();// => blue

JavaScript Arrays {.cols-3}

Arrays

consta1=[0,1,2,3];// Different data typesconsta2=[1,'chicken',false];

Property .length

constnumbers=[1,2,3,4];numbers.length// 4

Index

// Accessing an array elementconstmyArray=[100,200,300];console.log(myArray[0]);// 100console.log(myArray[1]);// 200

Method .push()

// Adding a single element:constcart=['apple','orange'];cart.push('pear');// Adding multiple elements:constnumbers=[1,2];numbers.push(3,4,5);

Method .pop()

consta=['eggs','flour','chocolate'];constp=a.pop();// 'chocolate'console.log(a);// ['eggs', 'flour']

Mutable

constnames=['Alice','Bob'];names.push('Carl');// ['Alice', 'Bob', 'Carl']

JavaScript Loops {.cols-3}

While Loop

while(condition){// code block to be executed}leti=0;while(i<5){console.log(i);i++;}

Reverse Loop

consta=['banana','cherry'];for(leti=a.length-1;i>=0;i--){console.log(`${i}. ${items[i]}`);}// => 2. cherry// => 1. banana

Do…While Statement

x=0i=0do{x=x+i;console.log(x)i++;}while(i<5);// => 0 1 3 6 10

For Loop

for(leti=0;i<4;i+=1){console.log(i);};// => 0, 1, 2, 3

Looping Through Arrays

for(leti=0;i<array.length;i++){console.log(array[i]);}// => Every item in the array

Break

for(leti=0;i<99;i+=1){if(i>5){break;}console.log(i)}// => 0 1 2 3 4 5

Continue

for(i=0;i<10;i++){if(i===3){continue;}text+="The number is "+i+"<br>";}

Nested

for(leti=0;i<2;i+=1){for(letj=0;j<3;j+=1){console.log(`${i}-${j}`);}}

for...in loop

letdic={brand: 'Apple',model: ''};for(letkeyinmobile){console.log(`${key}: ${mobile[key]}`);}

JavaScript Iterators {.cols-2}

Functions Assigned to Variables

letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14

Callback Functions

constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.

Array Method .reduce()

constarrayOfNumbers=[1,2,3,4];constsum=arrayOfNumbers.reduce((accumulator,curVal)=>{returnaccumulator+curVal;});console.log(sum);// 10

Array Method .map()

consta=['Taylor','Donald','Don','Natasha','Bobby'];constannouncements=a.map(member=>{returnmember+' joined the contest.';})console.log(announcements);

Array Method .forEach()

constnumbers=[28,77,45,99,27];numbers.forEach(number=>{console.log(number);});

Array Method .filter()

constrandomNumbers=[4,11,42,14,39];constfilteredArray=randomNumbers.filter(n=>{returnn>5;});

JavaScript Objects {.cols-2}

Accessing Properties

constapple={color: 'Green',price: {bulk: '$3/kg',smallQty: '$4/kg'}};console.log(apple.color);// => Greenconsole.log(apple.price.bulk);// => $3/kg

Naming Properties

// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}

Non-existent properties

constclassElection={date: 'January 12'};console.log(classElection.place);// undefined

Mutable {.row-span-2}

conststudent={name: 'Sheldon',score: 100,grade: 'A',}console.log(student)// { name: 'Sheldon', score: 100, grade: 'A' }deletestudent.scorestudent.grade='F'console.log(student)// { name: 'Sheldon', grade: 'F' }student={}// TypeError: Assignment to constant variable.

Assignment shorthand syntax

constperson={name: 'Tom',age: '22',};const{name, age}=person;console.log(name);// 'Tom'console.log(age);// '22'

Delete operator

constperson={firstName: "Matilda",age: 27,hobby: "knitting",goal: "learning JavaScript"};deleteperson.hobby;// or delete person[hobby];console.log(person);/*{ firstName: "Matilda" age: 27 goal: "learning JavaScript"}*/

Objects as arguments

constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);

Shorthand object creation

constactivity='Surfing';constbeach={ activity };console.log(beach);// { activity: 'Surfing' }

this Keyword

constcat={name: 'Pipey',age: 8,whatName(){returnthis.name}};console.log(cat.whatName());// => Pipey

Factory functions

// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};

Methods

constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();

Getters and setters

constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';

JavaScript Classes {.cols-3}

Static Methods

classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();

Class

classSong{constructor(){this.title;this.author;}play(){console.log('Song playing!');}}constmySong=newSong();mySong.play();

Class Constructor

classSong{constructor(title,artist){this.title=title;this.artist=artist;}}constmySong=newSong('Bohemian Rhapsody','Queen');console.log(mySong.title);

Class Methods

classSong{play(){console.log('Playing!');}stop(){console.log('Stopping!');}}

extends

// Parent classclassMedia{constructor(info){this.publishDate=info.publishDate;this.name=info.name;}}// Child classclassSongextendsMedia{constructor(songData){super(songData);this.artist=songData.artist;}}constmySong=newSong({artist: 'Queen',name: 'Bohemian Rhapsody',publishDate: 1975});

JavaScript Modules {.cols-2}

Require

varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)

Export

// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27

Export Module

letCourse={};Course.name="Javascript Node.js"module.exports=Course;

Import keyword

// add.jsexportconstadd=(x,y)=>{returnx+y}// main.jsimport{add}from'./add';console.log(add(2,3));// 5

JavaScript Promises {.cols-2}

Promise states {.row-span-2}

constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));

Executor function

constexecutorFn=(resolve,reject)=>{resolve('Resolved!');};constpromise=newPromise(executorFn);

setTimeout()

constloginAlert=()=>{alert('Login');};setTimeout(loginAlert,6000);

.then() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('Result');},200);});promise.then((res)=>{console.log(res);},(err)=>{alert(err);});

.catch() method

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{reject(Error('Promise Rejected Unconditionally.'));},1000);});promise.then((res)=>{console.log(value);});promise.catch((err)=>{alert(err);});

Promise.all()

constpromise1=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(3);},300);});constpromise2=newPromise((resolve,reject)=>{setTimeout(()=>{resolve(2);},200);});Promise.all([promise1,promise2]).then((res)=>{console.log(res[0]);console.log(res[1]);});

Avoiding nested Promise and .then()

constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);

Creating

constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);

Chaining multiple .then()

constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});

JavaScript Async-Await {.cols-2}

Asynchronous

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds

Resolving Promises

letpro1=Promise.resolve(5);letpro2=44;letpro3=newPromise(function(resolve,reject){setTimeout(resolve,100,'foo');});Promise.all([pro1,pro2,pro3]).then(function(values){console.log(values);});// expected => Array [5, 44, "foo"]

Async Await Promises

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

Error Handling

letjson='{ "age": 30 }';// incomplete datatry{letuser=JSON.parse(json);// <-- no errorsalert(user.name);// no name!}catch(e){alert("Invalid JSON data!");}

Aysnc await operator

functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}asyncfunctionmsg(){constmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 seconds

JavaScript Requests {.cols-3}

JSON

const jsonObj = {"name": "Rick",
"id": "11A",
"level": 4};

XMLHttpRequest

constxhr=newXMLHttpRequest();xhr.open('GET','mysite.com/getjson');

GET

constreq=newXMLHttpRequest();req.responseType='json';req.open('GET','/getdata?id=65');req.onload=()=>{console.log(xhr.response);};req.send();

POST {.row-span-2}

constdata={fish: 'Salmon',weight: '1.5 KG',units: 5};constxhr=newXMLHttpRequest();xhr.open('POST','/inventory/add');xhr.responseType='json';xhr.send(JSON.stringify(data));xhr.onload=()=>{console.log(xhr.response);};

fetch api {.row-span-2}

fetch(url,{method: 'POST',headers: {'Content-type': 'application/json','apikey': apiKey},body: data}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message)})}

JSON Formatted

fetch('url-that-returns-JSON').then(response=>response.json()).then(jsonResponse=>{console.log(jsonResponse);});

promise url parameter fetch api

fetch('url').then(response=>{console.log(response);},rejection=>{console.error(rejection.message););

Fetch API Function

fetch('https://api-xxx.com/endpoint',{method: 'POST',body: JSON.stringify({id: "200"})}).then(response=>{if(response.ok){returnresponse.json();}thrownewError('Request failed!');},networkError=>{console.log(networkError.message);}).then(jsonResponse=>{console.log(jsonResponse);})

async await syntax {.col-span-2}

constgetSuggestions=async()=>{constwordQuery=inputField.value;constendpoint=`${url}${queryParams}${wordQuery}`;try{constresponse=awaitfetch(endpoint,{cache: 'no-cache'});if(response.ok){constjsonResponse=awaitresponse.json()}}catch(error){console.log(error)}}