9 Super Useful Tricks for JavaScript Developers

Useful Javascript tricks you might have missed.

As we all know, JavaScript has been changing rapidly. With the new ES2020, there are many awesome features introduced that you might want to checkout. To be honest, you can write code in many different ways. They might achieve the same goal, but some are shorter and much clearer. You can use some small tricks to make your code cleaner and clearer. Here is a list of useful tricks for JavaScript developers that will definitely help you one day.

Method Parameter Validation

JavaScript allows you to set default values for your parameters. Using this, we can implement a neat trick to validate your method parameters.

const isRequired = () => { throw new Error('param is required'); };
const print = (num = isRequired()) => { console.log(`printing ${num}`) };
print(2);//printing 2
print()// error
print(null)//printing null

Neat, isn’t it?

Format JSON Code

You would be quite familiar with JSON.stringify by now. But are you aware that you can format your output by using stringify ? It is quite simple actually.

The stringify method takes three inputs. The value , replacer , and space. The latter two are optional parameters. That is why we did not use them before. To indent our JSON, we must use the space parameter.

console.log(JSON.stringify({name:"John",Age:23},null,'\t'));
>>> 
{
"name": "John",
"Age": 23
}

Here’s a React component I’ve published to Bit. Feel free to play with the stringify example.

https://bit.dev/eden/stringify-components/display-results

Get Unique Values From An Array

Getting unique values from an array required us to use the filter method to filter out the repetitive values. But with the new Set native object, things are really smooth and easy.

let uniqueArray = [...new Set([1, 2, 3, 3,3,"school","school",'ball',false,false,true,true])];
>>> [1, 2, 3, "school", "ball", false, true]

Removing Falsy Values From Arrays

There can be instances where you might want to remove falsy values from an array. Falsy values are values in JavaScript which evaluate to FALSE. There are only six falsy values in JavaScript and they are,

  • undefined
  • null
  • NaN
  • 0
  • “” (empty string)
  • false

The easiest way to filter out these falsy values is to use the below function.

myArray
.filter(Boolean);

If you want to make some modifications to your array and then filter the new array, you can try something like this. Keep in mind that the original myArray remains unchanged.

myArray
.map(item => {
// Do your changes and return the new item
})
.filter(Boolean);

Merge Several Objects Together

I have had several instances where I had the need to merge two or more classes, and this was my go-to approach.

