Use the conditionals properly in JS

Hi Guys, I know I haven't been writting too much (none I guess) I'm sorry for that, but I've been learning new stuff :D

Today I want to share with you how to take advantage of the conditionals in JS, but first we need to understand how they work:

//OR

You might know that in JS the OR operator is represented by double pipes: || but, is it really returning a boolean value? well, the answer to that question is...NO, JS uses type conversion, it converts a type to boolean but just in certain contexts, take the following code snippet as example:


Basically the OR operator seeks for a truly value from left to right, once it found it, it returns that value, if the conditional is used on a loop/conditional context, then JS will evaluate its truly value, if not, it will evaluate the real value.

//AND

The AND operator (&&) it's used to evalue a truly condition, but I guess you already know that, and knowing how JS evaluates the conditionals depending on the context, I'm just going to say:

The AND operator will look for all the values to be true, starting from left to right, if all the values are true, it will return the last value and its truly value, but if one of those are false, it will return that value along with its falsy value

Please see the below example:



JS handles the conditionals in different way that some other languages do, but we should take advantage of that, let's say you want to return a value if some value is true, we normally use a ternary condition:

truly ? return 'Hello' : return null

But let's be honest, reading a ternary operator is never that easy, so why don't we change the above condition for something like:

return truly && 'Hello'

We know 'Hello' is true, so if truly is true, JS will return 'Hello' if not, it will return a falsy value, no extra evaluation and easy to read.

//Summary

We use conditionals everywhere, but knowing how they work could make or code easier to read and therefore easier to mantain, let's take advantage of the type conversion and use it properly, JS will return a value always, but depending of the context it will return either a boolean value or a real value.

JS works by evaluating falsys or truly values, by using type conversion, so we could say that each variable we create it could be either a true or a false value if we use it in loops/conditional contexts.

Well guys I hope you have enjoyed and learned something about conditionals in JS, see you ^_^/

Comments

Popular posts from this blog

Juego de Gato Usando HTML, JavaScript y CSS

AfterEffects - Quitar el Fondo de un Video Forma 1: KeyLight

Crear un nuevo Libro de Excel con VBA ES