JavaScript Snippets
Conditional prop (for React components & Objects)
const o = { id: 1, ...(condition && { b: 5 }) }
<button id='1' {...(condition && { b: 5 })} />
Dynamic object key
const { name, id } = event.target
setSearchParams({ [name]: id })
Date Time
const timeStamp = new Date() // Mon Nov 15 2021 09:37:35 GMT+0700 (GMT+07:00)
timeStamp.toLocaleString() // 11/15/2021, 9:37:35 AM
timeStamp.toLocaleDateString() // 11/15/2021
timeStamp.toLocaleTimeString() // 9:37:35 AM
timeStamp.getHours() // getMinutes(), getSeconds(), getMilliseconds()
const day = timeStamp.getDay() // 1 (0 is Sunday, 1 is Monday, ...)
const date = timeStamp.getDate() // 15
const month = timeStamp.getMonth() // 10 (0 is January, 1 is February, ...)
const year = timeStamp.getFullYear() // 2021. `getYear()` is deprecated
const timeStampInMs = timeStamp.getTime() // 1636943855000. Useful for comparing date values. `Date.now()` is the same.
// If not specify locale (`undefined` instead of `en-US`), use the browser's default locale
timeStamp.toLocaleString('en-US', {
// Shortcut, CAN'T be used with other options (e.g. weekday, hour, month, etc.).
dateStyle: 'full', // full, long, medium, short
timeStyle: 'short', // full, long, medium, short
}) // Saturday, November 4, 2023 at 10:36 AM
// For `dateTime` attribute of <time> element: <time dateTime={isoString}>...</time>
const isoString = timeStamp.toISOString()
const isoDateString = timeStamp.toISOString().split('T')[0]
const isoTimeString = timeStamp.toISOString().split('T')[1].slice(0, -1)
Round to n
decimal places
// Simple, with value = 1.50
Math.round(value * 100) / 100 // number 1.5, for 3 decimal places use 1000, etc.
value.toFixed(2) // string "1.50", use `parseFloat` to convert to number 1.5
// More comprehensive
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals)
}
round(1.005, 2) // 1.01
Measure function runtime
// Cach 1
console.time('filter array')
const visibleTodos = getFilteredTodos(todos, filter)
console.timeEnd('filter array') // filter array: 0.15ms
// Cach 2
const start = performance.now()
const visibleTodos = getFilteredTodos(todos, filter)
const end = performance.now()
console.log('filter array took', end - start, 'ms')
Create a base Array
Array.from({ length: 5 }, (_, i) => i + 1) // [1, 2, 3, 4, 5]
Array(5).fill(0) // [0, 0, 0, 0, 0]
Move array item to last position
array.push(array.splice(index, 1)[0]) // Already know the index of the item to move
array.push(array.splice(array.indexOf(element), 1)[0]) // If you don't have the index, and only the element
Shallow Copy vs Deep Copy (with Lodash)
const obj = [{ a: 1 }, { b: 2 }]
const shallow = _.clone(obj)
shallow[0] === obj[0] // true
const deep = _.cloneDeep(obj)
deep[0] === obj[0] // => false
const newDeep = structuredClone(obj)
newDeep[0] === obj[0] // => false
Delete Reference value
let arr1 = [1, 2]
const arr2 = arr1
// ❌ Xóa arr1 dính luôn arr2
arr1.length = 0 // arr2 = []
arr1.splice(0, arr1.length) // arr2 = []
// ✅ Xóa arr1 ko ảnh hưởng đến arr2
arr1 = [] // arr2 = [1, 2];
Nested Destructing
const {
data: {
plans,
plans: [plan1, plan2],
},
} = {
data: {
plans: [
{ a: 1, b: 2 },
{ a: 3, b: 4 },
],
},
}
Barrel
A container file and is represented by index.js
file which exports different files together within the same folder.
- Components/Carousel.jsx
- Components/Product.jsx
- Components/index.js
- Cart/Cart.jsx
export default function Carousel() {
return <h1>Carousel</h1>
}
export default function Product() {
return <h1>Product</h1>
}
export { default as Cart } from './Cart'
export { default as Product } from './Product'
import { Carousel } from '../Components'
import { Product } from '../Components'
export default function Cart() {
return (
<div>
<Carousel />
<Product />
</div>
)
}
Swap array items
let arr = [1, 2, 3, 4]
;[arr[0], arr[1]] = [arr[1], arr[0]]
// Nếu ko có dấu ; thì sẽ bị lỗi:
arr = [1, 2, 3, 4][(arr[0], arr[1])] = [arr[1], arr[0]]
Cache a value
const cache = {}
function addTwo(input) {
if (!cache.hasOwnProperty(input)) {
cache[input] = input + 2
}
return cache[input]
}
addTwo(3) // 5
addTwo(3) // 5, but this time we got it from the cache 🤓