Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 17, 2022 02:21 pm GMT

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

Short circuiting

// instead of using the usual if statementif (login.status) {displayUser()}// use a technique called short circuit evaluationlogin.status && displayUser()

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 typedata.id = "3223"// a quick and easy to turn it into a numberif(+data.id===3223) console.log("It is now a number!)

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

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}

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}

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.


Original Link: https://dev.to/quality_pre/3-nice-little-javascript-tips-that-you-will-want-to-use-4ib0

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To