JavaScript
Created: 2017 December 1st
Updated: 2020 July 27th
Document Design ModeEdit a web page, set the design mode to on.
document . designMode = 'on'
document . designMode = 'off'
Copy an array
const cats = [ ` Darcy ` , ` Leo ` , ` Boris ` ]
const copyCats = [ ... cats ]
output:
[ "Darcy" , "Leo" , "Boris" ]
Combine two arrays
const cats = [ ` Darcy ` , ` Leo ` , ` Boris ` ]
const people = [ ` Scott ` , ` Islem ` , ` Tom ` , ` George ` ]
const catsAndPeople = [ ... cats , ... people ]
output:
[ "Darcy" , "Leo" , "Boris" , "Scott" , "Islem" , "Tom" , "George" ]
Remove item without mutating
const cats = [ ` Darcy ` , ` Leo ` , ` Boris ` ]
const people = [ ` Scott ` , ` Islem ` , ` Tom ` , ` George ` ]
const catsAndPeople = [ ... cats , ... people ]
const withoutTom = [
... catsAndPeople . slice ( 0 , 5 ) ,
... catsAndPeople . slice ( 6 ) ,
]
Tom is left out of the new array party, sorry Tom
output:
[ "Darcy" , "Leo" , "Boris" , "Scott" , "Islem" , "George" ]
Reverse an arraySo, .reverse()
will mutate the original array so it’s a good idea to
make a new array.
const cats = [ ` Darcy ` , ` Leo ` , ` Boris ` ]
const reverseCatNames = [ ... cats ] . reverse ( )
output:
[ "Darcy" , "Leo" , "Boris" ]
[ "Boris" , "Leo" , "Darcy" ]
Reverse a stringThere’s a .reverse()
method for arrays, so if you split your sting
into an array then you’ll be able to reverse it.
'racecar' . split ( '' ) . reverse ( ) . join ( '' )
output:
New array from existingReturn one new entry for every existing entry: .map()
const originalArray = [ 1 , 2 , 3 ]
const newArray = originalArray . map ( item => item * 2 )
console . log ( newArray )
output:
Return new array filterReturn a new array with only some of the existing entries: .filter()
const originalArray = [ 1 , 9 , 4 , 2 , 42 ]
const newArray = originalArray . filter ( item => item > 5 )
console . log ( newArray )
output:
Return one new thing onlyReturn one new thing only: .reduce()
const originalArray = [
'Alice' ,
'Bob' ,
'Charlie' ,
'Bob' ,
'Bob' ,
'Charlie' ,
]
const numberOfBobs = originalArray . reduce ( ( accumulator , item ) => {
if ( item === 'Bob' ) {
return accumulator + 1
} else {
return accumulator
}
} , 0 )
console . log ( numberOfBobs )
output:
Sum all even numbers from arrayconst arr = [ 0 , 1 , 2 , 3 , 4 , 5 , null , 6 , 9 ]
function addEven ( ) {
return arr . reduce (
( acc , cur ) => ( cur % 2 === 0 ? acc + cur : acc ) ,
0
)
}
addEven ( arr )
Return the first duplicate numberfunction firstDuplicate ( arr ) {
let checkArray = { }
for ( let i = 0 ; i < arr . length ; i ++ ) {
if ( checkArray [ arr [ i ] ] !== undefined )
return arr [ i ]
else checkArray [ arr [ i ] ] = i
}
return - 1
}
Async await with axios and GraphQLconst axios = require ( 'axios' )
axios ( {
url : 'https://spotify-graphql-server.herokuapp.com/graphql' ,
method : 'post' ,
data : {
query : `
{
queryArtists(byName:"Andy C") {
name
id
image
albums {
name
image
}
}
}
` ,
} ,
} ) . then ( result => {
console . log ( result . data )
} )
Remove vowels from stringUse a regular expression:
'replace vowels from string' . replace ( /[aeiou]/gi , '' )
Output:
With JavaScript functions:
'replace vowels from string'
. split ( 'a' )
. join ( '' )
. split ( 'e' )
. join ( '' )
. split ( 'i' )
. join ( '' )
. split ( 'o' )
. join ( '' )
. split ( 'u' )
. join ( '' )
Output:
Closure examplesClosures are the ability for a child function (or inner function) to
access variables from a higher level scope even after the functions
have been called (closed or closed over).
The running of a function within a function:
function greeting ( salutation = '' ) {
const sarcasm = ( ) => {
return [ ... salutation ]
. map ( ( char , i ) => char [ ` to ${ i % 2 ? 'Upper' : 'Lower' } Case ` ] ( ) )
. join ( '' )
}
return function ( name ) {
return ` ${ sarcasm ( ) } ${ name } `
}
}
const sayHiya = greeting ( 'Hiiiya' )
const sayHello = greeting ( 'Hellooo' )
console . log ( sayHiya ( 'scott' ) )
console . log ( sayHello ( 'margret' ) )
Private variables:
function createGame ( gameType ) {
let score = 0
return function increment ( ) {
score ++
return ` Your game of ${ gameType } score is ${ score } . `
}
}
const cribbage = createGame ( 'Cribbage' )
const bridge = createGame ( 'Bridge' )
console . log ( cribbage ( ) )
console . log ( cribbage ( ) )
console . log ( cribbage ( ) )
console . log ( cribbage ( ) )
console . log ( bridge ( ) )
console . log ( bridge ( ) )
console . log ( cribbage ( ) )
Output:
Your game of Cribbage score is 1 .
Your game of Cribbage score is 2 .
Your game of Cribbage score is 3 .
Your game of Cribbage score is 4 .
Your game of Bridge score is 1 .
Your game of Bridge score is 2 .
Your game of Cribbage score is 5 .
Mock and endpointUse a mock endpoint to test against for auth forms.
const wait = n => new Promise ( resolve => setTimeout ( resolve , n ) )
const mockFetch = url =>
wait ( 1000 ) . then ( ( ) => ( {
status : 200 ,
body : {
url : 'http://bbc.co.uk' ,
} ,
} ) )
mockFetch ( ` ${ endpoint } ` ) . then ( response => {
console . log ( '=====================' )
console . log ( response . status )
console . log ( form . userEmail . value )
console . log ( form . userPassword . value )
console . log ( '=====================' )
response . status === 200
? ( location = response . body . url )
: console . error ( ` incorrect ` )
} )
List all image URLs from a web pageNeed to quickly grab a load of images from a page?
let images = document . querySelectorAll ( 'img' )
Array . from ( images ) . map ( i => {
console . log ( i . src )
} )
<div>
cannot appear as a descendant of <p>
If you’re looking for where this is happening, in console you can use:
document . querySelectorAll ( ' p * div ' )
Truncate a stringShorten a string! Define the start and the end of the string you want
to return:
const myString = 'ABCDEFG'
const myTruncatedString = myString . substring ( 0 , 3 )
Current year one linerconst copyrightYear = new Date ( ) . getFullYear ( )
Fizz BuzzClassic FizzBuzz loop.
for ( let i = 1 ; i <= 100 ; ++ i ) {
let output = ''
if ( i % 3 === 0 ) {
output += 'Fizz'
}
if ( i % 5 === 0 ) {
output += 'Buzz'
}
if ( output === '' ) {
output = i
}
console . log ( output )
}
Prototypal InstantiationInstantiation patterns are ways to create something in JavaScript.
var person = function ( name ) {
var obj = Object . create ( objMethods )
obj . name = name
return obj
}
var objMethods = {
sayHello : function ( ) {
console . log ( ` ${ this . name } says hello! ` )
} ,
changeName : function ( newName ) {
var oldName = this . name
this . name = newName
console . log ( ` ${ oldName } has changed their name to ${ this . name } ` )
} ,
}
var person1 = person ( 'Austin' )
person1 . sayHello ( )
person1 . changeName ( 'Derek' )
person1 . sayHello ( )
Output:
Austin says hello !
Austin has changed their name to Derek
Derek says hello !
Change Page Font SizeWant to change the font size on a page? Here you can target the while
document, but could change html
with p
, span
whatever.
document . getElementsByTagName ( 'html' ) [ 0 ] . style [ 'font-size' ] = '10px'