Skip to content

⚡ Short and effective JavaScript & TypeScript snippets for the modern-day developer

License

NotificationsYou must be signed in to change notification settings

matijaoe/modern-javascript-snippets

Repository files navigation

Modern JavaScript Snippets ⚡

Short and effective JavaScript & TypeScript snippets for the modern-day developer.


JavaScriptTypeScript

Features

  • Over 200 carefully crafted snippets
  • Modern JavaScript syntax
  • Modern JavaScript APIs (Intl, URL, Navigator...)
  • Strategically placed tabstops
  • Prefixes created with exact-match in mind
  • Auto-generated documentation

Support

Only JavaScript and TypeScript will be supported. Specific frameworks get their own extensions. No bloat.

Setup

The following is not mandatory, but could provide a nicer experience. Test them out and decide what works best for you.

Look for it in user settings, or edit the settings.json directly:

"editor.formatOnSave": true,

// Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled.
"editor.tabCompletion": "onlySnippets"

Style

Most of the code snippets are without semicolons (;), except for where it allows for better tabstop management. Strings use single quotes (').

It's highly recommended to use these snippets along with Prettier/ESLint to have your code automatically formatted to your preference.

Snippet syntax

Tabstops

  • $1, $2, $3 specify cursor locations, in order in which tabstops will be visited
  • $0 denotes the final cursor position
  • Multiple occurrences of the same tabstop are linked and updated in sync

Placeholders

  • Tabstops with default values → ${1:name}

Choices

  • Tabstops with multiple values → ${1|one,two,three|}.
  • Truncated in documentation, for easier viewing → ${1|one,...|}.

Snippets

Assignments

PrefixNameBody
caconst assignment
const ${1:name} = $2
lalet assignment
let ${1:name} = $2
casconst string assignment
const ${1:name} = '$2'
laslet string assignment
let ${1:name} = '$2'
caaconst array assignment
const ${1:arr} = [$0]
caoconst object assignment
const ${1:obj} = { $0 }
dobobject destructuring
const { $2 } = ${1:obj}$0
dararray destructuring
const [$2] = ${1:arr}$0

Functions

PrefixNameBody
fnfunction
function ${1:fn}($2) {
  $0
}
fnaasync function
async function ${1:fn}($2) {
  $0
}
nfnnamed arrow function
const ${1:fn} = ($2) => {$0}
nfnaasync named arrow function
const ${1:fn} = async ($2) => {$0}
afarrow function
($1) => $0
arrarrow function arrow
=> $0
afaasync arrow function
async ($1) => $0
afbarrow function with body
($1) => {
  $0
}
afbaasync arrow function with body
async ($1) => {
  $0
}
iifeimmediately-invoked function expression
(($1) => {
  $0
})($2)

Flow control

PrefixNameBody
iffif statement
if (${1:true}) {$2}
ifelif/else statement
if (${1:true}) {$2} else {$3}
ifeiif/else-if statement
if (${1:true}) {$2} else if ($3) {$4}
elelse statement
else {
  $0
}
eielse if statement
else if ($1) {$2}
terternary operator
$1 ? $2 : $3
teraternary expression assignment
const ${1:name} = $2 ? $3 : $4
swswitch
switch ($1) {
  case $2 : $3
  default: $0
}
scaseswitch case
case $1 : $2
tctry/catch
try {
  $1
} catch (err) {
  $0
}
tcftry/catch/finally
try {
  $1
} catch (err) {
  $2
} finally {
  $3
}
tftry/finally
try {
  $1
} finally {
  $2
}

Loops

PrefixNameBody
flrfor loop (range)
for (let ${1:i} = 0; ${1:i} < ${2:5}; ${1:i}++) {
  $0
}
rflreverse for loop
for (let ${1:i} = ${2:iter}.length - 1; ${1:i} >= 0; ${1:i}--) {
  $0
}
finfor...in loop
for (let ${1:key} in ${2:array}) {
  $0
}
foffor...of loop
for (let ${1:item} of ${2:items}) {
  $0
}
fofafor await...of loop
for await (let ${1:item} of ${2:items}) {
  $0
}
wlwhile loop
while (${1:true}) {
  $0
}
dwldo while loop
do {
  $0
} while ($1)

Classes

PrefixNameBody
csclass
class $1 {
  $0
}
cseclass extends
class $1 extends ${2:Base} {
  $0
}
cspclass proprety
${1:name} = ${2:value}
cscclass with constructor
class $1 {
  constructor($2) {
    $0
  }
}
csecclass extends with constructor
class $1 extends ${2:Base} {
  constructor($3) {
    $0
  }
}
cstclass constructor
constructor($1) {
  $0
}
getgetter
get ${1:property}() {
  $0
}
setsetter
set ${1:property}(${2:value}) {
  $0
}
gsgetter and setter
get ${1:property}() {
  $0
}
set ${1:property}(${2:value}) {
  $0
}
metmethod
${1:name}($2) {
  $0
}
metaasync method
async ${1:name}($2) {
  $0
}

Array methods

PrefixNameBody
aatarray.at
$1.at(${2:0})
feArray.forEach()
$1.forEach((${2:item}) => {
  $0
})
mapArray.map()
$1.map((${2:item}) => ${3})
fmapArray.flatMap()
$1.flatMap((${2:item}) => ${3})
reduceArray.reduce()
$1.reduce((${2:acc}, ${3:curr}) => {
  $0
}, ${4:initial})
reduceRightArray.reduceRight()
$1.reduceRight((${2:acc}, ${3:curr}) => {
  $0
}, ${4:initial})
filterArray.filter()
$1.filter((${2:item}) => ${3})
findArray.find()
$1.find((${2:item}) => ${3})
findlArray.findLast()
$1.findLast((${2:item}) => ${3})
findiArray.findIndex()
$1.findIndex((${2:item}) => ${3})
findliArray.findLastIndex()
$1.findLastIndex((${2:item}) => ${3})
everyArray.every()
$1.every((${2:item}) => ${3})
someArray.some()
$1.some((${2:item}) => ${3})
reverseArray.reverse()
$1.reverse()
sortArray.sort(
$1.sort((${2:a}, ${3:b}) => $4)
groupArray.group()
$1.group((${2:item}) => $3)
groupMapArray.groupToMap()
$1.groupToMap((${2:item}) => $3)
mapStrArray.map() to string
$1.map(String)
mapNumArray.map() to number
$1.map(Number)
mapBoolArray.map() to boolean
$1.map(Boolean)
filterTruthyArray.filter() truthy
$1.filter(Boolean)
arfrArray.from
Array.from($1)

Modules

PrefixNameBody
imimport from module
import { $2 } from '${1:module}'
imdimport default
import ${2:thing} from '${1:module}'
imaimport as
import ${2:*} as ${3:name} from '${1:module}'
imfimport file
import '$1'
impimport dynamic
import('$0')
impaawait import dynamic
await import('$0')
immimport meta
import.meta.$0
exexport
export $0
exdexport default
export default $0
exfexport from
export { $0 } from '${1:module}'
exaexport all from
export * from '${1:module}'
exoexport object
export const ${1:name} = { $0 }
efnexport function
export function ${1:name}($2) {
  $0
}
edfnexport default function
export default function ${1:name}($2) {
  $0
}
enfnexport named arrow function
export const ${1:name} = ($2) => {$0}

Promises

PrefixNameBody
fetfetch
await fetch($1).then(res => res.json())
fetafetch assignment
const ${1|data,...|} = await fetch($2).then(res => res.json())
nprpromise
new Promise((resolve, reject) => {
  $0
})
prrPromise.resolve
Promise.resolve($1)
prjPromise.reject
Promise.reject($1)
thenpromise then()
$1.then((${2:value}) => $0)
catcpromise catch()
$1.catch((${2:err}) => $0)
thencpromise then().catch()
$1.then((${2:value}) => $3)
  .catch((${4:err}) => $5)
praPromise.all
Promise.all($1)
prasPromise.allSettled
Promise.allSettled($1)
pranPromise.any
Promise.any($1)

Literals, operators, expressions

Grouping them all together for now

PrefixNameBody
arrarray literal
[$0]
obobject literal
{ }
tltemplate literal
`$0`
tletemplate literal operation
${${1:name}}$0
nsnew Set
new Set($1)
nmnew Map
new Map($1)
amarray merge
[...$1]
omobject merge
{ ...$1 }
orOR (||)
|| $0
andAND (&&)
&& $0
ltless than (<)
< $0
lteless than or equal to (<=)
<= $0
gtgreater than (>)
> $0
gtegreater than or equal to (>=)
>= $0
ncnullish coalescing (??)
?? $0
neqstrict non-equality (===)
!== $0
eqstrict equality (===)
=== $0
oralogical OR assignment (||=)
||= $0
ncanullish coalescing assignment (??=)
??= $0
plusaddition
+ $0
minussubtraction
- $0
mulmultiplication
* $0
divdivision
/ $0
modmodulo
% $0
incaddition assignment
+= ${0:1}
subsubtraction assignment
-= ${0:1}
mulamultiplication assignment
*= ${0:1}
divadivision assignment
/= ${0:1}
colcolon
: 

Objects

PrefixNameBody
oeObject.entries
Object.entries($0)
ofeObject.fromEntries
Object.fromEntries($0)
okObject.keys
Object.keys($0)
ovObject.values
Object.values($0)

Utilities

PrefixNameBody
piparse int
parseInt($1, ${2|10,...|})
pfparse float
parseFloat($1)
uniqarray of unique values
[...new Set($0)]
seqsequence of 0..n
[...Array(${1:length}).keys()]
cpcopy to clipboard
navigator.clipboard.writeText($1)
nurlnew URL
new URL($1)
spurl search params
new URLSearchParams($1)
spaurl search params assignment
const ${1:params} = new URLSearchParams($2)
spgget search param
${1:params}.get($2)
spsset search param
${1:params}.set($2, $3)

Returns and exceptions

PrefixNameBody
retreturn
return $0
reoreturn object
return {
  $0
}
reireturn object inline
return ({$0})
terrthrow error
throw new ${1|Error,...|}($0)

Timers

PrefixNameBody
siset interval
setInterval(() => {
  $0
}, ${1:1000})
stset timeout
setTimeout(() => {
  $0
}, ${1:1000})
simset immediate
setImmediate(() => {
  $0
})
prntprocess next tick
process.nextTick(() => {
  $0
})

JSON

PrefixNameBody
jspJSON parse
JSON.parse(${1:json})
jssJSON stringify
JSON.stringify(${1:value})
jssfJSON stringify (formatted)
JSON.stringify(${1:value}, null, 2)

Console

PrefixNameBody
clconsole.log
console.log($0)
ciconsole.info
console.info($1)
cdiconsole.dir
console.dir($1)
ceconsole.error
console.error($1)
cwconsole.warn
console.warn($1)
ctconsole.time
console.time('$1')
$0
console.timeEnd('$1')
ctbconsole.table
console.table($1)
clrconsole.clear
console.clear()
clmconsole.log message
console.log('$0')
cloconsole.log object
console.log({ $0 })
clcconsole.log clipboard
console.log({ $CLIPBOARD })
cllconsole.log (labeled)
console.log('$1 :', $1$2)
cilconsole.info (labeled)
console.info('$1 :', $1$2)
celconsole.error (labeled)
console.error('$1 :', $1$2)
cwlconsole.warn (labeled)
console.warn('$1 :', ${2:$1})

Dates

PrefixNameBody
ndnew Date()
new Date($1)
ndsnew Date() with date string
new Date('${1:2023}-${2:|01,...|}-${3:31}')
nowDate.now()
Date.now()
tlsDate.toLocaleString()
$1.toLocaleString('${2|en-US,...|}'$3)

DOM

PrefixNameBody
qsquery selector
${1:document}.querySelector('$2')
qsaquery selector all
${1:document}.querySelectorAll('$2')
qsaaquery selector all as array
[...${1:document}.querySelectorAll('$2')]
aelevent listener
${1:document}.addEventListener('${2:click}', (e$3) => $0)
qsaequery selector with event listener
${1:document}.querySelector('$2')?.addEventListener('${3:click}', (e$4) => $0)
gidget element by id
${1:document}.getElementById('$2')

Node

PrefixNameBody
reqrequire
require('${1:module}')
rqrrequire assignment
const $1 = require('${1:module}')
mexmodule.exports
module.exports = {$1}

Intl

Internationalization API

PrefixNameBody
infIntl.NumberFormat
new Intl.NumberFormat('${1|en-US,...|}'$3).format($2)
infsIntl.NumberFormat style
new Intl.NumberFormat('${1|en-US,...|}', {
  style: '${3|decimal,...|}',$4
}).format($2)
infcIntl.NumberFormat as currency
new Intl.NumberFormat('${1|en-US,...|}', {
  style: 'currency',
  currency: '${3|USD,...|}',$4
}).format($2)
infpIntl.NumberFormat as percentage
new Intl.NumberFormat('${1|en-US,...|}', {
  style: 'percent',$3
}).format($2)
infuIntl.NumberFormat as unit
new Intl.NumberFormat('${1|en-US,...|}', {
  style: 'unit',
  unit: '${3|acceleration-g-force,...|}',
  unitDisplay: '${4|long,...|}',$0
}).format($2)
idtfIntl.DateTimeFormat
new Intl.DateTimeFormat('${1|en-US,...|}'$3).format($2)
idtfsIntl.DateTimeFormat with style
new Intl.DateTimeFormat ('${1|en-US,...|}', {
  dateStyle: '$3',$0
}).format($2)

Types

PrefixNameBody
aiais array
Array.isArray($0)
toftypeof
typeof $1
tofctypeof check
typeof $1 === '${2|undefined,...|}'
iofinstanceof
$1 instanceof ${0:Class}
isnilis nil
$1 == null
nnilis not nil
$1 != null
isnanis NaN
isNaN($0)
nnanis not NaN
!isNaN($0)

Testing

PrefixNameBody
descdescribe
describe('$1', () => {
  $0
})
contcontext
context('$1', () => {
  $0
})
ittest (synchronous)
it('$1', () => {
  $0
})
itatest (asynchronous)
it('$1', async () => {
  $0
})
itctest (callback)
it('$1', (done) => {
  $0
  done()
})
bfbefore test suite
before(() => {
  $0
})
bfebefore each test
beforeEach(() => {
  $0
})
aftafter test suite
after(() => {
  $0
})
afeafter each test
afterEach(() => {
  $0
})

Globals

PrefixNameBody
wlowindow.location
window.location
wlhwindow.location.href
window.location.href

Misc

PrefixNameBody
us'use strict' statement
'use strict'
prsprocess.server
process.server
prcprocess.client
process.client
envenv variable
process.env.$0
envvenv variable (meta)
import.meta.env.$0

TypeScript

Available only where TypeScript is supported

Declarations

PrefixNameBody
catconst assignment (typed)
const ${1:name}: ${2:string} = $3
latlet assignment (typed)
let ${1:name}: ${2:string} = $3
caatarray assignment (typed)
const ${1:arr}: ${2:string}[] = [$0]
caotobject assignment (typed)
const ${1:obj}: ${2:object} = { $0 }

Types

PrefixNameBody
intinterface
interface ${1:Model} {
  $0
}
inteinterface extends
interface ${1:Model} extends ${2:Base} {
  $0
}
tptype
type ${1:Model} = $2
tputype union
type ${1:Model} = ${2:string} | ${3:number}
tpitype intersection
type ${1:Model} = $2 & $3

DOM

PrefixNameBody
qstquery selector (typed)
${1:document}.querySelector<${2|HTMLElement,...|}>('$3')
qsatquery selector all (typed)
${1:document}.querySelectorAll<${2|HTMLElement,...|}>('$3')
qsaatquery selector all as array (typed)
[...${1:document}.querySelectorAll<${2|HTMLElement,...|}>('$3')]
gidtget element by id (typed)
${1:document}.getElementById<${2|HTMLElement,...|}>('$3')

Running locally

# ensure Deno is installed
# https://deno.land/[email protected]/getting_started/installation

# generate .code-snippets and documentation
npm run generate