Hello Friends, this is a small article which will help you to understand the difference between the typeof operator and in built JavaScript object method valueOf.

Difference between typeof and valueOf in JavaScript

Difference between typeOf and valueOf

The first difference is mentioned in the first paragraph itself. typeof is an operator which takes a single parameter and returns its type as String.

The JavaScript typeof operator returns the type of a variable. The list of possible re-turned values are:
“number” if variable is a number.
“string” if variable is a string.
“boolean” if variable is a Boolean.
“function” if variable is a function.
“object” if variable is null, an array, or another JavaScript object.
“undefined” if variable is undefined.

Whereas valueOf is an inbuilt method applied across all the objects in the JavaScript. It gets the primitive value of the object

Lets try to understand both of these with examples.

In the below code if I use typeof with String object, I get the object as output. Whereas if I use typeof with String literal, I get string as output.

var myStringObject = new String("Vikram");
var myName = "Vikram";

console.log(typeof myStringObject); //object
console.log(typeof myName); //string

Now lets see the same example with valueOf method as shown in the below code. In both the cases I get the literal value assigned to the variables.

var myStringObject = new String("Vikram");
var myName = "Vikram";

console.log(myStringObject.valueOf()); //vikram
console.log(myName.valueOf()); //vikram

Check of Non Empty String

If we want to check for non empty string we have to use both valueOf and typeof in JavaScript.

If we only use typeof as shown in the below code, there are chances that we may be dealing with String object and not the string literal.

// succeeds if string with length greater than zero
if ((typeof unknownVariable == "string") && (unknownVariable.length > 0)) {

But what if we are dealing with String Object. In that case the above code will not work for us. And we have to use valueof and typeof as shown in the code snippet below

// true if variable exists, is a string, and has a length greater than zero
if(((typeof unknownVariable != "undefined") &&
(typeof unknownVariable.valueOf() == "string")) &&
(unknownVariable.length > 0)) {


This was a small article to find the difference between typeof operator and valueOf method provided by the object class in JavaScript. And how we can use both to find if a string is Empty or not.

The post Difference between typeof and valueOf in JavaScript appeared first on Dot Net For All.