Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

matijaoe/modern-javascript-snippets

Repository files navigation

Modern JavaScript Snippets ⚡

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


JavaScript TypeScript

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

Prefix Name Body
ca const assignment
const ${1:name} = 2ドル
la let assignment
let ${1:name} = 2ドル
cas const string assignment
const ${1:name} = '2ドル'
las let string assignment
let ${1:name} = '2ドル'
caa const array assignment
const ${1:arr} = [0ドル]
cao const object assignment
const ${1:obj} = { 0ドル }
dob object destructuring
const { 2ドル } = ${1:obj}0ドル
dar array destructuring
const [2ドル] = ${1:arr}0ドル

Functions

Prefix Name Body
fn function
function ${1:fn}(2ドル) {
 0ドル
}
fna async function
async function ${1:fn}(2ドル) {
 0ドル
}
nfn named arrow function
const ${1:fn} = (2ドル) => {0ドル}
nfna async named arrow function
const ${1:fn} = async (2ドル) => {0ドル}
af arrow function
(1ドル) => 0ドル
arr arrow function arrow
=> 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ドル)

Flow control

Prefix Name Body
iff if statement
if (${1:true}) {2ドル}
ifel if/else statement
if (${1:true}) {2ドル} else {3ドル}
ifei if/else-if statement
if (${1:true}) {2ドル} else if (3ドル) {4ドル}
el else statement
else {
 0ドル
}
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ドル
}
scase switch case
case 1ドル : 2ドル
tc try/catch
try {
 1ドル
} catch (err) {
 0ドル
}
tcf try/catch/finally
try {
 1ドル
} catch (err) {
 2ドル
} finally {
 3ドル
}
tf try/finally
try {
 1ドル
} finally {
 2ドル
}

Loops

Prefix Name Body
flr for loop (range)
for (let ${1:i} = 0; ${1:i} < ${2:5}; ${1:i}++) {
 0ドル
}
rfl reverse for loop
for (let ${1:i} = ${2:iter}.length - 1; ${1:i} >= 0; ${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ドル
}
dwl do while loop
do {
 0ドル
} while (1ドル)

Classes

Prefix Name Body
cs class
class 1ドル {
 0ドル
}
cse class extends
class 1ドル extends ${2:Base} {
 0ドル
}
csp class proprety
${1:name} = ${2:value}
csc class with constructor
class 1ドル {
 constructor(2ドル) {
 0ドル
 }
}
csec class extends with constructor
class 1ドル extends ${2:Base} {
 constructor(3ドル) {
 0ドル
 }
}
cst 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}) {
 0ドル
}
met method
${1:name}(2ドル) {
 0ドル
}
meta async method
async ${1:name}(2ドル) {
 0ドル
}

Array methods

Prefix Name Body
aat array.at
1ドル.at(${2:0})
fe Array.forEach()
1ドル.forEach((${2:item}) => {
 0ドル
})
map Array.map()
1ドル.map((${2:item}) => ${3})
fmap Array.flatMap()
1ドル.flatMap((${2:item}) => ${3})
reduce Array.reduce()
1ドル.reduce((${2:acc}, ${3:curr}) => {
 0ドル
}, ${4:initial})
reduceRight 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})
findl Array.findLast()
1ドル.findLast((${2:item}) => ${3})
findi Array.findIndex()
1ドル.findIndex((${2:item}) => ${3})
findli Array.findLastIndex()
1ドル.findLastIndex((${2:item}) => ${3})
every Array.every()
1ドル.every((${2:item}) => ${3})
some Array.some()
1ドル.some((${2:item}) => ${3})
reverse Array.reverse()
1ドル.reverse()
sort Array.sort(
1ドル.sort((${2:a}, ${3:b}) => 4ドル)
group Array.group()
1ドル.group((${2:item}) => 3ドル)
groupMap Array.groupToMap()
1ドル.groupToMap((${2:item}) => 3ドル)
mapStr Array.map() to string
1ドル.map(String)
mapNum Array.map() to number
1ドル.map(Number)
mapBool Array.map() to boolean
1ドル.map(Boolean)
filterTruthy Array.filter() truthy
1ドル.filter(Boolean)
arfr Array.from
Array.from(1ドル)

Modules

Prefix Name Body
im import from module
import { 2ドル } from '${1:module}'
imd import default
import ${2:thing} 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ドル')
imm import meta
import.meta.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ドル}

