7 Useful JavaScript Tricks

7 Useful JavaScript Tricks

In this post I will share 7 JavaScript tricks you can start using today!

Just like every other programming language, JavaScript has dozens of tricks to accomplish both easy and difficult tasks. Some tricks are widely known while others are enough to blow your mind. Let's have a look at seven JavaScript tricks you can start using today!

Get Unique Values of an Array

Getting an array of unique values is probably easier than you think:

var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]

I love the mixture of rest expression and Set!

Array and Boolean

Ever need to filter falsy values (0, undefined, null, false, etc.) out of an array? You may not have known this trick:

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

Just pass Boolean and all those falsy value go away!

Create Empty Objects

Sure you can create an object that seems empty with {}, but that object still has a __proto__ and the usual hasOwnProperty and other object methods. There is a way, however, to [create a pure "dictionary" object](https://davidwalsh.name/object-create-null "create a pure "dictionary" object"):

let dict = Object.create(null);

// dict.__proto__ === "undefined"
// No object properties exist until you add them

There are absolutely no keys or methods on that object that you don't put there!

Merge Objects

The need to merge multiple objects in JavaScript has been around forever, especially as we started creating classes and widgets with options:

const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };

const summary = {...person, ...tools, ...attributes};
/*
Object {
  "computer": "Mac",
  "editor": "Atom",
  "eyes": "Blue",
  "gender": "Male",
  "hair": "Brown",
  "handsomeness": "Extreme",
  "name": "David Walsh",
}
*/

Those three dots made the task so much easier!

Require Function Parameters

Being able to set default values for function arguments was an awesome addition to JavaScript, but check out this trick for requiring values be passed for a given argument:

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// This will throw an error because no name is provided
hello();

// This will also throw an error
hello(undefined);

// These are good!
hello(null);
hello('David');

That's some next level validation and JavaScript usage!

Destructuring Aliases

Destructuring is a very welcomed addition to JavaScript but sometimes we'd prefer to refer to those properties by another name, so we can take advantage of aliases:

const obj = { x: 1 };

// Grabs obj.x as { x }
const { x } = obj;

// Grabs obj.x as { otherName }
const { x: otherName } = obj;

Useful for avoiding naming conflicts with existing variables!

Get Query String Parameters

For years we wrote gross regular expressions to get query string values but those days are gone -- enter the amazing [URLSearchParams](https://davidwalsh.name/query-string-javascript "URLSearchParams") API:

// Assuming "?post=1234&action=edit"

var 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"

Much easier than we used to fight with!

JavaScript has changed so much over the years but my favorite part of JavaScript these days is the velocity in language improvements we're seeing. Despite the changing dynamic of JavaScript, we still need to employ a few decent tricks; keep these tricks in your toolbox for when you need them!

What are your favorite JavaScript tricks?

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.