Check if a variable is a string using JavaScript
Checking the type of a variable can be done by using typeof operator. It directly applies either to a variable name or to a variable.
Syntax:
typeof varName;
- varName: It is the name of variable.
Example 1:This Example checks if the variable boolValue and numValue is string.
html
< h1 style = "color:green;" > GeeksForGeeks </ h1 > < p > var boolValue = true; < br > var numValue = 17; </ p > < button onclick = "Geeks()" > Click to check </ button > < p id = "GFG_P" style = "color:green; font-size: 20px;" > </ p > < script > function Geeks() { <!-- "boolean" value. --> var boolValue = true; <!-- "integer " value. --> var numValue = 17; var el = document.getElementById("GFG_P"); var bool, num; if (typeof boolValue == "string") { bool = "is a string"; } else { bool = "is not a string"; } if (typeof numValue == "string") { num = "is a string"; } else { num = "is not a string"; } el.innerHTML = "boolValue " + bool + "< br >numValue " + num; } </ script > |
Output:

Example 2:This Example checks if the variable strValue and objGFG is a string.
html
< h1 style = "color:green;" > GeeksForGeeks </ h1 > < p > <!-- "String" value. --> var strValue = "This is GeeksForGeeks"; < br > <!-- "Object" value. --> var objGFG = new String( "This is GeeksForGeeks" ); </ p > < button onclick = "Geeks()" > Click to check </ button > < p id = "GFG_P" style = "color:green; font-size: 20px;" > </ p > < script > function Geeks() { var strValue = "This is GeeksForGeeks"; var objGFG = new String("This is GeeksForGeeks"); var el = document.getElementById("GFG_P"); var str, obj; if (typeof strValue == 'string') { str = "is a string"; } else { str = "is not a string"; } if (typeof objGFG == "string") { obj = "is a string"; } else { obj = "is not a string"; } el.innerHTML = "strValue " + str + "< br >objGFG " + obj; } </ script > |
Output:

Explanation: String formed using new keyword will be of object type hence objGFG doesn’t return true when compared to String.
Please Login to comment...