JavaScript String.IsNullOrEmpty

I’ve been doing a lot of JavaScript lately and in my JS I’ve been testing if a string is empty, null or undefined.   C# has string.IsNullOrEmtpy and I believe JS should have the same.  I was about to write my on function, but decided to first see if someone else has done this.  I found an example, but didn’t completely like it. So I made some changes and here’s String.IsNullOrEmpty
 String.IsNullOrEmpty = function(value) {
  var isNullOrEmpty = true;
  if (value) {
   if (typeof (value) == ‘string’) {
    if (value.length > 0)
     isNullOrEmpty = false;
  return isNullOrEmpty;
I don’t know why it’s "String.IsNullOrEmpty" instead of "String.prototype.IsNullOrEmpty", but it works.  Maybe someone can answer this for me.

3 thoughts on “JavaScript String.IsNullOrEmpty”

  1. I figured out why to use "String.IsNullOrEmpty" instead of "String.prototype.IsNullOrEmpty".  When using prototype the function is added to the object and every object that is instantiated has that function.  For example: Animal.prototype.Move = function(value){…} var dog = new Animal();dog.move(5); But if the prototype is not included, the function is added to the class.  Similar to a static member in C#.  So for example we can do this. Math.Pi = function(){  return 3.14159265;}
    var circumference = 2 * Math.Pi * Radius

  2. Mike’s comment was really helpful, along with the idea in your post. I went with the prototype approach so I could call it directly on an object, like myStringVariable.isNullOrEmpty():

    String.prototype.isNullOrEmpty = function() {
    var _isNullOrEmpty = true;
    if (this)
    if (this.length > 0)
    _isNullOrEmpty = false;
    return _isNullOrEmpty;

Leave a Reply

Your email address will not be published. Required fields are marked *