JavaScript Tips & Tricks

JavaScript Tips & Tricks

Β·

4 min read

Must Know JavaScript Tips & Tricks 🎈

Let's have a look at 7 valuable tips and tricks found in the most popular language in the world, JavaScript.

1. Deep Copy with JSON

You may have heard of using object spread or Object.assign() to make shallow copies of an object, but did you know about using JSON to make deep copies?

Simply convert an object to JSON using JSON.stringify() and then re-parse it using JSON.parse() to create a deep copy.

Just remember to only do this for simple objects, as doing it on large objects may raise performance issues.

const person = {
    name: "Dom",
    age: 28,
    skills: [
        "Programming",
        "Cooking",
        "Tennis"
    ]
};

const copied = JSON.parse(JSON.stringify(person));

// false 😎
console.log(person.skills === copied.skills);

2. Destructuring with Parameters

You can use object destructuring within function parameters. A popular use case for this would be something like event listeners, and gaining access to the target property on the event object.

buttonElement.addEventListener("click", ({ target }) {
    // is the same as using e.target πŸ‘‡
    console.log(target);
});

3. Easy Defaults with OR

Basically, you can use the logical OR operator (||) for defaults as opposed to using an if statement.

Alternatively, for stricter comparisons, you can take advantage of the nullish coalescing operator

Old Code (using if statement - 4 lines)

let username = getUsername();

if (!username) {
    username = "Dom";
}

New Code (using || - 1 line)

const username = getUserdata() || "someOtherValue";

4. Remove Array Duplicates

You may have heard of this one before, but there's a really simple way to remove duplicates from an array using the Set data structure.

Basically, Set doesn't allow duplicate values. We can take advantage of that by turning an array into a Set, and then back into an array.

const numbers = [5, 10, 5, 20];
const withoutDuplicates = Array.from(new Set(numbers));

// [5, 10, 20] πŸ‘‡
console.log(withoutDuplicates);

I Used frequently below code.

var arr = ["apple", "mango", "apple",
            "orange", "mango", "mango"];  
    function removeDuplicates(arr) {
        return [...new Set(arr)];
    }
    console.log(removeDuplicates(arr));

5. Advanced Array Searching

Step aside, indexOf() and includes() because there's another method that allows for advanced array searching and it's called find().

The find() method allows you to pass in a test function. The first element within the array to pass the test function will be returned.

This makes for more useful array searching.

const platforms = [
    "mysql",
    "vue",
    "angular",
    "nodejs",
    "nestjs",
    "firebase",
    "supabase",

];

const result = platforms.find(o => o.startsWith("n"));

console.log(result);

6. Self-Invoking Functions

This one is a classic. Self-invoking functions are functions that execute themselves. A common use case for these is to assign a variable or constant that requires complex logic.

const someComplexValue = (() => {
    const a = 10;
    const b = 20;

    if (a > b) {
        return a * b;
    }

    return b / a;
})();

Of course, the above example is trivial but you can imagine the kind of complex code you may require to be within the self-invoking function.

7. Array Copying with Spread

Last on this list involves creating shallow copies of an array. We can do this using spread (...).

const numbers = [5, 19, 24, 36,56];
const numbersCopy = [...numbers];

// false
console.log(numbers === numbersCopy);

8. Reduce the length of an array using an array length property

We can reduce the size of the array using the array.length() method,

Let’s see the code for that:

let array = [11,12,12,122,1222]

We now have an array of 5 elements. array.length will return 5.

Now suppose I want to reduce the length of an array we can just do it by using array.length = 4 now when you print the array your array will consist of [11,12,12,122] only.

var array=[11,12,13,14,150];
console.log(array.length);
// 5
array.length=2;
console.log('now the array is',array);
// 11,12

Verify that a given argument is an array

function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}

Note that if the toString() method is overridden, you will not get the expected result using this trick.

Or use…

Array.isArray(obj); // its a new Array method

You could also use instanceof if you are not working with multiple frames. However, if you have many contexts, you will get the wrong result.

var myFrame = document.createElement('iframe');
document.body.appendChild(myFrame);

var myArray = window.frames[window.frames.length-1].Array;
var arr = new myArray(a,b,10); // [a,b,10]  

// instanceof will not work correctly, myArray loses his constructor 
// constructor is not shared between frames
arr instanceof Array; // false

I hope you learned at least something new from this list.
if you learned something from this list let me know in the comment section.😊😊

Did you find this article valuable?

Support ramu k by becoming a sponsor. Any amount is appreciated!

Β