15 ‘Hacks’ In JavaScript
Enjoy working with these simple wow JavaScript hacks.
Learning JavaScript language is easy but using it to develop an interactive web interface requires specific tricks and techniques. Thus, to facilitate you to use this programming language easily, I had brought a list of wow hacks that will help you optimize the performance, speed and save time while development of the website.
1) Async/ await with destructing:
It’s simply wonderful how the Array Destructing can offer so many functions. If you wish to make a complex flow much simpler, just combine array destruction with async/await and see what it does!
Use this:
const [user, account] = await Promise.all([
fetch('/user'),
fetch('/account')
])
2) Use ‘!!’ Operator to convert to boolean:
This (!!) is known as the double negation operator in the JavaScript language. The programmers can use it to find out whether a variable exists or has a valid value to be considered as true value or not. Thus, use a simple ‘!!variable’. This can convert the data automatically to a boolean which will come back as false if it showcases any of these values: 0,””, null, NaN, or undefined. In an otherwise case, it will come back as true. The hack is as follows:
function Account(cash) {this.cash =cashthis.hasMoney = !!cash;}var account = new Account(100.50);console.log(account.cash); // 100.50console.log(account.hasMoney); // truevar emptyAccount = new Account(0);console.log(emptyAccount.cash); // 0console.log(emptyaccount.hasMoney); // fasle
In the above-mentioned case, if the value of account.cash is greater than zero, the account.hasMoney will be considered true. Try it out yourself and see how well it works!
3) Swap variables:
You can make this happens by using the array destruction to swap the values. Use this code to do it:
let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world// Yes, it's magic
4) Use the + operator to convert to numbers:
At number four, we have a very simple yet magical hack that works with string numbers. If not, then it will return as NaN that indicates being not a number.
function toNumber( strNumber) {return +strNumber;}console.log(toNumber( “1234”)); // 1234console.log(toNumber(“ABC”)); // NaN
You can use this magical hack with dates too. For the dates, it goes as follows:
console.log(+new Date( )) // 1461288164385
5) Short-circuit conditionals:
Are you willing to shorten the code? Using shortcuts can save time and speed up the operation. Thus, if you see such a code somewhere
If(connected){Login()}
You can combine the variables and a function with the help of && (AND operator) to shorten the code. The above code will look as below:
connected &&login();
Another code can also be used:
User&&user.login();
6) Debugging hack:
If you use console.log to debug, you’ll be amazed by this hack. Here you go:
console.log({ a, b, c })// outputs this nice object:
// {
// a: 5,
// b: 6,
// c: 7
// }
7) How to detect properties in an object with a hack?
The answer to this very question is given below. It is used to check if an attribute exists or not. It helps by preventing to run undefined functions or attributes.
An example will help you understand in a better way. Say you need a code that is compatible with the old internet explorer 6 version and you want to use document.querySelector() to get some of the elements by their ids. But, in the latest browser this function does not exist and so you can use the ‘in’ operator to check the earlier existence of the function.
if (‘querySelector’ in document) {document.querySelector(“#id”);} else {Document.get Element ById(“id”);}
This states that if there is no ‘querySelector’ function in the document object, the document.getElementById function will be used as a fallback.
8) One-liners:
The Syntax is quite compact for the array operations
// Find max value
const max = (arr) => Math.max(...arr);
max([123, 321, 32]) // outputs: 321// Sum array
const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10
9) Array concatenation:
Use the concat in place of the spread operator:
one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']// Old way #1
const result = one.concat(two, three)// Old way #2
const result = [].concat(one, two, three)// New
const result = [...one, ...two, ...three]
10) Array filter usage:
If you are looking for a hack to save time and omit the multiple lines of code, then array filter code is the one for you! Use this to filter out the desired elements from the array pool. With this process, you’ll create an array full of all array elements that pass a test. For the non-required elements, you can create a callback function.
For example:
schema = ["hi","ihaveboyfriend",null, null, "goodbye"]schema = schema.filter(function(n) { return n });Output: ["hi","ihaveboyfriend", "goodbye"]
11) Get your floating number ensuring good performance:
The micro-optimization in the code is what boosts the performance and helps eliminate decimals using “~~” instead of math.ceil, math.floor, and math.round.
Thus, replace math.round(math.random*100)
with ~~ (math.random*100)
12) Array elements are deleted using splice:
How does this help? Well, to tell you the truth, it is the best JS code used for speed optimization. It saves the some of the “null/ undefined space” in the code. If you use delete instead of the splice, the object property would be deleted without the arrays reindex or length update.
The sample for you:
myArray = ["a", "b", "c", "d"] myArray.splice(0, 2) ["a", "b"] Result: myArray ["c", "d"]
13) Get the last item in the array:
If you want to cut the arrays, you can set the begin and end arguments like Array.prototupe.slice(begin, end). Not setting the end argument means that the function will automatically go for the max value for the array. This function also accepts the negative values. If you set a negative number as begin an argument, you will obtain the last element from the array.
It is as follows:
var array= [1, 2, 3, 4, 5, 6];console.log(array. Slice(-1)); // [6]console.log(array. Slice(-2)); // [5, 6]console.log(array. Slice(-3)); // [4, 5, 6]
14) Named parameters:
The developers can use this code hack to make the function and function calls more readable with the help of destructuring. The hack is as follows:
const getStuffNotBad = (id, force, verbose) => {
...do stuff
}
const getStuffAwesome = ({ id, name, force, verbose }) => {
...do stuff
}// Somewhere else in the codebase... WTF is true, true?
getStuffNotBad(150, true, true)// Somewhere else in the codebase... I ? JS!!!
getStuffAwesome({ id: 150, force: true, verbose: true })
15) Cloning:
Enjoy the ease of cloning arrays and objects with ease. Just keep in mind that it produces a shallow clone.
const obj = { ...oldObj }
const arr = [ ...oldArr ]
Conclusion:
With this, your stock of having cool and simple hacks for the JavaScript programming is now full. You can place these codes and functions in various places and enjoy the benefit of enhanced performance and good speed.
Reference