8

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

 2 years ago
source link: https://dev.to/quality_pre/3-nice-little-javascript-tips-that-you-will-want-to-use-4ib0
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK