DEV Community

Sobhan Dash
Sobhan Dash

Posted on

Become a Javascript Magician with these tricks!

Do you know how to perform tricks?
Maybe a card trick or something that involves ease of work or sleight of hand?

Being a developer means we get to work with lots of code. More often than not, it gets tedious.
How do we solve them? Easy!

We use certain tricks that simplify complex code and bring more efficient work to the table.

I've brought some tricks in JavaScript which will do exactly that.

Get Unique items from an array

You might know about the spread operator.
Do you that we can use it to create an array with no duplicate values from the original array?

const arr = ["dogs", "cats", 1, 1, "lion", "lion"]
console.log(arr)
//OP: ["dogs", "cats", 1, 1, "lion", "lion"]

const uniqueArr = [... new Set(arr)]
console.log(uniqueArr)
//OP: ["dogs", "cats", 1, "lion"] 
Enter fullscreen mode Exit fullscreen mode

Easy conversion to a number

Any JavaScript beginner would know, that by adding a number and a string we get a string as output.
We can solve it by using a + operator in front of the string to convert it to a number.

const n1  = 10
const n2 = "20"
const total = n1 + n2
console.log(total)
//OP: 1020

//Fixed Code
const newTotal = n1 + +n2
console.log(newTotal)
//OP: 30
Enter fullscreen mode Exit fullscreen mode

Easy conversion to a string

Similar to the above one, we can convert a number to a string by concatenating empty quotes after the number.

const num  = 10
console.log(typeof num)
//OP:  number

const numStr  = 10 + ""
console.log(typeof numStr)
//OP:  string
Enter fullscreen mode Exit fullscreen mode

Avoid if-else statements

There is a powerful operator known as the ternary operator.
The simplicity of the operator makes our code short and sweet.

const aboolean = false
if(aboolean) {
    console.log("It is True!")
} else{
    console.log("It is False!")
}
//OP: It is False!

// Replacing with the ternary operator
aboolean ? console.log("It is True!") : console.log("It is False!")
Enter fullscreen mode Exit fullscreen mode

Get Max, Min, and Total from an array

The last trick is the "reduce" function.
We use the ternary operator here too to get the values.

const nums = [1, 10, 6, 3, -2, 8]
const maxVal = nums.reduce((a, b) => {
    return a > b ? a : b    
})
console.log(maxVal)
// 10

const minVal = nums.reduce((a, b) => {
    return a < b ? a : b    
})
console.log(minVal)
// -2

const totalVal = nums.reduce((a, b) => {
    return a + b    
})
console.log(totalVal)
// 26
Enter fullscreen mode Exit fullscreen mode

So that's it!
These are some tricks that I discovered recently. I'll use these from now onwards.
Let me know if you know about some more like these and if you follow these tricks on a day-to-day basis!

Discussion (6)

Collapse
frankwisniewski profile image
Frank Wisniewski
  const aboolean = false
  console.log (`It is ${aboolean?"True":"False"}!`)
  //max
  const nums = [1, 10, 6, 3, -2, 8]
  console.log(Math.max(...nums))
  //min
  console.log(Math.min(...nums))
Enter fullscreen mode Exit fullscreen mode
Collapse
sobhandash profile image
Sobhan Dash Author

Even cooler way to get the work done!🙌

Collapse
dwd profile image
Dave Cridland

Converting to a number and string that way is risky, because you're using implicit conversions.

Instead, you can convert a number to a string by using string interpolation:

const stringNumber = `${number}`
Enter fullscreen mode Exit fullscreen mode

Converting to a number can be done two ways - you can use Number or parseInt, depending on the behaviour you need when it's not quite a number:

const numberString = Number('20') // 20
const numberWang = parseInt('20 cows') // 20
Enter fullscreen mode Exit fullscreen mode
Collapse
sobhandash profile image
Sobhan Dash Author

True! I was trying to find other ways to do the conversations. These are the better options clearly.

Collapse
curiousdev profile image
CuriousDev

Thanks, but for the unique items it most likely only works for simple data types, like numbers and strings. For complex objects you still should write a function, which would do the comparison in order to know, which objects are supposed to be the same. Maybe there is also a function for this, but it surely will not be simple.

Collapse
sobhandash profile image
Sobhan Dash Author

I think we can use the Set function with addition to map or filter functions to create the uniqueFinder function that you are talking about