DEV Community

Cover image for Important Javascript functions you have to know to be a better developer
Sam Sonter
Sam Sonter

Posted on • Updated on

Important Javascript functions you have to know to be a better developer

Hi everybody, today I am going to show examples of few important Javascript functions.

DEEP COPY

JavaScript allows you to deep copy an object by converting it into string and then back into object.

Here is an example:

const deepCopy = (obj) => { 
JSON.parse(JSON.stringify(obj)) 
};
Enter fullscreen mode Exit fullscreen mode

WAIT FUNCTION

Javascript can do a ship with a setTimeout function,
but it does not return a promise object, making it hard to use in async functions. So, we have to write our own wait sleep function.
Here is an example:

const wait = new Promise((resolve) => setTimeout(resolve, ms));

const asyncFunction = async() => {
    await wait(1000);
    console.log("async");

};
asyncFunction();
Enter fullscreen mode Exit fullscreen mode

Intersection Observer

You can check if an element is visible at viewport.
I am going to make use of intersectionObserver()
to check if an element is visible in the viewport.


const callback = (entries) => {
        entries.foreach((entry) => {
                    entries.forEach((entry) => {
                        if (entry.isIntersecting) {
                            //enter target in dom element.
                            //e.g entry.target.classList.add('animated');
                            console.log(`${entry.target} is visible`);
                        }
                    });
                };

                const options = {
                    threshold: 1.0,
                };

                const observer = new IntersectionObserver(callback, options);
                const btn = document.getElementById('.btn');
                const bottomBtn = document.getElementById('.bottomBtn');

observer.observe(btn); 
observer.observe(bottomBtn);
Enter fullscreen mode Exit fullscreen mode

Customize the behavior of the observer using the option parameter. threshold is the most useful attribute.
It defines the percentage of the element that
needs to be visible in the viewport of the browser trigger.

HIDE ELEMENTS

you can toggle the visibility of an element using the style. visiabilty property and in case you want to remove it from the render flow, you can the style.display property.
Here is an example:


const hideElement = (element, removeFromFlow = false) => {
    removeFromFlow
        ?
        (element.style.display = 'none') :
        (element.style.visibility = 'hidden');
}

Enter fullscreen mode Exit fullscreen mode

GET URL PARAMETERS

Easy search of parameters from a URL objects.
Here is an example:

const url = new URL(window.location.href);
const paramterValue = url.searchParams.get("pramaName");
console.log(paramterValue);
Enter fullscreen mode Exit fullscreen mode

DECTECT DEVICE TYPES

Use navigator.UserAgent to detect the device running the app.
Here is example:

const dectectDeviceType = () =>
    /Andriod|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        navigator.userAgent
    ) ?
    "mobile" :
    "desktop";
console.log(dectectDeviceType);
Enter fullscreen mode Exit fullscreen mode

If you dont remove an element from the render flow , it will be hidden , but its space will be occupied. it is highly useful while rendering long list of elements.
The elements not in view can be tested using IntersectionObserver Can be hidden to provide a performance boost.

Top comments (18)

Collapse
 
_genjudev profile image
Larson • Edited

You should not use JSON.stringify to clone object. It leads to problems because it can't strinigfy functions,symbol etc.

JSON.stringify({ 
    fun: () => console.log('lol'), 
    s: Symbol(), 
    u: undefined, 
    n: NaN, 
    in: Infinity
})
'{"n":null,"in":null}'
Enter fullscreen mode Exit fullscreen mode

Just use lodash. Or write your own deep cloning algo. Or when using the browser you can use structuredClone (there are some limits too).

Collapse
 
peerreynders profile image
peerreynders

Node.js 17.0.0 added structuredClone(value[, options])

Before that use v8.serialize(value) and v8.deserialize(buffer).

Then there is flatted which adds recursive references and RecursiveMap on top of JSON (still no functions, symbols, etc.).

Collapse
 
asapsonter profile image
Sam Sonter

noted. thanks

Collapse
 
asapsonter profile image
Sam Sonter

noted. thanks

Collapse
 
tamirazrab profile image
Tamir

"And you can google any of these if needed." reading relaxed me instantly.

Collapse
 
curiousdev profile image
CuriousDev

Thank you and I would like to add, that creating a clone with JSON object (with parse and stringify) has some limitations! It will not work with every object.

Collapse
 
codingjlu profile image
codingjlu

It's also important to remember that JSON.stringify cannot copy functions, so the "deep copy" only works for regular data types and objects.

Collapse
 
asapsonter profile image
Sam Sonter

hhahahhahah. what work, works

Collapse
 
jacksonkasi profile image
Jackson Kasi

wow, thanks, it's really helpful for me :)

Collapse
 
mat3uszkek profile image
Mateusz Skrobiś

love that reply, thank u.

Collapse
 
risclover profile image
Sara (Risclover)

These seem useful. Thanks for posting!

Collapse
 
asapsonter profile image
Sam Sonter

you are welcome

 
sanzhardanybayev profile image
Sanzhar Danybayev

That's good too hear. I like your attitude. No offense. Might have misread your comment.

Collapse
 
sanzhardanybayev profile image
Sanzhar Danybayev

Bro, you're a bit harsh. Though I would agree that title looks like a clickbait.

Collapse
 
asapsonter profile image
Sam Sonter

I dont mind criticism. Its ok

Thread Thread
 
sanzhardanybayev profile image
Sanzhar Danybayev

You're opened minded. Much respected!

Collapse
 
insign profile image
Hélio oliveira

There is some typos. Like DECTECT , Andriod, prama, visiabilty.

Collapse
 
longcui profile image
Long Cui

The "Wait" function is wrong. Please see @luke shiru's comment.