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;
}
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.
Source
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
Thanks bardev for this post. I learn a lot from this post about javascript.
Sid
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;
}