This article consists of intermediate-level JavaScript tips and tricks. It will also guide you through some tricks that are effective in coding competitions, such as Code Golf. By the end of this article, you should be able to figure out the differences between these suggestions and when to use them yourself. They differ based on those to use in competitions, and those that make you more efficient in your day-to-day coding.
Converting to Boolean is a type conversion. If you don’t define the values, JavaScript will treat your values as true or false. This is normal with regular Boolean values. Unless you define a value, all the values will be true in JavaScript. With the exception of 0, "", null, undefined, NaN, and false which themselves are false. Switching between the true and false values is no big deal. All you have to do is use the negative operator “!”, which besides switching, also transforms your type to a Boolean type.
{% code-block language="js" %}
const isTrue = !0;
const isFalse = !1; //isFalse=!!0
console.log("The result will be true: "+isTrue);
console.log("Type of true is: ", typeof true);
{% code-block-end %}
Usually, you only define “false” value as !1 during a time-based coding competition. Yet, such conversions are also applicable in conditional statements.
Converting to a string is another type conversion. Here’s how you convert your values in numbers to strings:
{% code-block language="js" %}
const value = 1 + "";
console.log("Value ofter converting to string: "+value);
console.log("Type of value is: ", typeof value);
{% code-block-end %}
Here we used the concatenation operator “+”. We could have used an empty set of double-quotes as well. But with the concatenation operator, our number transformed into a string very quickly.
Converting a string into a number is yet another type conversion. The trick here is the opposite of what we did in the previous one (converting to a string). All you need to do here is use the concatenation operator “+” as shown below:
{% code-block language="js" %}
let int = "10";
int = +int
console.log("Value of int: "+ int);
console.log("Type of value is: ", typeof int);
{% code-block-end %}
Using the same method, you may also convert Booleans to numbers as done below:
{% code-block language="js" %}
console.log("+true to number: " + +true);
console.log("+false to number: " + +false);
{% code-block-end %}
You might be using “+” as the concatenation operator instead of another operator. But, in such cases you would need to return an integer, not a float.
With ES7 made available, we now have the ease to use our exponentiation operator “**”. This is a time-saving tool, or shorthand for powers, as it is much faster than using the Math.pow(2, 3) method. Here’s how you will apply this:
{% code-block language="js" %}
console.log("2 ** 3: "+ 2 ** 3);
{% code-block-end %}
You also want to ensure that you aren’t mixing this up with the symbol “^”. This symbol is usually used to represent exponents. However, in JavaScript, it represents your bitwise XOR operator. If ES7 wasn’t there, you could use shorthand dealing with powers, with a base of 2, as done in the example below:
{% code-block language="js" %}
console.log("Math.pow(2,3): ", Math.pow(2,3));
{% code-block-end %}
This type of conversion is an operational or type conversion. To convert a float all you need to do is to apply Math.floor() , Math.ceil() or Math.round(). Since we are here to make your life easier though, it’s fastest to do this using the bitwise OR operator “|”. Here’s how it’s done:
{% code-block language="js" %}
console.log("24.9 | 0: ", 24.9 | 0);//24
console.log("-24.9 | 0: ", -24.9 | 0);//24
{% code-block-end %}
Keep in mind that the behavior of your bitwise OR operator “|” may differ from your expectations. It may differ based on positive or negative numbers. Thus, you will want to be sure about them before using the bitwise OR operator in JavaScript.
When using the bitwise OR operator, if your n is positive, n | 0 rounds down. The opposite will happen if n is negative, resulting in rounding up. You can also use Tildes “~~” for the same purpose of rounding. This operation also removes large numbers of digits from the end of an integer. This makes your life easier as you can convert your integers as shown below:
{% code-block language="js" %}
console.log("27433/100 | 0: ", 27433/100 | 0);//274
{% code-block-end %}
Earlier you had to be more cautious as you were comparing value by value. In doing so, you had to ensure that each value and position was being taken as desired. Usually, you would have used the For Loop to perform this task. Here’s an easier, simpler, and faster way to do this:
{% code-block language="js" %}
const hasSameElements = (a, b) => {
return a.length === b.length && a.every((v,i) => v===b[i])
}
console.log("hasSameElements([1,2],[2,3]): ", hasSameElements([1,2],[2,3]));//false
console.log("hasSameElements([1,2],[1,2]): ", hasSameElements([1,2],[1,2]));//true
{% code-block-end %}
Above we first ensured that the length is equal. If it isn’t, then it will return false. We used a.every() to check every array for falseness. However, note that you can’t perform this trick for a nested array.
If you have a mixture array with empty and non-empty values, you need to get rid of those empty values. Here’s a time-saving way to do that:
{% code-block language="js" %}
const arr = [0,1,2,null,undefined,"",false];
const nonEmptyValues = arr.filter(Boolean);
console.log("nonEmptyValues: ", nonEmptyValues); //[1, 2]
{% code-block-end %}
Not only are your empty values eliminated this way, but you also removed the zeros and false values. This is something that you might want to avoid in a few cases.
Now, we will use the hasEmptyVals command as shown below. Note that if your array consists of some empty values, instead of a “complete” filter, “some is used”. So the output will let you know whether your array has empty values or not, which is something useful to check.
{% code-block language="js" %}
const arr = [0,1,2,null,undefined,"",false];
const hasEmptyValues = arr.some(Boolean);
console.log("hasEmptyValues: ", hasEmptyValues); // true
{% code-block-end %}
You can also check if each value is empty by replacing “some” with “every”.
{% code-block language="js" %}
const arr = [0,1,2,null,undefined,"",false];
const hasEmptyEveryValues = arr.every(Boolean);
console.log("hasEmptyEveryValues: ", hasEmptyEveryValues); // false
{% code-block-end %}
The slice() array way of getting your Last Item(s) in an Array can take negative integers. If you provide the values from the end, rather than the beginning, it will take them from the end too. Here’s our tip for doing that:
{% code-block language="js" %}
let array = [1, 2, 3, 4 ,5 ,6 ,7, 8, 9];
console.log("array.slice(-1): ",array.slice(-1));//[9]
console.log("array.slice(-2): ",array.slice(-2));//[8, 9]
console.log("array.slice(-3): ",array.slice(-3));//[7, 8, 9]
{% code-block-end %}
You might have used splice() method for removing values from the end of an array. However, here’s a faster and more efficient way to do that:
{% code-block language="js" %}
let array = [1, 2, 3, 4 ,5 ,6 ,7, 8, 9];
array.length=4;
console.log("Array after Truncating: ", array);// [ 1, 2, 3, 4 ]
{% code-block-end %}
Above, we re-defined the length of our array property knowing its size. Although this method is efficient enough, the slice() method is even faster than this.
{% code-block language="js" %}
let array = [1, 2, 3, 4 ,5 ,6 ,7, 8, 9];
array = array.slice(0,4);
console.log("Array after Truncating: ", array);// [ 1, 2, 3, 4 ]
{% code-block-end %}
Before you go and nail your coding competition, here’s your final tip. This tip will help you check the performance of your code in JavaScript.
Do the below to check the performance of your code in JavaScript:
{% code-block language="js" %}
let startAt = performance.now();
for (let k=0; k<30000; k++){
console.log(k);
}
let endAt = performance.now();
console.log("Performance time for running the all tricks is ", endAt-startAt, " miliseconds")
{% code-block-end %}
Note that this doesn’t run in Node.Js, so you will have to go to the browser to run this. If you are wondering why this trick isn’t working on your VS code, you need to run it on your browser.
There you have it, our 10 JavaScript tips and tricks! As you can see these tips and tricks will help you speed things up when coding, and optimize your code. I hope you learned something new, and will apply these in your daily coding. After learning these tips and tricks you should be able to perform better in your job or in development world. For a better understanding of these tips, you can explore the source code on GitHub.
Happy Coding!
Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.