JavaScript Tricks - part 2
Nashmeyah
Posted on April 12, 2021
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); // []
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"
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);
Disclaimer! These are not tricks I figured out myself, social media is a wonderful place! Enjoy!
💖 💪 🙅 🚩
Nashmeyah
Posted on April 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.