You see, I was practicing conditionals and using the short circuit operator to assign a value to a variable, I didn't quite understand why values are considered true or false even though they are not booleans.
try this example
let hola,hola2="Hola mundo"
hola = hola2 || "Adios"
In this case the value I got was the value of hello2 as it was considered true.
While in this other example using &&
let hola,hola2="Hola mundo"
hola = hola2 && "Adios"
I got the second value which in this case is "Goodbye"
From what I learned about the short-circuit operators when using them to assign a value to a variable, it is that in the case of using the operator || if the first value is true it will assign the first value to the variable and if it is false it will assign the second value. In the case of the && operator, if the first value is true, the second value is assigned to the variable and if not, the first value is assigned.
I did another test doing this example with if:
let persona="Hola mundo";
if(persona){
console.log("Hola mundo");
}
persona=null;
if(persona){
console.log("No es null o undefined");
}else{
console.log("Es null o undefined");
}
My question is, why are my variables considered true or false if they are not boolean? true value when they have a stored value and false when they are undefined or null. Is it proper to language to do that?
In Javascript there is a concept we call Truthy :
Using Javascript 's type coercion (forcing the interpreter to change the types of variables to operate on them), you can check this with simple tests:
This feature is useful for quick checks on whether a field has been filled:
or to check that an attribute exists:
But you have to be careful if the value is a number, because if it
prop1
is 0 it can be a correct value, in that case you would have to do something likeAnother utility is to take default values: imagine that you have to check if an attribute exists and, if it doesn't, assign a value to it:
Conditionals can be created, albeit quite ugly:
This causes it to be executed
f(a)
only if ita
exists and has a value of truthy , because the operation&&
is short- circuited (the second part is not executed if the first part is not fulfilled)