When I began , I made a list of every time-saving trick that I found in other people’s code, on code challenge websites, and anywhere the tutorials I was using. learning JavaScript other than Each of these tricks accomplishes tasks that most developers need to do on a daily basis. Depending on your experience you might already know some of these tricks, while others will blow your mind. In this article, we’ll go over a list of tricks that will make you a better developer and supercharge your JavaScript skills. 1. Filter Unique Values The Set object type was introduced in ES6, and along with ..., the ‘spread’ operator, we can use it to create a new array with the unique values. only array = [ , , , , , , ] uniqueArray = [...new (array)]; .log(uniqueArray); const 1 1 2 3 5 5 1 const Set console // Result: [1, 2, 3, 5] Before ES6, isolating unique values would involve a lot more code than that! This trick works for arrays containing primitive types: , , , and . (If you had an array containing objects, functions or additional arrays, you’d need a different approach!) undefined null boolean string number 2. Every and some The and functions are functions that not all developers are familiar with. However, they can be very useful in certain situations. Let’s start with the function. You can use this function if you want to know whether all elements of an array pass a certain test. Essentially what this is doing is going through each element of the array and checking to see if they’re all true. every some every This might sound a little abstract to you, so let’s lets take a look at the following example. It’s not as complex as it sounds. random_numbers = [ , , , , ] more_random_numbers = [ , , , ] isPositive = { number > } random_numbers.every(isPositive); more_random_numbers.every(isPositive); const 13 2 37 18 5 const 0 -1 30 22 const ( ) => number return 0 // returns true // returns false The function returns a boolean. If all elements in the array pass the test, will be returned. If one of the elements in the array fails the test, will be returned. every true false You could also use an anonymous function as a tester function if you’d like to: random_numbers.every( { number > }) ( ) => number return 0 The function almost works exactly the same as the function. There’s only one major difference: the function tests whether at least one element in the array passes the test implemented. some every some If we take a look at the previous example and use the function instead of the function both arrays will return , since both arrays contain a positive number. some every true random_numbers = [ , , , , ] more_random_numbers = [ , , , ] isPositive = { number > } random_numbers.some(isPositive); more_random_numbers.some(isPositive); const 13 2 37 18 5 const 0 -1 30 22 const ( ) => number return 0 // returns true // returns true 3. Short-Circuit Evaluation The ternary operator is a quick way to write simple (and sometimes not-so-simple) conditional statements, like these: x > ? : ; x > ? (x > ? : ) : ; 100 'Above 100' 'Below 100' 100 200 'Above 200' 'Between 100-200' 'Below 100' But sometimes even the ternary operator is more complicated than necessary. Instead, we can use the ‘and’ and ‘or’ || logical operators to evaluate certain expressions in an even more concise way. This is often called ‘short-circuiting’ or ‘short-circuit evaluation’. && How It Works Let’s say we want to return just one of two or more options. Using will return the first or ‘falsy’ value. If every operand evaluates to , the last evaluated expression will be returned. && false true one = , two = , three = ; .log(one && two && three); .log( && ); let 1 2 3 console // Result: 3 console 0 null // Result: 0 Using || will return the first or ‘truthy’ value. If every operand evaluates to , the last evaluated expression will be returned. true false one = , two = , three = ; .log(one || two || three); .log( || ); let 1 2 3 console // Result: 1 console 0 null // Result: null Example 1 Let’s say we want to return the of a variable, but we don’t know the variable type. length We could use an statement to check that is an acceptable type, but this could get pretty longwinded. Short circuit evaluation allows us to do this instead: if/else foo (foo || []).length; return If the variable is truthy, it will be returned. Otherwise, the of the empty array will be returned: 0 . foo length Example 2 Have you ever had problems accessing a nested object property? You might not know if the object or one of the sub-properties exists, and this can cause frustrating errors. Let’s say we wanted to access a property called within , but is undefined until our program has successfully returned a fetch request. data this.state data Depending on where we use it, calling could prevent our app from running. To get around this, we could wrap it in a conditional: this.state.data ( .state.data) { .state.data; } { ; } if this return this else return 'Fetching Data' But that seems pretty repetitive. The ‘or’ operator provides a more concise solution: ( .state.data || ); return this 'Fetching Data' We can’t refactor the code above to use . The statement will return whether it is or not. This is because is ‘truthy’, and so the will always pass over it when it is listed first. && 'Fetching Data' && this.state.data this.state.data undefined 'Fetching Data' && A New Proposed Feature: Optional Chaining There is currently a proposal to allow ‘optional chaining’ when attempting to return a property deep in a tree-like structure. Under the proposal, the question mark symbol could be used to extract a property if it is not . ? only null For example, we could refactor our example above to , thus only returning if it is not . this.state.data?.() data null Or, if we were mainly concerned about whether was defined or not, we could return . state this.state?.data 4. Convert to Boolean Besides the regular boolean values and , JavaScript also treats all other values as either ‘truthy’ or ‘falsy’. true false Unless otherwise defined, all values in JavaScript are ‘truthy’ with the exception of , , , , and of course , which are ‘falsy’. 0 "" null undefined NaN false We can easily switch between true and false by using the negative operator ! , which will also convert the type to . "boolean" isTrue = ! ; isFalse = ! ; alsoFalse = !! ; .log(isTrue); .log( ); const 0 const 1 const 0 console // Result: true console typeof true // Result: "boolean" This kind of type conversion can be handy in conditional statements, although the only reason you’d choose to define as is if you were playing code golf! false !1 5. Conditionally setting a variable Conditionally setting a variable is both easy and makes your code look more elegant. There’s no need to write an if-statement when applying this trick — which personally is one of my favorite tricks in JavaScript. So how can you conditionally set a variable? timezone = user.preferred_timezone || const 'America/New_York' In the example above we check if the user has a preferred timezone. If the user has a preferred timezone, we use that timezone. If the user doesn’t have a preferred timezone we use the default timezone, which is . ‘America/New_York’ This code looks so much cleaner than when using an if-statement. timezone = (user.preferred_timezone) { timezone = user.preferred_timezone } let 'America/New_York' if Looks much cleaner, doesn’t it? 6. Convert to String To quickly convert a number to a string, we can use the concatenation operator + followed by an empty set of quotation marks . "" val = + ; .log(val); .log( val); const 1 "" console // Result: "1" console typeof // Result: "string" 7. Convert to Number The opposite can be quickly achieved using the addition operator . + int = ; int = +int; .log(int); .log( int); Result: let "15" console // Result: 15 console typeof "number" This may also be used to convert booleans to numbers, as below: .log(+ ); .log(+ ); console true // Return: 1 console false // Return: 0 There may be contexts where the will be interpreted as the concatenation operator rather than the addition operator. When that happens (and you want to return an integer, not a float) you can instead use two tildes: . + ~~ A tilde, known as the ‘bitwise NOT operator’, is an operator equivalent to . So, for example, is equal to . -n — 1 ~15 -16 Using two tildes in a row effectively negates the operation, because . In other words, equals . — ( — n — 1) — 1 = n + 1 — 1 = n ~ — 16 15 int = ~~ .log(int); .log( int); Result: const "15" console // Result: 15 console typeof "number" Though I can’t think of many use-cases, the bitwise NOT operator can also be used on booleans: and . ~true = -2 ~false = -1 8. Casting values in Arrays Sometimes you want to cast all values in an array. One of those occurrences could be when you’re using the triple equals operator to check whether a certain number exists in an array, for example. I lately ran into a problem where I had a multi-select. The HTML values of the select options were strings instead of integers, which makes sense. The array of selected values looked like this: selected_values = [ , , ] let '1' '5' '8' The problem was that I was checking if a certain integer existed in the array of the selected values. Without success. I used an intersect function that used the triple equals operator. And since ‘5’ !== 5 I had to find a solution. The prettiest solution, in my opinion, was to cast all values in the array to an integer. When trying to do this I stumbled upon a painfully simple, yet elegant, solution. selected_values = selected_values.map( ) Number // [ 1, 5, 8 ] Instead of casting all values to an integer, you could also cast all values in the array to a boolean by simply changing the argument of the map function. selected_values = selected_values.map( ) Boolean 9. Quick Powers Since ES7, it has been possible to use the exponentiation operator as a shorthand for powers, which is faster than writing . This is straightforward stuff, but it makes the list because not many tutorials have been updated to include this operator! ** Math.pow(2, 3) .log( ** ); console 2 3 // Result: 8 This shouldn’t be confused with the ^ symbol, commonly used to represent exponents, but which in JavaScript is the bitwise XOR operator. Before ES7, shorthand existed only for powers with base 2, using the bitwise left shift operator : << .pow( , n); << (n - ); **n; // The following expressions are equivalent: Math 2 2 1 2 For example, is equivalent to . 2 << 3 = 16 2 ** 4 = 16 10. Quick Float to Integer If you want to convert a float to an integer, you can use , or . But there is also a faster way to truncate a float to an integer using , the bitwise OR operator. Math.floor() Math.ceil() Math.round() | .log( | ); .log( | ); console 23.9 0 // Result: 23 console -23.9 0 // Result: -23 The behaviour of varies depending on whether you’re dealing with positive or negative numbers, so it’s best only to use this shortcut if you’re sure. | If is positive, effectively rounds down. If is negative, it effectively rounds up. To put it more accurately, this operation removes whatever comes after the decimal point, truncating a float to an integer. n n | 0 n You can get the same rounding effect by using , as above, and in fact bitwise operator would force a float to an integer. The reasons these particular operations work is that — once forced to an integer — the value is left unchanged. ~~ any Remove Final Digits The bitwise OR operator can also be used to remove any amount of digits from the end of an integer. This means we don’t have to use code like this to convert between types: str = ; (str.substring( , str.length - )); let "1553" Number 0 1 Instead, the bitwise OR operator allows us to write: .log( / | ) .log( / | ) .log( / | ) console 1553 10 0 // Result: 155 console 1553 100 0 // Result: 15 console 1553 1000 0 // Result: 1 11. Object destructuring Once you know about object destructuring it’s probably something that you’re going to be using every single day. But what exactly is destructuring? Destructuring is a JavaScript expression that allows you to extract data from arrays, objects, maps and sets into their own variable. It allows you to extract properties from an object or items from an array, multiple at a time. Let’s take a look at the following example where we have a user object. If you want to store the user’s name in a variable you have to assign it to a variable on a new line. And if you want to store the gender as well in a variable, you’d have to do the same again. user = { : , : , : , : } name = user.name gender = user.gender const name 'Frank' age 23 gender 'M' member false const const With destructuring you can directly get the variables for the object’s properties using the following syntax: { name, age, gender, member } = user; .log(name) .log(age) .log(gender) .log(member) const console // Frank console // 23 console // M console // false 12. Automatic Binding in Classes We can use ES6 arrow notation in class methods, and by doing so binding is implied. This will often save several lines of code in our class constructor, and we can happily say goodbye to repetitive expressions such as ! this.myMethod = this.myMethod.bind(_this_) React, { Component } React; { (props) { (props); .state = {}; }myMethod = { }render() { ( <div> {this.myMethod()} </div> import from export default class App extends Compononent constructor super this => () // This method is bound implicitly! return <> ) } }; </> 13. Better debugging using performance One of the things that you’ll do a lot as a developer is debugging. However, debugging is more than just printing out a bunch of log messages in your console using . console.log Did you know that the console object has a great way to analyze performance of pieces of your code? However, most developers only know about the standard way of debugging their code. console.log The console object has way more helpful functions. It has a and function that can help you analyzing performance. It works really simple. time timeEnd In front of the code that you want to test, you call the function. This function has one argument, which takes a string that describes what you want to analyze. At the end of the code that you want to test, you call the function. You give this function the same string as the first parameter. You’ll then see the time it took to run the code in your console. console.time console.timeEnd .time( ) ( i = ; i < ; i++) { } .timeEnd( ) console 'loop' for let 0 10000 // Do stuff here console 'loop' 14. Truncate an Array Arrays If you want to remove values from the end of an array destructively, there’s are faster alternatives than using . splice() For example, if you know the size of your original array, you can re-define its length property, like so: array = [ , , , , , , , , , ]; array.length = ; .log(array); let 0 1 2 3 4 5 6 7 8 9 4 console // Result: [0, 1, 2, 3] This is a particularly concise solution. However, I have found the run-time of the method to be even faster. If speed is your main goal, consider using something like this: slice() array = [ , , , , , , , , , ]; array = array.slice( , ); .log(array); let 0 1 2 3 4 5 6 7 8 9 0 4 console // Result: [0, 1, 2, 3] 15. Get the Last Item(s) in an Array Arrays The array method can take negative integers, and if provided it will take values from the end of the array rather than the beginning. slice() array = [ , , , , , , , , , ]; .log(array.slice( )); .log(array.slice( )); .log(array.slice( )); let 0 1 2 3 4 5 6 7 8 9 console -1 // Result: [9] console -2 // Result: [8, 9] console -3 // Result: [7, 8, 9] 16. Format JSON Code JSON Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you? The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value. The space value takes an integer for the number of spaces you want or a string (such as '\t' to insert tabs), and it can make it a lot easier to read fetched JSON data. .log( .stringify({ : , : }, , )); console JSON alpha 'A' beta 'B' null '\t' // Result: // '{ // "alpha": A, // "beta": B // }' Overall, I hope you found these tips as useful as I did when I first discovered them. Got any JavaScript tricks of your own? I’d love to read them in the comments below! Originally published on Morioh.com .