Promises

Prefix Name Body
fet fetch
await fetch(1ドル).then(res => res.json())
feta fetch assignment
const ${1|data,...|} = await fetch(2ドル).then(res => res.json())
npr promise
new Promise((resolve, reject) => {
 0ドル
})
prr Promise.resolve
Promise.resolve(1ドル)
prj Promise.reject
Promise.reject(1ドル)
then promise then()
1ドル.then((${2:value}) => 0ドル)
catc 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ドル)
pras Promise.allSettled
Promise.allSettled(1ドル)
pran Promise.any
Promise.any(1ドル)

Literals, operators, expressions

Grouping them all together for now

Prefix Name Body
arr array literal
[0ドル]
ob object literal
{ }
tl template literal
`0ドル`
tle template literal operation
${${1:name}}0ドル
ns new Set
new Set(1ドル)
nm new Map
new Map(1ドル)
am array merge
[...1ドル]
om object merge
{ ...1ドル }
or OR (||)
|| 0ドル
and AND (&&)
&& 0ドル
lt less than (<)
< 0ドル
lte less than or equal to (<=)
<= 0ドル
gt greater than (>)
> 0ドル
gte greater than or equal to (>=)
>= 0ドル
nc nullish coalescing (??)
?? 0ドル
neq strict non-equality (===)
!== 0ドル
eq strict equality (===)
=== 0ドル
ora logical OR assignment (||=)
||= 0ドル
nca nullish coalescing assignment (??=)
??= 0ドル
plus addition
+ 0ドル
minus subtraction
- 0ドル
mul multiplication
* 0ドル
div division
/$0
mod modulo
% 0ドル
inc addition assignment
+= ${0:1}
sub subtraction assignment
-= ${0:1}
mula multiplication assignment
*= ${0:1}
diva division assignment
/=${0:1}
col colon
: 

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ドル)

Utilities

Prefix Name Body
pi parse int
parseInt(1ドル, ${2|10,...|})
pf parse float
parseFloat(1ドル)
uniq array of unique values
[...new Set(0ドル)]
seq sequence of 0..n
[...Array(${1:length}).keys()]
cp copy to clipboard
navigator.clipboard.writeText(1ドル)
nurl new URL
new URL(1ドル)
sp url search params
new URLSearchParams(1ドル)
spa url search params assignment
const ${1:params} = new URLSearchParams(2ドル)
spg get search param
${1:params}.get(2ドル)
sps set search param
${1:params}.set(2ドル, 3ドル)

Returns and exceptions

Prefix Name Body
ret return
return 0ドル
reo return object
return {
 0ドル
}
rei return object inline
return ({0ドル})
terr throw error
throw new ${1|Error,...|}(0ドル)

Timers

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

JSON

Prefix Name Body
jsp JSON parse
JSON.parse(${1:json})
jss JSON stringify
JSON.stringify(${1:value})
jssf JSON stringify (formatted)
JSON.stringify(${1:value}, null, 2)

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ドル)
cil console.info (labeled)
console.info('1ドル :', 1ドル2ドル)
cel console.error (labeled)
console.error('1ドル :', 1ドル2ドル)
cwl console.warn (labeled)
console.warn('1ドル :', ${2:1ドル})

Dates

Prefix Name Body
nd new Date()
new Date(1ドル)
nds new Date() with date string
new Date('${1:2023}-${2:|01,...|}-${3:31}')
now Date.now()
Date.now()
tls Date.toLocaleString()
1ドル.toLocaleString('${2|en-US,...|}'3ドル)

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}', (e3ドル) => 0ドル)
qsae query selector with event listener
${1:document}.querySelector('2ドル')?.addEventListener('${3:click}', (e4ドル) => 0ドル)
gid get element by id
${1:document}.getElementById('2ドル')

