Javascript and Typescript snippets
Sometimes I come across different tricks that help me make some magic in Javascript or Typescript work and then I usually forget about them. This is an attempt to list them in one place as I go. This post will be updated regularly.
Assign new property to Window object
Usually you do window.<new_property> = <value>
but IDE like Webstorm will show an error that the <new_property>
doesn't exist on object window
, so you can do the same in ES6 style with:
const <new_property> = <class_function_or_object>
Object.assign(window, { <new_property> })
example with Ably
service attached to window
:
Object.assign(window, { Ably })
which is the same as:
Object.assign(window, { Ably: Ably })
Generate random string
We have so many ways of achieving this, but I like the one with window.crypto
:
function generateId (length: number): string {
const arr = new Uint8Array((length || 40) / 2)
window.crypto.getRandomValues(arr)
return Array.from(
arr,
(dec) => dec.toString(16).padStart(2, '0')
).join('')
}
Trigger window resize event
Manually dispatching resize
event on browser window is quite easy. It allows you to re-run code assigned to the event if you don't have a function that you can call.
window.dispatchEvent(new Event('resize'))
Get current year in full (4 digits)
I use it in copyright notice in footer and never remember the right syntax. Last time I forgot to put parenthesis after Date and had to google it again. I blame switching between PHP and Javascript. My brain is mixing things up.
const year = new Date().getFullYear()
COMMENTS