Navin Rauniyar
Navin Rauniyar

Reputation: 10555

What are the objects in javascript?

It is said that all are the objects in javascript. But I found that the primitive values like null, undefined, true, 'foo' are not objects. Is that true?

What are the objects in javascript and what are the non-objects in javascript? What is the primitive value actually?

If I'm understanding the following is true?

var str1 = "hello world!"; // primitive value
var str2 = String("hello world!");// object value

Upvotes: 1

Views: 94

Answers (2)

user2864740
user2864740

Reputation: 62005

JavaScript has two classes of values

  • Primitives - number, string, boolean, undefined, null

  • Objects - all other values, including Arrays and Functions

A major difference between primitives and objects is that primitives are immutable and custom/adhoc properties cannot be assigned to primitive values.


The number, string, and boolean primitive types have corresponding Object types: Number, String, and Boolean. However, there are no corresponding Object types for undefined or null - these values are lonely singletons.

The associated types contain the [prototype] which, when applied with implicit conversions, allows primitives to otherwise "act like" objects in that methods can be invoked on them. For instance, "foo".trim() calls the String.prototype.trim function.

The Number/String/Boolean functions, when not used as constructors, also act as conversions to the applicable primitive values.

"foo"                       // is string (primitive)
String("foo")               // is string (primitive)
new String("foo")           // is String (object)
"foo" === String("foo")     // -> true
"foo" === new String("foo") // -> false

One should generally use the primitive types to avoid confusion.

Upvotes: 4

Praveen
Praveen

Reputation: 56539

It is said that all are the objects in javascript. But I found that the primitive values like null, undefined, true, 'foo' are not objects.

If you read the documentation, It is already given

In JavaScript, almost everything is an object. All primitive types except null and undefined are treated as objects. They can be assigned properties (assigned properties of some types are not persistent), and they have all characteristics of objects.

List of data types in Javascript

Upvotes: 1

Related Questions