Skip to content

matijaoe/modern-javascript-snippets

Repository files navigation

Modern JavaScript Snippets ⚡

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


🚧 Still a work in progress. Some snippets may be changed or removed, and more will be added.

Features

  • Contains over 180 snippets
  • Modern JavaScript syntax
  • Strategically placed tabstops
  • Auto-generated documentation
  • ...

JavaScript TypeScript

Support

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

Supported file extensions:

  • .js
  • .ts
  • .jsx
  • .tsx

Setup

The following is not mandatory, but could provide a nicer experience.

Search for editor.tabCompletion in user settings, or edit the settings.json directly:

// 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.

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

Snippet syntax

Tabstops

  • With tabstops you can make the editor cursor move inside a snippet
  • $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

  • Placeholders are tabstops with values, such as ${1:name}
  • Placeholder text will be inserted and selected such that it can be easily changed
  • Can be nested, like ${1:another ${2:placeholder}}

Snippets

Assignments

Prefix Name Body
c const
const $0
l let
let $0
ca const assignment
const $1 = $2;
la let assignment
let $1 = $2;
cas const string assignment
const $1 = '$2';
car const array assignment
const $1 = [$0]
cao const object assignment
const $1 = { $0 }
dob object destructuring
const { $0 } = ${1:object}
dar array destructuring
const [$0] = ${1:array}

Flow control

Prefix Name Body
if if statement
if ($1) {
  $2
}
ifel if/else statement
if ($1) {
  $2
} else {
  $3
}
ifei if/else-if statement
if ($1) {
  $2
} else if ($3) {
  $4
}
el else statement
else {
  $3
}
ei else if statement
else if ($1) {
  $2
}
ter ternary operator
$1 ? $2 : $3
tera ternary expression assignment
const ${1:name} = $2 ? $3 : $4
sw switch
switch ($1) {
  case $2 : $3
  default: $0
}
cas case
case ${1:value}:
  $0
  break;
tc try/catch
try {
  $1
} catch (error) {
  $0
}
tcf try/catch/finally
try {
  $1
} catch (error) {
  $2
} finally {
  $3
}
tf try/finally
try {
  $1
} finally {
  $2
}

Functions

Prefix Name Body
fn function
function ${1:name}($2) {
  $0
}
fna async function
async function ${1:name}($2) {
  $0
}
nfn named arrow function
const ${1} = ($2) => {$0}
nfna async named arrow function
const ${1:name} = async ($2) => {$0}
af arrow function
($1) => $0
afa async arrow function
async ($1) => $0
afb arrow function with body
($1) => {
  $0
}
afba async arrow function with body
async ($1) => {
  $0
}
iife immediately-invoked function expression
(($1) => {
  $0
})($2)

Loops

Prefix Name Body
fl for loop
for (let ${1:i} = 0, ${2:len} = ${3:iterable}.length; ${1:i} < ${2:len}; ${1:i}++) {
  $0
}
rfl reverse for loop
for (let ${1:i} = ${2:iterable}.length - 1; ${1:i} >= 0; ${1:i}--) {
  $0
}
flr for loop (range)
for (let ${1:i} = 0; ${1:i} < ${2:5}; ${1:i}++) {
  $0
}
fin for...in loop
for (let ${1:key} in ${2:array}) {
  $0
}
fof for...of loop
for (let ${1:item} of ${2:items}) {
  $0
}
fofa for await...of loop
for await (let ${1:item} of ${2:items}) {
  $0
}
wl while loop
while (${1:true}) {
  $0
}

Classes

Prefix Name Body
cs class
class $1 {
  $0
}
cse class extends
class $1 extends ${2:Base} {
  $0
}
csc class with constructor
class $1 {
  constructor($2) {
  	$0
  }
}
csec class extends with constructor
class $1 extends ${2:Base} {
  constructor($3) {
  	$0
  }
}
ctor class constructor
constructor($1) {$0}
get getter
get ${1:property}() {
  $0
}
set setter
set ${1:property}(${2:value}) {
  $0
}
gs getter and setter
get ${1:property}() {
  $0
}
set ${1:property}(${2:value}) {
  
}
met method
${1:name}($2) {
  $0
}
meta async method
async ${1:name}($2) {
  $0
}

