DEV Community

Adam Preece
Adam Preece

Posted on

3 nice little JavaScript tips that you will want to use!

Short circuiting

// instead of using the usual if statement
if (login.status) {
displayUser()
}

// use a technique called short circuit evaluation

login.status && displayUser()
Enter fullscreen mode Exit fullscreen mode

This works because of the && (the logical AND which is read left to right), so if the first operand is true(login.status) then it will run the second operand (displayUser()).

If the first operand is false Javascript will 'short-circuit' as the AND will always be false and carry on reading the rest of the code!

This technique is especially import if using React as you cannot use IF/ELSE statements in JSX code.

Using an unary operator to turn a string into a number

// you may get an Id or some number as a string type

data.id = "3223"

// a quick and easy to turn it into a number

if(+data.id===3223) console.log("It is now a number!)


Enter fullscreen mode Exit fullscreen mode

All you have to do is place a +(the operator) before your string(operand) and it converts the operand to a number.

There are more unary operators to use, like for example "++"
which adds 1 to its operand.

Another use tip with this is changing any negative number/string into a positive


console.log(-"-12") // 12!
console.log(--12) // 12

Enter fullscreen mode Exit fullscreen mode

See what happens when you place a + or - operator before other operands such as true, null, false, NaN etc. Can you correctly predict?

Shortening multiple condition checking

We have all been there


if(input==="yes" || input ==="y"|| input ==="ok"){
//code to execute
}
Enter fullscreen mode Exit fullscreen mode

It is long, you can miss an equals or just use one, you can forget to write input again. So if you find yourself needing to write some code similar to the above try this little JavaScript code!


if(["yes","y","ok"].includes(input)) {
//code to execute
}
Enter fullscreen mode Exit fullscreen mode

The includes is a method for an array which returns a boolean, if it does not find any of the elements in the array it simply returns false.

Oldest comments (0)