Snippets
Conditionally add properties๐ก in the object from 11 Useful Modern JavaScript Tips
const isValid = false
const age = 18
const person = {
name: "Krina",
...(isValid && { isActive: true }),
...(age >= 18 || (isValid && { card: 0 })),
}
58 JavaScript Tips and Tricks for Web Developers
Loop array
const array = ["a", "b", "c"]
for (let item of array) {
console.log(item)
}
Copy text to clipboard
const copyTextarea = document.querySelector("#urlToShare")
copyTextarea.focus()
copyTextarea.select()
try {
document.execCommand("copy")
alert(this.$t("URL์ด ๋ณต์ฌ๋์์ต๋๋ค. ์ํ๋ ๊ณณ์ ๋ถ์ฌ๋ฃ๊ธฐ ํ์ธ์."))
} catch (err) {
alert(this.$t("๋ณต์ฌ๊ฐ ์คํจํ์ต๋๋ค. ์ง์ ๋ณต์ฌํ์ธ์."))
}
Throttling requests
let cRequest = 0
export const preventDOSsuspiciousAction = () => {
cRequest++
return new Promise((resolve) => {
setTimeout(() => {
cRequest = 0
resolve()
}, cRequest * 300)
})
}
//
window.promisePost = async (URL, prms, noToast = false, loadingFor) => {
showBusyIndicator(loadingFor)
await preventDOSsuspiciousAction()
return new Promise((resolve, reject) => {
$.post(URL, prms)
.done((rsp) => {
if (rsp.success) {
resolve(rsp)
return
}
if (!noToast) vueObj.$toast.open(rsp.message)
reject(rsp)
})
.fail(reject)
.always(() => {
hideBusyIndicator(loadingFor)
})
})
}
Deep copy in JavaScript
const original = { id: 0, prop: { name: "Tom" } }
/* Old hack */
const deepCopy = JSON.parse(JSON.stringify(original))
/* New way */
const deepCopy = structuredClone(original)
Children