DEV Community

loading...

JavaScript Tricks - part 2

nashmeyah profile image Nashmeyah ・1 min read

Hi Guys! So I found a couple more JS tricks I wanted to share with you guys!

Length

When you want to resize an array and set it to 0 or erase your whole array maybe needing to start fresh. Here is a simple way you can do it.

let array = [1, 9, 42, 4, 90];  
console.log(array.length); // 5  

array.length = 4;  
console.log(array.length); // 4 -- it removes the last element  
console.log(array); // [1,9,42,4]

array.length = 0;  
console.log(array.length); // 0  -- we are at 0
console.log(array); // []
Enter fullscreen mode Exit fullscreen mode

Query String Params

I loved this one, reminded me of when I went crazy for days trying to get params data.

let urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "? 
post=1234&action=edit&active=1"
Enter fullscreen mode Exit fullscreen mode

Array, Boolean

Want to get rid of all the falsey values in an array, just pass Boolean to a .filter() method.

myArray
.map(item => {
    // ...
})
// Get rid of bad values
.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

Disclaimer! These are not tricks I figured out myself, social media is a wonderful place! Enjoy!

Discussion (0)

pic
Editor guide