My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Post hidden from Hashnode

Posts can be hidden from Hashnode network for various reasons. Contact the moderators for more details.

5 Neat JavaScript tricks for better programming.

Vimal Tiwari's photo
Vimal Tiwari
·Nov 10, 2018

1. Clearing or truncating an array - Change the length property.

const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined

2. Switch with ranges

function getWaterState(tempInCelsius) {
let state;

switch (true) {
case (tempInCelsius <= 0): 
state = 'Solid';
break;
case (tempInCelsius > 0 && tempInCelsius < 100): 
state = 'Liquid';
break;
default: 
state = 'Gas';
}
return state;
}

3. Creating pure objects

const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined

4. Formatting JSON code

JSON.stringify can do more than simply stringify an object. You can also beautify your JSON output with it:

const obj = { 
foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } } 
};
// The third parameter is the number of spaces used to 
// beautify the JSON output.
JSON.stringify(obj, null, 4); 
// =>"{
// => "foo": {
// => "bar": [
// => 11,
// => 22,
// => 33,
// => 44
// => ],
// => "baz": {
// => "bing": true,
// => "boom": "Hello"
// => }
// => }
// =>}"

5. Removing duplicate items from an array - using SET

const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]

I hope these neat little tricks help you write better and more beautiful JavaScript.

Src : medium