Promises

Prefix Name Body
fet fetch
fetch('$1'$2).then(res => res.json())
feta fetch assignment
const ${1|data,{ data }|} = await fetch('$2'$3).then(res => res.json())
pr promise
new Promise((resolve, reject) => {
  $0
})
prs Promise.resolve
Promise.resolve($1)
prj Promise.reject
Promise.reject($1)
then promise then()
$1.then((${2:value}) => $0)
catch promise catch()
$1.catch((${2:err}) => $0)
thenc promise then().catch()
$1.then((${2:value}) => $3).catch((${4:err}) => $5)
pra Promise.all
Promise.all($1)
prsa Promise.allSettled
Promise.allSettled($1)
pran Promise.any
Promise.any($1)

Modules

Prefix Name Body
im import from module
import { $2 } from '${1:module}';
imd import default
import $2 from '${1:module}';
ima import as
import ${2:*} as ${3:name} from '${1:module}';
imf import file
import '$1';
imp import dynamic
import('$0')
impa await import dynamic
await import('$0')
ime import meta env
import.meta.env.$0
ex export
export $0
exd export default
export default $0
exf export from
export { $0 } from '${1:module}';
exa export all from
export * from '${1:module}';
exo export object
export const ${1:name} = { $0 }
efn export function
export function ${1:name}($2) {
  $0
}
edfn export default function
export default function ${1:name}($2) {
  $0
}
enfn export named arrow function
export const ${1:name} = ($2) => {$0}

Array methods

Prefix Name Body
fe Array.forEach()
$1.forEach((${2:item}) => {
  $0
})
map Array.map()
$1.map((${2:item}) => ${3})
reduce Array.reduce()
$1.reduce((${2:acc}, ${3:curr}) => {
  $0
}, ${4:initial})
reduce-right Array.reduceRight()
$1.reduceRight((${2:acc}, ${3:curr}) => {
  $0
}, ${4:initial})
filter Array.filter()
$1.filter((${2:item}) => ${3})
find Array.find()
$1.find((${2:item}) => ${3})
every Array.every()
$1.every((${2:item}) => ${3})
some Array.some()
$1.some((${2:item}) => ${3})
reverse Array.reverse()
$1.reverse()
map-string Array.map() as string
$1.map(String)
map-number Array.map() as number
$1.map(Number)
filter-true Array.filter() truthy
$1.filter(Boolean)

Objects

Prefix Name Body
oe Object.entries
Object.entries($0)
ofe Object.fromEntries
Object.fromEntries($0)
ok Object.keys
Object.keys($0)
ov Object.values
Object.values($0)

Returns

Prefix Name Body
re return
return $0
reo return object
return {
  $0
}
rei return object inline
return ({$0})

Operators, Expressions, Literals

Grouping them all together for now

Prefix Name Body
or OR (||)
|| $0
and AND (&&)
&& $0
nc nullish coalescing (??)
?? $0
eq strict equality (===)
=== $0
ore logical OR expression
$1 || $0
ande logical AND expression
$1 && $0
nce nullish coalescing expression (??)
$1 ?? $0
eqe strict equality expression
$1 === $0
ora logical OR assignment (||=)
$1 ||= $0
nca nullish coalescing assignment (??=)
$1 ??= $0
inc addition assignment
$1 += ${0:1}
sub subtraction assignment
$1 -= ${0:1}
mul multiplication assignment
$1 *= ${0:1}
div division assignment
$1 /= ${0:1}
ol object literal
{ $1: $0 }
al array literal
[$0]
tl template literal
`$0`
tlo template literal operation
${$1}$0
tle template literal expression
`$1${$2}$3`

Console

