Interview question
What are JavaScript falsy values and how are they evaluated in conditions? JavaScript में falsy values कौन से हैं और conditions में कैसे evaluate होते हैं?
Answer
Falsy values are values that evaluate to false in a boolean context. There are only 6 falsy values in JavaScript.
// The 6 falsy values
false
0
-0
0n (BigInt zero)
'' (empty string)
undefined
null
NaN
// Examples
if (0) console.log('This won\'t run');
if ('') console.log('This won\'t run');
if (undefined) console.log('This won\'t run');
if (null) console.log('This won\'t run');
if (NaN) console.log('This won\'t run');
if ([]) console.log('This WILL run - arrays are truthy!'); // true
if ({}) console.log('This WILL run - objects are truthy!'); // true
if ('0') console.log('This WILL run - non-empty strings are truthy!'); // trueInterview tip: Remember that empty arrays [], empty objects {}, and the string '0' are all truthy! This trips up many developers.
Falsy values वो हैं जो boolean context में false evaluate होती हैं। JavaScript में सिर्फ 6 falsy values हैं।
// 6 falsy values
false
0
-0
0n
'' (empty string)
undefined
null
NaN
if (0) console.log('यह नहीं चलेगा');
if ('') console.log('यह नहीं चलेगा');
if (undefined) console.log('यह नहीं चलेगा');
if ([]) console.log('यह चलेगा - arrays truthy हैं!'); // true
if ({}) console.log('यह चलेगा - objects truthy हैं!'); // true
if ('0') console.log('यह चलेगा - non-empty strings truthy!'); // trueइंटरव्यू टिप: याद रखें [] (empty arrays), {} (empty objects), और '0' (string) सभी truthy हैं! यह बहुत सारे developers को confuse करता है।
Was this answer clear?