0% found this document useful (0 votes)
5 views

Javascript 3

This document is a comprehensive cheat sheet for JavaScript ES6, covering key features such as arrow functions, object property assignment, promises, async/await, and various array and object destructuring techniques. It also includes examples of API calls using XMLHttpRequest, Fetch, Axios, and jQuery AJAX. The content is structured to provide quick references for developers looking to utilize ES6 features effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Javascript 3

This document is a comprehensive cheat sheet for JavaScript ES6, covering key features such as arrow functions, object property assignment, promises, async/await, and various array and object destructuring techniques. It also includes examples of API calls using XMLHttpRequest, Fetch, Axios, and jQuery AJAX. The content is structured to provide quick references for developers looking to utilize ES6 features effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

JavaScript ES6 Cheat Sheet

@codingtute

Arrow function Object property assignment Object function assignment


const sum = (a, b) => a + b const a = 2 const obj = {
console.log(sum(2, 6)) // prints 8 const b = 5 a: 5,
const obj = { a, b } b() {
Default parameters // Before es6: console.log('b')
function print(a = 5) { // obj = { a: a, b: b } }
console.log(a) console.log(obj) }
} // prints { a: 2, b: 5 } obj.b() // prints "b"
print() // prints 5
print(22) // prints 22
Object.assign() Object.entries()
Let Scope const obj1 = { a: 1 } const obj = {
let a = 3 const obj2 = { b: 2 } firstName: 'FirstName',
if (true) { const obj3 = Object.assign({}, lastName: 'LastName',
let a = 5 obj1, obj2) age: 24,
console.log(a) // prints 5 console.log(obj3) country: 'India',
} // { a: 1, b: 2 } };

JS
console.log(a) // prints 3 const entries = Object.entries(obj);
/* returns an array of [key, value]
Promises with finally
Const pairs of the object passed */
promise
// can be assigned only once console.log(entries);
.then((result) => { ··· })
const a = 55 /* prints
.catch((error) => { ··· })
a = 44 // throws an error [
.finally(() => { /* logic
['firstName', 'FirstName'],
independent of success/error */ })
Multiline string ['lastName', 'LastName'],
/* The handler is called when the
console.log(` ['age', 24],
promise is fulflled or rejected.*/
This is a ['country', 'India']
multiline string ]; */
`)

Template strings Spread operator


const name = 'World' const a = {
const message = `Hello ${name}` firstName: "FirstName",
console.log(message)
lastName: "LastName1",
// prints "Hello World"
}
Exponent operator const b = {
const byte = 2 ** 8 ...a,
// Same as: Math.pow(2, 8) lastName: "LastName2",
canSing: true,
Spread operator
const a = [ 1, 2 ] }
const b = [ 3, 4 ] console.log(a)
const c = [ ...a, ...b ] //{firstName: "FirstName", lastName: "LastName1"}
console.log(c) // [1, 2, 3, 4] console.log(b)

String includes()
/* {firstName: "FirstName", lastName: "LastName2",
console.log('apple'.includes('pl')) canSing: true} */
// prints true /* great for modifying objects without side
console.log('apple'.includes('tt')) effects/affecting the original */
// prints false

String startsWith()
console.log('apple'.startsWith('ap')) Destructuring Nested Objects
//prints true const Person = {
console.log('apple'.startsWith('bb')) name: "Harry Potter",
//prints false age: 29,
sex: "male",
String repeat() materialStatus: "single",
console.log('ab'.repeat(3)) address: {
//prints "ababab"
country: "USA",
state: "Nevada",
Destructuring array
city: "Carson City",
let [a, b] = [3, 7];
console.log(a); // 3 pinCode: "500014",
console.log(b); // 7 },
};
Destructuring object const { address : { state, pinCode }, name } = Person;
let obj = { console.log(name, state, pinCode)
a: 55, // Harry Potter Nevada 500014
b: 44 console.log(city) // ReferenceError
};
let { a, b } = obj;
console.log(a); // 55
console.log(b); // 44

codingtute.com
JavaScript ES6 Cheat Sheet
@codingtute

Arrow function Object property assignment Object function assignment


const sum = (a, b) => a + b const a = 2 const obj = {
console.log(sum(2, 6)) // prints 8 const b = 5 a: 5,
const obj = { a, b } b() {
Default parameters // Before es6: console.log('b')
function print(a = 5) { // obj = { a: a, b: b } }
console.log(a) console.log(obj) }
} // prints { a: 2, b: 5 } obj.b() // prints "b"
print() // prints 5
print(22) // prints 22
Object.assign() Object.entries()
Let Scope const obj1 = { a: 1 } const obj = {
let a = 3 const obj2 = { b: 2 } firstName: 'FirstName',
if (true) { const obj3 = Object.assign({}, lastName: 'LastName',
let a = 5 obj1, obj2) age: 24,
console.log(a) // prints 5 console.log(obj3) country: 'India',
} // { a: 1, b: 2 } };

JS
console.log(a) // prints 3 const entries = Object.entries(obj);
/* returns an array of [key, value]
Promises with finally
Const pairs of the object passed */
promise
// can be assigned only once console.log(entries);
.then((result) => { ··· })
const a = 55 /* prints
.catch((error) => { ··· })
a = 44 // throws an error [
.finally(() => { /* logic
['firstName', 'FirstName'],
independent of success/error */ })
Multiline string ['lastName', 'LastName'],
/* The handler is called when the
console.log(` ['age', 24],
promise is fulflled or rejected.*/
This is a ['country', 'India']
multiline string ]; */
`)

Template strings Spread operator


const name = 'World' const a = {
const message = `Hello ${name}` firstName: "FirstName",
console.log(message)
lastName: "LastName1",
// prints "Hello World"
}
Exponent operator const b = {
const byte = 2 ** 8 ...a,
// Same as: Math.pow(2, 8) lastName: "LastName2",
canSing: true,
Spread operator
const a = [ 1, 2 ] }
const b = [ 3, 4 ] console.log(a)
const c = [ ...a, ...b ] //{firstName: "FirstName", lastName: "LastName1"}
console.log(c) // [1, 2, 3, 4] console.log(b)

String includes()
/* {firstName: "FirstName", lastName: "LastName2",
console.log('apple'.includes('pl')) canSing: true} */
// prints true /* great for modifying objects without side
console.log('apple'.includes('tt')) effects/affecting the original */
// prints false

String startsWith()
console.log('apple'.startsWith('ap')) Destructuring Nested Objects
//prints true const Person = {
console.log('apple'.startsWith('bb')) name: "Harry Potter",
//prints false age: 29,
sex: "male",
String repeat() materialStatus: "single",
console.log('ab'.repeat(3)) address: {
//prints "ababab"
country: "USA",
state: "Nevada",
Destructuring array
city: "Carson City",
let [a, b] = [3, 7];
console.log(a); // 3 pinCode: "500014",
console.log(b); // 7 },
};
Destructuring object const { address : { state, pinCode }, name } = Person;
let obj = { console.log(name, state, pinCode)
a: 55, // Harry Potter Nevada 500014
b: 44 console.log(city) // ReferenceError
};
let { a, b } = obj;
console.log(a); // 55
console.log(b); // 44

codingtute.com
JavaScript loops @codingtute

for for...in
for (let i = 0; i < 5; i++) const arr = [3, 5, 7];

JS
{ arr.foo = 'hello';
console.log(i); for (let i in arr) {
} console.log(i);
//Prints 0 1 2 3 4 }
//Prints "0", "1", "2", "foo"
do-while
let iterator = 0;
do { for...of
iterator++; const arr = [3, 5, 7];
console.log(iterator); for (let i of arr) {
} while (iterator < 5); console.log(i);
//Prints 1 2 3 4 5 }
//Prints 3, 5, 7
while
let iterator = 0;
while (iterator < 5) {
iterator++;
console.log(iterator);
}
//Prints 1 2 3 4 5
codingtute.com
JavaScript loops @codingtute

for for...in
for (let i = 0; i < 5; i++) const arr = [3, 5, 7];

JS
{ arr.foo = 'hello';
console.log(i); for (let i in arr) {
} console.log(i);
//Prints 0 1 2 3 4 }
//Prints "0", "1", "2", "foo"
do-while
let iterator = 0;
do { for...of
iterator++; const arr = [3, 5, 7];
console.log(iterator); for (let i of arr) {
} while (iterator < 5); console.log(i);
//Prints 1 2 3 4 5 }
//Prints 3, 5, 7
while
let iterator = 0;
while (iterator < 5) {
iterator++;
console.log(iterator);
}
//Prints 1 2 3 4 5
codingtute.com
JavaScript Arrays Destructuring
@codingtute

Assigning array items to variables

JS
const [a, b, c] = [123, 'second', true];
// a => 123
// b => 'second'
// c => true

Skipping items
const [, b] = [123, 'second', true];
// b => 'second'

Assigning the first values, storing the rest together


const [a, b, ...rest] = [123, 'second', true, false, 42];
// a => 123
// b => 'second'
// rest => [true, false, 42]

Swapping variables
let x = true;
let y = false;
[x, y] = [y, x];
// x => false
// y => true
codingtute.com
JavaScript Arrays Destructuring
@codingtute

Assigning array items to variables

JS
const [a, b, c] = [123, 'second', true];
// a => 123
// b => 'second'
// c => true

Skipping items
const [, b] = [123, 'second', true];
// b => 'second'

Assigning the first values, storing the rest together


const [a, b, ...rest] = [123, 'second', true, false, 42];
// a => 123
// b => 'second'
// rest => [true, false, 42]

Swapping variables
let x = true;
let y = false;
[x, y] = [y, x];
// x => false
// y => true
codingtute.com
JavaScript Async/Await
@codingtute

JS
Async
When we append the keyword “async” to the function, this function
returns the Promise by default on execution. Async keyword provides
extra information to the user of the function:
The function contains some Asynchronous Execution
The returned value will be the Resolved Value for the Promise.

async function f() {


return 1;
}
f().then(alert); // 1

Await
The keyword "await" makes JavaScript wait until that promise settles
and returns its result
The 'await' works only inside async functions

async function f() {


let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves
alert(result); // "done!"
}
f();

codingtute.com
JavaScript Async/Await
@codingtute

JS
Async
When we append the keyword “async” to the function, this function
returns the Promise by default on execution. Async keyword provides
extra information to the user of the function:
The function contains some Asynchronous Execution
The returned value will be the Resolved Value for the Promise.

async function f() {


return 1;
}
f().then(alert); // 1

Await
The keyword "await" makes JavaScript wait until that promise settles
and returns its result
The 'await' works only inside async functions

async function f() {


let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves
alert(result); // "done!"
}
f();

codingtute.com
JavaScript API Calls Cheat Sheet

JS
@codingtute

XML HTTP Request Fetch


All modern browsers support the The Fetch API provides an interface for
XMLHttpRequest object to request data fetching resources (including across the
from a server. network) in an asynchronous manner.
It works on the oldest browsers as well It returns a Promise
as on new ones. It is an object which contains a single value
It was deprecated in ES6 but is still either a Response or an Error that occurred.
widely used. .then() tells the program what to do once
Promise is completed.
var request = new XMLHttpRequest();
request.open('GET',
'https://jsonplaceholder.typicode.com/todos') fetch('https://jsonplaceholder.typicode.com/todos'
request.send(); ).then(response =>{
request.onload = ()=>{ return response.json();
}).then(data =>{
console.log(JSON.parse(request.response)); console.log(data);
} })

Axios jQuery AJAX


It is an open-source library for making It performs asynchronous HTTP requests.
HTTP requests. Uses $.ajax() method to make the requests.
It works on both Browsers and Node js
It can be included in an HTML file by <script
using an external CDN src="https://ajax.googleapis.com/ajax/libs/jquery
It also returns promises like fetch API /3.5.1/jquery.min.js"></script>
$(document).ready(function(){
<script $.ajax({
src="https://cdn.jsdelivr.net/npm/axios/dis url:
t/axios.min.js"></script> "https://jsonplaceholder.typicode.com/todos",
type: "GET",
axios.get("https://jsonplaceholder.typicode success: function(result){
.com/todos") console.log(result);
.then(response =>{ }
console.log(response.data)
}) })
})
codingtute.com
JavaScript API Calls Cheat Sheet

JS
@codingtute

XML HTTP Request Fetch


All modern browsers support the The Fetch API provides an interface for
XMLHttpRequest object to request data fetching resources (including across the
from a server. network) in an asynchronous manner.
It works on the oldest browsers as well It returns a Promise
as on new ones. It is an object which contains a single value
It was deprecated in ES6 but is still either a Response or an Error that occurred.
widely used. .then() tells the program what to do once
Promise is completed.
var request = new XMLHttpRequest();
request.open('GET',
'https://jsonplaceholder.typicode.com/todos') fetch('https://jsonplaceholder.typicode.com/todos'
request.send(); ).then(response =>{
request.onload = ()=>{ return response.json();
}).then(data =>{
console.log(JSON.parse(request.response)); console.log(data);
} })

Axios jQuery AJAX


It is an open-source library for making
HTTP requests. It performs asynchronous HTTP requests.
It works on both Browsers and Node js Uses $.ajax() method to make the requests.
It can be included in an HTML file by
using an external CDN <script
It also returns promises like fetch API src="https://ajax.googleapis.com/ajax/libs/jquery
/3.5.1/jquery.min.js"></script>

<script $(document).ready(function(){
src="https://cdn.jsdelivr.net/npm/axios/dis $.ajax({
t/axios.min.js"></script> url:
"https://jsonplaceholder.typicode.com/todos",
axios.get("https://jsonplaceholder.typicode type: "GET",
success: function(result){
.com/todos") console.log(result);
.then(response =>{
console.log(response.data) }
}) })
})
codingtute.com
JWT Token Generation @codingtute

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and
self-contained way for securely transmitting information between parties as a
JSON object. JSON Web Tokens consist of three parts separated by dots (.),
which are: Header, Payload and, Signature. Therefore, a JWT typically looks
like the following.
xxxxx.yyyyy.zzzzz

Header Payload Signature


{ HMACSHA256(
{
"sub": "1234567890", base64UrlEncode(header) +
"alg": "HS256",
"name": "John Doe", "." +
"typ": "JWT"
"admin": true base64UrlEncode(payload),
}
} secret)

base64UrlEncode base64UrlEncode

eyJhbGciOiJIUz eyJzdWIiOiIxMjM0 SflKxwRJSMeKKF2QT


I1NiIsInR5cCI6 + "." + NTY3ODkwIiwibmFt + "." + 4fwpMeJf36POk6yJV
IkpXVCJ9 ZSI6IkpvaG4gRG9l _adQssw5c
IiwiaWF0IjoxNTE2
MjM5MDIyfQ

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpva
G4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

codingtute.com
JWT Token Generation @codingtute

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and
self-contained way for securely transmitting information between parties as a
JSON object. JSON Web Tokens consist of three parts separated by dots (.),
which are: Header, Payload and, Signature. Therefore, a JWT typically looks
like the following.
xxxxx.yyyyy.zzzzz

Header Payload Signature


{ HMACSHA256(
{
"sub": "1234567890", base64UrlEncode(header) +
"alg": "HS256",
"name": "John Doe", "." +
"typ": "JWT"
"admin": true base64UrlEncode(payload),
}
} secret)

base64UrlEncode base64UrlEncode

eyJhbGciOiJIUz eyJzdWIiOiIxMjM0 SflKxwRJSMeKKF2QT


I1NiIsInR5cCI6 + "." + NTY3ODkwIiwibmFt + "." + 4fwpMeJf36POk6yJV
IkpXVCJ9 ZSI6IkpvaG4gRG9l _adQssw5c
IiwiaWF0IjoxNTE2
MjM5MDIyfQ

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpva
G4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

codingtute.com
ES6 HTML DOM codingtute.com
@codingtute

Document properties of Legacy DOM plugins[]: This property is the synonym


for embeds[].
alinkColor: This property defines the color Eg.document.plugins[0],document.plugins[1]
of the activated links. Referrer: String that contains the URL of
Eg. document.alinkColor the document if it is linked with any.
anchors[]: It is the array of each anchor Eg. document.referrer
object, one for each anchor as it appears in Title: Contents of the <title> tag.
the document. Eg. document.title
Eg. document.anchors[0],document.anchors[1] URL: This property defines the URL.
applets[]: It is the array of applet objects Eg. document.URL
one for each applet as it appears in the vlinkColor: This property defines the
document. color of the visited links(not-activated).
Eg. document.applets[0],document.applets[1] Eg. document.vlinkColor
bgColor: This property defines the
background color of the document. Document methods in Legacy DOM
Eg. document.bgColor
Cookie: This property defines valued clear(): Erases the contents of the
property with special behavior which allows document and returns nothing.
the cookies associated with the document to Eg. document.clear()
be queried to set. close(): Closes the document opened with
Eg. document.cookie open().
Domain: This property defines the domain Eg. document.close()
that a document belongs to it has been used open(): Deletes the existing document

codingtute.com
for security purpose. content and opens a stream to which the
Eg. document.domain new document contents may be written.
embeds[]: Synonym for plugins[]. It is the Returns nothing.
array of objects that represent data Eg. document.open()
embedded in the document write(): Inserts the specified string in
Eg. document.embeds[0],document.embeds[1] the document.
fgColor: This property defines the default Eg. document.write()
text color for the document. writeln(): Same as write() but inserts a
Eg. document.fgColor new line after it is done appending.
forms[]: It is the array of forms object one Eg. document.writeln()
for each, as it appears in the form.
Eg. document.forms[0],document.forms[1]
Document properties in W3C DOM
images[]: It is the array of form objects,
one for each element with <img> tag as it
body: Contents of the tag.
appears in the form.
Eg. document.body
Eg. document.images[0],document.images[1]
defaultView: Represents the window in
lastModified: This property defines date of
which the document is displayed.
the most recent update.
Eg. document.defaultView
Eg. document.lastModified
documentElement: Reference to the tag of
linkColor: This property defines the color
the document.
of unvisited links it is the opposite of the
Eg. document.documentElement
vlinkColor.
implementation: Represents the
Eg. document.linkColor
DOMImplementation object that represents
links[]: Document link array.
the implementation that created this
Eg. document.links[0],document.links[1]
document.
Location: This property holds the URL of the
Eg. document.implementation
document.
Eg. document.location

codingtute.com @codingtute @codingtute @codingtute


codingtute.com
@codingtute

Documents methods in W3C DOM Document properties in IE4 DOM

createAttribute(name_of_attr): Returns a activeElement: Refers to the currently


newly-created Attr node with the specified active input element.
name. Eg. document.activeElement
Eg. document.createAttribute(name_of_attr) all[]: An indexable array of all element
createComment(text): Creates and returns a new objects within the document.
Comment node containing the specified text. Eg. document.all[]
Eg. document.createComment(some_text) charset: Character set of the document.
createDocumentFragment(): Creates and returns Eg. document.charset
an empty DocumentFragment node. children[]: Array that contains the HTML
Eg. document.createDocumentFragment() elements that are the direct children of
createElement(tagname_of_new_ele): creates and the document.
returns a new Element node with a specified Eg. document.children[]
tagname. defaultCharset: Default charset of the
Eg. document.createElement(tagname_of_new_ele) document.
createTextNode(text): Creates and returns a Eg. document.defaultCharset
new Text node that contains the specified expando: When this property is set to
text. false, it prevents client side objects
Eg. document.createTextNode(text) from getting expanded.
getElementById(Id): Returns the value from the Eg. document.expando

codingtute.com
document of the element with the mentioned Id. parentWindow: Document containing window.
Eg. document.getElementById(Id) Eg. document.parentWindow
getElementsByName(name): Returns an array of readyState: Specifies the loading status
nodes with the specified name from the of the document.
document. Eg. document.readyState
Eg. document.getElementsByName(name) uninitialized: Document has not yet
getElementsByTagName(tagname): Returns an started loading.
array of all element nodes in the document Eg. document.uninitialized
that have a specified tagname. loading: Document is loading
Eg. document.getElementsByTagName(tagname) Eg. document.loading
importNode(importedNode, deep): Creates and interactive: Document has loaded
returns a copy of a node from some other sufficiently for the user to interact.
document that is suitable for insertion into Eg. document.interactive
this document. If the deep argument is true, complete: Document has loaded.
it recursively copies the children of the node Eg. document.complete
too.
Eg. document.importNode(importedNode, deep) Document methods in IE4 DOM

elementFromPoint(x,y): Returns the element


located at the specified point.
Eg. document.elementFromPoint(x,y)

codingtute.com @codingtute @codingtute @codingtute

You might also like