0
I am starting my studies in JS and I have the following question. Consider the code below:
const vazio = null
const resultado = vazio || 'Anonimo'
console.log(resultado)
The console output will be the 'Anonimo' string display'.
I know that null values are considered false, but I didn’t understand the JS behavior of assigning the string 'Anonimo' to the constant result. I thought it would convert the string 'Anonimo' to Boolean(true) and assign to the constant result the boolean comparison: false || true = false.
Because this behavior of the JS?
Thanks for your attention
|| is a logic operator and not a means of "conversion", I recommend you read What are Truthy and falsy values? - I recommend reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators
– Guilherme Nascimento
Hi William, thank you for the content, very enlightening... But in it there is no specific example similar to the example I quoted and could not abstract with the content indicated.
– Bruno Nobre
Oi Bruno. The || operator will not convert to true or false, the second value after || is the alternative to the first value before ||, which does not need to be exactly false, it can be "falsy" (are falsy values like null, Undefined, Number -0 or +0 and Nan), ie will not "convert", will deal within Truthy or falsy, being the value after || assigned only if the value before is falsy... Yet if I did
const resultado = !!(vazio || 'Anonimo')
you would have a Boolean result, read: https://answall.com/q/29014/3635– Guilherme Nascimento