Javascript useful code snippets
I summarize several useful Javascript/Typescript code snippets.
- Get the last element from an array. Note: in the future, you can use Array Relative Indexing
arr.at(-1)
once the proposal is finalized.
arr.slice(-1)[0]
- Optional array element.
[
cond && elm, // include elm only when cond is truthy
elm1,
].filter(Boolean)
This is very useful when you want to join a list of class names conditionally.
export const joinClassNames = (...classNames: ReadonlyArray<string | boolean | undefined>) => classNames
.filter(Boolean)
.join(' ')
I published a package for this, named jcls.
- Conditional object property.
const a = {
...val && {val},
key1: 'value1'
}
- Create an object from an array of properties.
const obj = Object.fromEntries(['key1', 'value1'], ['key2', 'value2'])
- Avoid ESLint warnings when you only import types from a dev or nested dependency package. Use
import type
.
ESLint: 'history' should be listed in the project's dependencies. Run 'npm i -S history' to add it(import/no-extraneous-dependencies)
import type {Location, LocationDescriptor, LocationState} from 'history'
- Check if the running environment is browser or others.
export const isBrowser = typeof window === 'object'
- Sort an array immutably.
arr.slice().sort()
Or use the recently introduced Array.prototype.toSorted()
.
- Sort an array in numerical order. Note: the default comparison function casts values to a string and compares them in lexigraphy order.
arr.slice().sort((a, b) => a - b)
- Replace all occurrences of
needle
toreplacement
inhaystack
. Note: if you are using NodeJS >= 15.x, useString.replaceAll
.
haystack.split(needle).join(replacement)