Null vs empty string?


#1

For example I have one function

var myFun = function(){
    .............. do something .............
    
   if(data..){
      return data;
   }else{
      return null; // or empty string ' ';
   }
}

I should be return null or empty string if the function don’t get any things.
Please explain me.


#2
// or empty string ' ';

This is not an empty string, but a string containing space. Be careful when doing such things, because it would fail the test for being empty and result with your code thinking there actually was data returned.

There’s no specific need to return particular thing as long as your code doesn’t expect it served in particular format.

What you want to return depends specifically on your use case, that s what you want to do with the data further. If you want to state that there’s no data found, you can return false too.


Function to convert of string like this: "12 -> 12, 21" - "123 -> 123, 132, 231, 213, 312, 321"?
#3

Thanks for your reply, sorry it is empty string ''; not space.
Yes I would like to return no data found null or '' or false or undefined, which one?.


#4

Quoted from Stack Overflow.

Returning null is usually the best idea if you intend to indicate that
no data is available.

An empty object implies data has been returned, whereas returning null
clearly indicates that nothing has been returned.

Additionally, returning a null will result in a null exception if you
attempt to access members in the object, which can be useful for
highlighting buggy code - attempting to access a member of nothing
makes no sense. Accessing members of an empty object will not fail
meaning bugs can go undiscovered.

In short, it still depends on what you do with the code later.