Prefix Name Body
cl console.log
console.log($0)
ci console.info
console.info($1)
cdi console.dir
console.dir($1)
ce console.error
console.error($1)
cw console.warn
console.warn($1)
ct console.time
console.time('$1')
$0
console.timeEnd('$1')
ctb console.table
console.table($1)
clr console.clear
console.clear()
clm console.log message
console.log('$0')
clo console.log object
console.log({ $0 })
clc console.log clipboard
console.log({ $CLIPBOARD })
cll console.log (labeled)
console.log('$1 ->', $1$2)
cel console.error (labeled)
console.error('$1 ->', $1$2)
cwl console.warn (labeled)
console.warn('$1 ->', ${2:$1})

Timers

Prefix Name Body
si set interval
setInterval(() => {
  $0
}, ${1:delay})
st set timeout
setTimeout(() => {
  $0
}, ${1:delay})
sim set immediate
setImmediate(() => {
  $0
})
nt process next tick
process.nextTick(() => {
  $0
})

JSON

Prefix Name Body
jp JSON parse
JSON.parse(${1:json})
js JSON stringify
JSON.stringify(${1:value})
jsp JSON stringify (pretty)
JSON.stringify(${1:value}, null, 2)
jss JSON.stringify if not string
typeof ${1:value} === 'string' ? value : JSON.stringify($1)

DOM

Prefix Name Body
qs query selector
${1:document}.querySelector('$2')
qsa query selector all
${1:document}.querySelectorAll('$2')
qsaa query selector all as array
[...${1:document}.querySelectorAll('$2')]
ael event listener
${1:document}.addEventListener('${2:click}', (e$3) => $0)
qsae query selector with event listener
${1:document}.querySelector('$2')?.addEventListener('${3:click}', (e$4) => $0)
gid get element by id
${1:document}.getElementById('$2')
on event handler
${1:emitter}.on('${2:event}', (${3:arguments}) => {
  $0
})

Dates

Prefix Name Body
nd new Date()
new Date($1)
now Date.now()
Date.now()

Testing

Prefix Name Body
desc describe
describe('${1:description}', () => {
  $0
})
cont context
context('${1:description}', () => {
  $0
})
it test (synchronous)
it('${1:description}', () => {
  $0
})
ita test (asynchronous)
it('${1:description}', async () => {
  $0
})
itc test (callback)
it('${1:description}', (done) => {
  $0
  done()
})
bf before test suite
before(() => {
  $0
})
bfe before each test
beforeEach(() => {
  $0
})
aft after test suite
after(() => {
  $0
})
afe after each test
afterEach(() => {
  $0
})

Types

Prefix Name Body
aia is array
Array.isArray($0)
tof typeof
typeof ${1:value} === '${2|bigint,boolean,function,number,object,symbol,undefined|}'
iof instanceof
${1:object} instanceof ${0:Class}
isnil is nil
${1:value} == null
nnil is not nil
${1:value} != null
isnan is NaN
isNan($0)
nnan is not NaN
!isNan($0)

Misc

Prefix Name Body
us 'use strict' statement
'use strict'
pse process.server
process.server
pcl process.client
process.client
env env variable
process.env.$0
envv env variable (vite)
import.meta.env.$0

Uncategorized

Will be sorted into appropriate categories in the future.

Prefix Name Body
uniq array of unique values
[...new Set($0)]
pi parse int
parseInt($1, ${2|10,2,8,16|})
pf parse float
parseFloat($1)
am array merge
[...$1]
om object merge
{ ...$1 }
aat array.at
$1.at(${2:0})
seq sequence of 0..n
[...Array(${1:length}).keys()]

TypeScript

Available only in .ts and .tsx files

Declarations

Prefix Name Body
cat const assignment (typed)
const $1: ${2:string} = $3
lat let assignment (typed)
let $1: ${2:string} = $3
caat array assignment (typed)
const $1: ${2:string}[] = [$0]
caot object assignment (typed)
const $1: ${2:object} = { $0 }

Types

Prefix Name Body
int interface
interface ${1:Model} {
  $0
}
inte interface extends
interface ${1:Model} extends ${2:Base} {
  $0
}
tp type
type ${1:Model} = $0
tpu type union
type ${1:Model} = $2 | $3
tpi type intersection
type ${1:Model} = $2 & $3

Running locally

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

# generate .code-snippets and documentation
npm run generate