I was following a tutorial that suggested to check if an object is string and not empty as the following:
var s = "text here"; if ( s && s.charAt && s.charAt(0)) it is said that if s is string then it has a method charAt and then the last component will check if the string is empty or not.
I tried to test it with the other available methods like ( typeof and instanceof ) using some of the SO questions and here and here too !!
so I decided to test it in Js Bin : jsbin code here as follow:
var string1 = "text here"; var string2 = ""; alert("string1 is " + typeof string1); alert("string2 is " + typeof string2); //part1- this will succeed and show it is string if(string1 && string1.charAt){ alert( "part1- string1 is string"); }else{ alert("part1- string1 is not string "); } //part2- this will show that it is not string if(string2 && string2.charAt ){ alert( "part2- string2 is string"); }else{ alert("part2- string2 is not string "); } //part3 a - this also fails !! if(string2 instanceof String){ alert("part3a- string2 is really a string"); }else{ alert("part3a- failed instanceof check !!"); } //part3 b- this also fails !! //i tested to write the String with small 's' => string // but then no alert will excute !! if(string2 instanceof string){ alert("part3b- string2 is really a string"); }else{ alert("part3b- failed instanceof check !!"); } Now my questions are :
1- why does the check for string fails when the string is empty using the string2.charAt ???
2- why does the instanceof check failed??
if(string2.charAt)is only checking if method is defined, an empty string is still a string so will return true"".charAt(0) -> "" -> false-y. The thing that would not work is"" instanceof String && .., because it is a string value, not a String object.'somestring'.charAt(n)