6

typeof returns the primitive data type but I am not getting why it is used in javascript?

4

6 Answers 6

8

I am not getting why it is used in javascript?

typeof is used to

return[s] the primitive data

For example, if I wanted to know if something was undefined, I could do

if (typeof object === 'undefined')

to check because if it is undefined there is no datatype (because it's undefined). This is generally why typeof would be used other than for logging purposes, to see what is received through ajax, or for making functions that accept a parameter that can have different types and checking that type with typeof, etc.

Sign up to request clarification or add additional context in comments.

3 Comments

Another reason is when you make your functions accept different parameters. typeof will then allow you to determine the type and act accordingly
It is better to do this: if(object === undefined) when putting this conditional at the top of your scope when trying to prevent errors. That is because if(typeof object === undefined) won't necessarily branch out if that was your goal.
+1 because this is an actual example of code. All the other examples don't show the basic usage in an if statement...
2

typeof is an unary operator that is placed before a single operand which can be of any type. Its value is a string that specifies the type of operand.

   - x                             typeof x

   undefined                        "undefined"
   null                             "object"
   true or false                    "boolean"
   any number or NaN                "number"
   any string                       "string"
   any function                     "function"
   any non function native object   "object"

The typeof works sufficiently well with primitive values except null.typeof cannot distinguish between null & object because null is falsy & objects are truthy.Here are few case studies which may be useful. typeof evaluates to object for all object and array values other than function.How typeof deals with function is probably beyond the scope of this question.

Hope this will help you.

Comments

1

typeof in javascript why it is used?

Sometimes you might need to check what kind of data is stored in a variable for example, typeof is an operator not a function and it's completely different from the return statement that stops the execution of a function and returns a value from that function.

The typeof operator returns a string indicating the type of the unevaluated operand.

console.log(typeof 'name');
// expected output: "string"
console.log(typeof 74);
// expected output: "number"
console.log(typeof true);
// expected output: "boolean"
console.log(typeof declaredButUndefinedVariable);
// expected output: "undefined";

typeof MDN web docs

The typeof operator is always followed by its operand:

typeof UnaryExpression => keep in mind that parentheses are optional but remember that: Parentheses are very useful to determine the data type for expressions.

var data = 100;
typeof data + ' Bye'; // return 'number Bye'
typeof (data + 'Bye'); // return 'string'

Other examples:

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number('1') === 'number'; // Number tries to parse things into numbers


// Strings
typeof '' === 'string';
typeof 'bla' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // note that a number within a string is still typeof string
typeof (typeof 1) === 'string'; // typeof always returns a string
typeof String(1) === 'string'; // String converts anything into a string, safer than toString


// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean will convert values based on if they're truthy or falsy, equivalent to !!


// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'


// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 


// Objects
typeof {a: 1} === 'object';

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';
typeof /regex/ === 'object'; // See Regular expressions section for historical results

Comments

1

The typeof operator returns a string which represents the type of the operand. We can use this to check the type of a value in the following manner:

let nr = 5;

if (typeof nr === 'number') {
  console.log('nr is number');
}


let str = 'hi';

if (typeof str === 'string') {
  console.log('str is string');
}

This can be especially useful when a variable can have multiple values. For example, null, undefined, or a number. In this case we can use the typeof operator in conjunction with an if statement in order to execute the right code for a given scenario.

Comments

0

You can use the JavaScript typeof operator to find the type of a JavaScript variable. It is also use to validate a variable or input.Explain better => http://www.w3schools.com/js/js_datatypes.asp Example typeof "John" // Returns string typeof 3.14 // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name :'John', age:34} // Returns object

Comments

-1

The following is a common typeof hack which is somewhat problematic::

const type = obj => Object.prototype.toString.call(obj);

type("abc");// [object String]
type(123);// [object Number]// What's with all the objects?
type([]);// [object Array]
type({});// [object Object]
type(Object.create(null));// [object Object]
type(-1/0);// [object Number] Not exactly a true number
type(NaN);// [object Number] WTF?

As you can see there are a few problems with it. It always returns two types wrapped in brackets with the first always an "object". This makes the first type useless information if it is always returned. Secondly it is somehat limited in what it distinguishes. It cannot tell us if an object was created as a literal (plain) or with Object.create() which would require the keyword "new" when called. It also falesly calls infinity and NaN a number.

I wish to share a better typeof function that fixes all of those things. It works for all primitives including symbols, anomalies (errors, undefined, null, and NaN), most common cases of native objects and functions (Array, Map, Object, Function, Math, Date, Promise, and many more), and it can even detect between user made objects (identified as Plain) and DOM elements (identified as HTML). It should work for all modern and somewhat older browsers. It is broken down into several functions to make the code more user friendly:

const isDOM = obj => (obj.nodeType && !isPlain(obj)) ? true : false;
const isPlain = obj => obj ? obj.constructor === {}.constructor : false;
const sanString = str => str.replace(/[^a-zA-Z ]/g, "");
const isNaN = obj => (Object.is(obj, NaN) === true) ? true : false;

function objType(obj){
if(obj === undefined) return undefined;
if(obj === Infinity) return Infinity;
if(obj === -Infinity) return -Infinity;
if(isDOM(obj)) return 'HTML';
let str = Object.prototype.toString.call(obj);
if(str === '[object Object]' && isPlain(obj)) return 'Plain';
str = sanString(str).split(' ');
if(str[1] === 'Number' && isNaN(obj)) return NaN;
return str[1];}
}

Use like this:

objType(null);// Null
objType(undefined);// undefined
objType("abc");// String
objType(123);// Number
objType([]);// Array
objType({});// Plain not [object Object]
objType(Object.create(null));// Object is what we want
objType(document.body);// HTML
objType(-1/0);// -Infinity
objType(NaN);// NaN

Please let me know if you find any errors or bugs or have a better solution (not from liberaries or freameworks). I will gladly promply fix it.

3 Comments

objType({constructor:'',nodeType:true}) => "HTML". Really? Not really sure what you are trying to do here, but I don't see how this answers the current question. As a note, don't check against properties like that, e.g to know if an object is a Node, call object instanceof Node.
Using typeof(document.body) returns [object HTMLBodyElement] and each DOM element will have its own constructor. My objType groups all DOM as HTML. This is useful when you wish to check your code when manipulating the DOM to make certain it is actually generating HTML elements.
You didn't got my point... So first, typeof is an operator, you don't call it like a function (no need for ()). Then my first point was that your function will return 'HTML' for {constructor:'',nodeType:true}, while it is just a plain object. This is because you are doing it wrong by checking against properties. And no matter how I think about what your code is doing (IMM it's just a complicated way to get things wrong and write more), it absolutely doesn't answer the question at hand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.