const user = { 
name: 'John Ludwig',
gender: 'Male'
};
const college = { 
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = { 
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
const summary = {...user, ...college, ...skills};

The three dots are also called the spread operator in JavaScript. You can read more of their uses over here.

Sort Number Arrays

JavaScript arrays come with a built-in sort method. This sort method converts the array elements into strings and performs a lexicographical sort on it by default. This can cause issues when sorting number arrays. Hence here is a simple solution to overcome this problem.

[0,10,4,9,123,54,1].sort((a,b) => a-b);
>>> [0, 1, 4, 9, 10, 54, 123]

You are providing a function to compare two elements in the number array to the sort method. This function helps us the receive the correct output.

Disable Right Click

You might ever want to stop your users from right-clicking on your web page. Although this is very rare, there can be several instances where you would need this feature.

<body oncontextmenu="return false">
<div></div>
</body>

This simple snippet would disable right click for your users.

Destructuring with Aliases

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Rather than sticking with the existing object variable, we can rename them to our own preference.

const object = { number: 10 };
// Grabbing number
const { number } = object;
// Grabbing number and renaming it as otherNumber
const { number: otherNumber } = object;
console.log(otherNumber); //10

Get the Last Items in an Array

If you want to take the elements from the end of the array, you can use the slice method with negative integers.

let array = [0, 1, 2, 3, 4, 5, 6, 7] 
console.log(array.slice(-1));
>>>[7]
console.log(array.slice(-2));
>>>[6, 7]
console.log(array.slice(-3));
>>>[5, 6, 7]

Build & share React components with Bit

Bit is an extensible tool that lets you create truly modular applications with independently authored, versioned, and maintained components.

Use it to build modular apps & design systems, author and deliver micro frontends, or share components between applications.

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Bit: The platform for the modular web

Related Stories

Resources
Blog post by David Walsh
Blog post by Bret Cameron
Blog post by Ngninja


9 Super Useful Tricks for JavaScript Developers was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Mike Chen

Useful Javascript tricks you might have missed.

As we all know, JavaScript has been changing rapidly. With the new ES2020, there are many awesome features introduced that you might want to checkout. To be honest, you can write code in many different ways. They might achieve the same goal, but some are shorter and much clearer. You can use some small tricks to make your code cleaner and clearer. Here is a list of useful tricks for JavaScript developers that will definitely help you one day.

Method Parameter Validation

JavaScript allows you to set default values for your parameters. Using this, we can implement a neat trick to validate your method parameters.

const isRequired = () => { throw new Error('param is required'); };
const print = (num = isRequired()) => { console.log(`printing ${num}`) };
print(2);//printing 2
print()// error
print(null)//printing null

Neat, isn’t it?

Format JSON Code

You would be quite familiar with JSON.stringify by now. But are you aware that you can format your output by using stringify ? It is quite simple actually.

The stringify method takes three inputs. The value , replacer , and space. The latter two are optional parameters. That is why we did not use them before. To indent our JSON, we must use the space parameter.

console.log(JSON.stringify({name:"John",Age:23},null,'\t'));
>>> 
{
"name": "John",
"Age": 23
}

Here’s a React component I’ve published to Bit. Feel free to play with the stringify example.

https://bit.dev/eden/stringify-components/display-results

Get Unique Values From An Array

Getting unique values from an array required us to use the filter method to filter out the repetitive values. But with the new Set native object, things are really smooth and easy.

let uniqueArray = [...new Set([1, 2, 3, 3,3,"school","school",'ball',false,false,true,true])];
>>> [1, 2, 3, "school", "ball", false, true]

Removing Falsy Values From Arrays

There can be instances where you might want to remove falsy values from an array. Falsy values are values in JavaScript which evaluate to FALSE. There are only six falsy values in JavaScript and they are,

  • undefined
  • null
  • NaN
  • 0
  • “” (empty string)
  • false

The easiest way to filter out these falsy values is to use the below function.

myArray
.filter(Boolean);

If you want to make some modifications to your array and then filter the new array, you can try something like this. Keep in mind that the original myArray remains unchanged.

myArray
.map(item => {
// Do your changes and return the new item
})
.filter(Boolean);

Merge Several Objects Together

I have had several instances where I had the need to merge two or more classes, and this was my go-to approach.

const user = { 
name: 'John Ludwig',
gender: 'Male'
};
const college = { 
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = { 
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
const summary = {...user, ...college, ...skills};

The three dots are also called the spread operator in JavaScript. You can read more of their uses over here.

Sort Number Arrays

JavaScript arrays come with a built-in sort method. This sort method converts the array elements into strings and performs a lexicographical sort on it by default. This can cause issues when sorting number arrays. Hence here is a simple solution to overcome this problem.

[0,10,4,9,123,54,1].sort((a,b) => a-b);
>>> [0, 1, 4, 9, 10, 54, 123]

You are providing a function to compare two elements in the number array to the sort method. This function helps us the receive the correct output.

Disable Right Click

You might ever want to stop your users from right-clicking on your web page. Although this is very rare, there can be several instances where you would need this feature.

<body oncontextmenu="return false">
<div></div>
</body>

This simple snippet would disable right click for your users.

Destructuring with Aliases

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Rather than sticking with the existing object variable, we can rename them to our own preference.

const object = { number: 10 };
// Grabbing number
const { number } = object;
// Grabbing number and renaming it as otherNumber
const { number: otherNumber } = object;
console.log(otherNumber); //10

Get the Last Items in an Array

If you want to take the elements from the end of the array, you can use the slice method with negative integers.

let array = [0, 1, 2, 3, 4, 5, 6, 7] 
console.log(array.slice(-1));
>>>[7]
console.log(array.slice(-2));
>>>[6, 7]
console.log(array.slice(-3));
>>>[5, 6, 7]

Build & share React components with Bit

Bit is an extensible tool that lets you create truly modular applications with independently authored, versioned, and maintained components.

Use it to build modular apps & design systems, author and deliver micro frontends, or share components between applications.

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Bit: The platform for the modular web

Related Stories

Resources
Blog post by David Walsh
Blog post by Bret Cameron
Blog post by Ngninja


9 Super Useful Tricks for JavaScript Developers was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Mike Chen


Print Share Comment Cite Upload Translate Updates
APA

Mike Chen | Sciencx (2021-08-23T20:42:59+00:00) 9 Super Useful Tricks for JavaScript Developers. Retrieved from https://www.scien.cx/2021/08/23/9-super-useful-tricks-for-javascript-developers/

MLA
" » 9 Super Useful Tricks for JavaScript Developers." Mike Chen | Sciencx - Monday August 23, 2021, https://www.scien.cx/2021/08/23/9-super-useful-tricks-for-javascript-developers/
HARVARD
Mike Chen | Sciencx Monday August 23, 2021 » 9 Super Useful Tricks for JavaScript Developers., viewed ,<https://www.scien.cx/2021/08/23/9-super-useful-tricks-for-javascript-developers/>
VANCOUVER
Mike Chen | Sciencx - » 9 Super Useful Tricks for JavaScript Developers. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/23/9-super-useful-tricks-for-javascript-developers/
CHICAGO
" » 9 Super Useful Tricks for JavaScript Developers." Mike Chen | Sciencx - Accessed . https://www.scien.cx/2021/08/23/9-super-useful-tricks-for-javascript-developers/
IEEE
" » 9 Super Useful Tricks for JavaScript Developers." Mike Chen | Sciencx [Online]. Available: https://www.scien.cx/2021/08/23/9-super-useful-tricks-for-javascript-developers/. [Accessed: ]
rf:citation
» 9 Super Useful Tricks for JavaScript Developers | Mike Chen | Sciencx | https://www.scien.cx/2021/08/23/9-super-useful-tricks-for-javascript-developers/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.