Contents
Like every other programming language, JavaScript has dozens of tricks to perform both easy and difficult tasks. Some tips are widely known while others are enough to blow your mind. In this article, we will go over 7 Javascript tips that you can start practicing and using after you finish reading this article.
1. Get Unique Values in Array
Solving duplicate array elements using Set.
var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]
2. Array and Boolean
You need to filter falsy values (0, undefined, null, false, etc.) from an array? You may not know this trick:
myArray
.map(item => {
// ...
})
// Get rid of bad values
.filter(Boolean);
3. Create Empty Objects
Of course, you can also create with {}. But you know the object just created that way still has the object hasOwnProperty, proto of that.
let obj = Object.create({});
// obj.__proto__ === {}
// obj.hasOwnProperty === function
and new tricks.
let dict = Object.create(null);
// dict.__proto__ === "undefined"
// No object properties exist until you add them
4. Merge Objects
You can never avoid merging objects in your developer life, so there are tricks for Javascript developer to achieve that.
Using spread syntax:
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 " ,
}
* /
5. Require Function Parameters
Setting default values for function arguments is a great addition to JavaScript, but see this tip to ask for values passed to 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' );
6. Get Query String Parameters
// 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"
JavaScript has changed a lot over the years, but my favorite part of JavaScript today is the speed at which the language is being improved. Although JavaScript changes, we still need to use some good tips;
Keep these tips in your toolbox when you need them!
Discussion about this post