Node

Prefix Name Body
req require
require('${1:module}')
rqr require assignment
const 1ドル = require('${1:module}')
mex module.exports
module.exports = {1ドル}

Intl

Internationalization API

Prefix Name Body
inf Intl.NumberFormat
new Intl.NumberFormat('${1|en-US,...|}'3ドル).format(2ドル)
infs Intl.NumberFormat style
new Intl.NumberFormat('${1|en-US,...|}', {
 style: '${3|decimal,...|}',4ドル
}).format(2ドル)
infc Intl.NumberFormat as currency
new Intl.NumberFormat('${1|en-US,...|}', {
 style: 'currency',
 currency: '${3|USD,...|}',4ドル
}).format(2ドル)
infp Intl.NumberFormat as percentage
new Intl.NumberFormat('${1|en-US,...|}', {
 style: 'percent',3ドル
}).format(2ドル)
infu Intl.NumberFormat as unit
new Intl.NumberFormat('${1|en-US,...|}', {
 style: 'unit',
 unit: '${3|acceleration-g-force,...|}',
 unitDisplay: '${4|long,...|}',0ドル
}).format(2ドル)
idtf Intl.DateTimeFormat
new Intl.DateTimeFormat('${1|en-US,...|}'3ドル).format(2ドル)
idtfs Intl.DateTimeFormat with style
new Intl.DateTimeFormat ('${1|en-US,...|}', {
 dateStyle: '3ドル',0ドル
}).format(2ドル)

Types

Prefix Name Body
aia is array
Array.isArray(0ドル)
tof typeof
typeof 1ドル
tofc typeof check
typeof 1ドル === '${2|undefined,...|}'
iof instanceof
1ドル instanceof ${0:Class}
isnil is nil
1ドル == null
nnil is not nil
1ドル != null
isnan is NaN
isNaN(0ドル)
nnan is not NaN
!isNaN(0ドル)

Testing

Prefix Name Body
desc describe
describe('1ドル', () => {
 0ドル
})
cont context
context('1ドル', () => {
 0ドル
})
it test (synchronous)
it('1ドル', () => {
 0ドル
})
ita test (asynchronous)
it('1ドル', async () => {
 0ドル
})
itc test (callback)
it('1ドル', (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ドル
})

Globals

Prefix Name Body
wlo window.location
window.location
wlh window.location.href
window.location.href

Misc

Prefix Name Body
us 'use strict' statement
'use strict'
prs process.server
process.server
prc process.client
process.client
env env variable
process.env.0ドル
envv env variable (meta)
import.meta.env.0ドル

TypeScript

Available only where TypeScript is supported

Declarations

Prefix Name Body
cat const assignment (typed)
const ${1:name}: ${2:string} = 3ドル
lat let assignment (typed)
let ${1:name}: ${2:string} = 3ドル
caat array assignment (typed)
const ${1:arr}: ${2:string}[] = [0ドル]
caot object assignment (typed)
const ${1:obj}: ${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} = 2ドル
tpu type union
type ${1:Model} = ${2:string} | ${3:number}
tpi type intersection
type ${1:Model} = 2ドル & 3ドル

DOM

Prefix Name Body
qst query selector (typed)
${1:document}.querySelector<${2|HTMLElement,...|}>('3ドル')
qsat query selector all (typed)
${1:document}.querySelectorAll<${2|HTMLElement,...|}>('3ドル')
qsaat query selector all as array (typed)
[...${1:document}.querySelectorAll<${2|HTMLElement,...|}>('3ドル')]
gidt get element by id (typed)
${1:document}.getElementById<${2|HTMLElement,...|}>('3ドル')

Running locally

# ensure Deno is installed
# https://deno.land/manual@v1.29.1/getting_started/installation
# generate .code-snippets and documentation
npm run generate

AltStyle によって変換されたページ (->オリジナル) /