-2

While facing an interview I got confused between

  1. if({}) console.log("hello")
  2. if([]) console.log("hello")
  3. if(' ') console.log("hello")
  4. if('') console.log("hello")

I know that first three will print hello , but I don't know on what basis evaluation is done.

And even I'll like to know about few sites or URL from where I can get these tricky questions and solutions

A.A Noman
  • 5,244
  • 9
  • 24
  • 46
Deepankar Singh
  • 193
  • 1
  • 13
  • 3
    Search for ["JavaScript truthy value"](https://www.google.com/search?q=javascript+truthy+values) - In `if (expr) stmt;`, stmt is executed if and only if `expr` evaluates to such a "truthy value". – user2864740 Dec 18 '18 at 05:22

1 Answers1

5

'', null, undefined and 0 are examples of falsey, others are truthy.

if({})
  console.log("Empty Object is truthy");
  
if([])
  console.log("Empty array is truthy");
  
if(' ')
  console.log("Space is truthy");
  
if(!'')
  console.log("Empty string is falsey");

if(!null)
  console.log("null is falsey");

if(!undefined)
  console.log("undefined is falsey");

if(!0)
  console.log("Zero is falsey");
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • Thanks Adrian for the answer but one thing more, if undefined is false then when we create an empty array it is also undefined. So, at that time how it evaluates to true – Deepankar Singh Dec 18 '18 at 05:44
  • Empty array is not undefined, it is an instance of an array object with properties like length === 0. – Adrian Brand Dec 18 '18 at 05:50
  • but when we declare array like var x = [] or var x= new Array(),it gives undefined – Deepankar Singh Dec 18 '18 at 06:05
  • What do you mean it gives undefined? – Adrian Brand Dec 18 '18 at 06:29
  • sorry adrian for asking so many doubts, but this one is last. when in console window i write var x = [] after pressing enter it gives undefined and when i write x:Array = [] it doesn't give undefined it gives empty array []. why so? – Deepankar Singh Dec 18 '18 at 07:30
  • The console is logging what x was before the assignment. Type in var x = 25; and you get the same thing but 25 is definitely not undefined. – Adrian Brand Dec 18 '18 at 22:25