By WalkingTree   April  02, 2020

Just like any other programming language, Javascript comes with many tips and tricks to ease the developer’s job by accomplishing difficult tasks. Let’s have a look at the five JavaScript tricks which you can start using today.

  • Every & Some

The every function shows whether all elements in an array pass a test.  If all elements in the array pass the test, true will be returned. If one of the elements in the array fails the test, false will be returned.

const random_numbers = [ 13, 2, 37, 18, 5 ] 
const more_random_numbers = [ 0, -1, 30, 22 ] 

const isPositive = (number) => { 
   return number > 0 } 

random_numbers.every(isPositive); // returns true more_random_numbers.every(isPositive); // returns false
  • Conditionally setting a variable

Conditionally setting up a variable is very easy and simple. Let’s take a look at an example. If the user sets a preferred timezone, we use that timezone. If the user doesn’t have a preferred timezone we use the default timezone, let’s say ‘America/New_York’.

const timezone = user.preferred_timezone || 'America/New_York'
  • Casting values in arrays

You can cast all the values in a single array by using a simple equation:

selected_values = selected_values.map(Number) // [ 1, 5, 8 ]

Or, you can also cast the values in a boolean:

selected_values = selected_values.map(Boolean)

  • Object Destruction

Destruction is an expression that helps in extracting data from arrays, objects, and maps. You can directly get the variables using the following syntax:

 const user = {
name: 'Frank',
age: 23,
gender: 'M',
member: false
}

const { name, age, gender, member } = user;
const user = {
name: 'Frank',
age: 23,
gender: 'M',
member: false
}
  • Better debugging using performance

Most developers are only aware of the standard console.log function for debugging the code. But the console function has many more features. It has a time and timeEnd function which can help in measuring performance. 

console.time('loop')

for (let i = 0; i < 10000; i++) { 
     // Do stuff here
} 

      console.timeEnd('loop')


 

Read on to know more about the tricks and best practices of JavaScript language.

Translate »