The !! operator in JavaScript is used to convert a value to a boolean (either true or false).
How !! Works?
· The first ! (logical NOT) negates the value, converting a truthy value to false and a falsy value to true.
· The second ! negates the result of the first !, effectively converting the original value to its boolean equivalent.
Truthy and Falsy Values in JavaScript
JavaScript considers certain values as "truthy" (values that evaluate to true in a boolean context) and others as "falsy" (values that evaluate to false in a boolean context).
The following values are considered falsy in JavaScript.
· false
· 0
· "" (empty string)
· null
· undefined
· NaN
Examples of Truthy Values
· Non-empty strings: "Hello" or "0" or "false" (any string that is not empty)
· Non-zero numbers: 42, -1, 3.14
· Arrays (even empty ones): []
· Objects (even empty ones): {}
· Functions: function() {} (any function definition)
· Infinity and -Infinity
· Infinity, -Infinity
· Date objects: new Date()
If a value is not explicitly one of the falsy values (false, 0, "", null, undefined, NaN), it is automatically considered truthy in JavaScript. Even unusual values like empty arrays and objects are truthy because JavaScript evaluates their presence rather than their content.
bangOperator.js
let value1 = "Hello, World!"; let value2 = 0; let value3 = null; let value4 = {}; let value5 = NaN; console.log(`value1 : ${value1}, Boolean Value : ${!!value1}`); console.log(`value2 : ${value2}, Boolean Value : ${!!value2}`); console.log(`value3 : ${value3}, Boolean Value : ${!!value3}`); console.log(`value4 : ${value4}, Boolean Value : ${!!value4}`); console.log(`value5 : ${value5}, Boolean Value : ${!!value5}`);
Output
value1 : Hello, World!, Boolean Value : true value2 : 0, Boolean Value : false value3 : null, Boolean Value : false value4 : [object Object], Boolean Value : true value5 : NaN, Boolean Value : false
No comments:
Post a Comment