Jump to content

string is it not a object ?


Ramu26

Recommended Posts

Hi,

 

var str="something"

typeof(str) -----> "String"
var strObject = new String()
typeof(strObject) -----> Object
I was expecting typeof(strObject) to return String, Yes it is a object, but, of type String. Does that mean "String" dataType is primitive and not a object
Link to comment
Share on other sites

Javascript is a little bit weird like that with types since essentially everything in Javascript is an object. There's some information about it here:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeofNote, for example, that this creates an object:

var str = new String('test');
But this creates a string:
var str = String('test');
You should never use that though, it's always better to do this:
var str = 'test';
There are other objects for the other types as well, e.g.:
var a = String('test');var b = Boolean(true);var c = Number(1);var d = Array();var e = [];console.log(typeof a); // "string"console.log(typeof B); // "boolean"console.log(typeof c); // "number"console.log(typeof d); // "object"console.log(typeof e); // "object"console.log(typeof undefined); // "undefined"console.log(typeof null); // "object"
  • Like 1
Link to comment
Share on other sites

Javascript seems to have a number of constructors that are best avoided unless you really understand their unexpected quirks. Most Javascript books will discuss this topic. Usually they provide a number of recommendations that avoid the use of the constructors, such as...

var a = []; // create a new empty arrayvar b = {}; // create a new empty objectvar c = ''; // create a new empty string
Link to comment
Share on other sites

One more thing, I was reading Wrox professional Javascript book. It states that there are six DataTypes

undefined,null,String,Number,Boolean primitives and Object which is complex. But when did

 

var f= function() {}

typeof(f). It gives "function". That means we have function dataType also right?

 

In that case is the book wrong, it is 3rd edition. How many datatypes are really there then ?

Edited by Ramu26
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...