82

I read this a lot in many JavaScript introductions. I just don't understand it. I always think of objects as something with methods and properties. Arrays I understand, since it has key value pair. How about "Strings" or "Numbers" or "functions" ? These things above listed seem to be like functions to me. This means you input something, you get something out. You don't really get the access properties or anything. There's no dot notation used in arrays or this list of "objects".

Does anyone code some examples of each of these with dot notations which its methods and properties are being accessed? I suspect that definition of object is probably limited since I did start learning about JavaScript...

sanchez
  • 4,519
  • 3
  • 23
  • 53
Matt
  • 2,439
  • 7
  • 29
  • 42
  • Have you learned a classical object oriented (the kind where you build classes and make a lot of instances from them, like C++ or Java) language? It might help in answering the question. – vinczemarton Feb 02 '12 at 08:13

6 Answers6

259

No, not everything is an object in JavaScript. Many things that you interact with regularly (strings, numbers, booleans) are primitives, not objects. Unlike objects, primitive values are immutable. The situation is complicated by the fact that these primitives do have object wrappers (String, Number and Boolean); these objects have methods and properties while the primitives do not, but the primitives appear to have methods because JavaScript silently creates a wrapper object when code attempts to access any property of a primitive.

For example, consider the following code:

var s = "foo";
var sub = s.substring(1, 2); // sub is now the string "o"

Behind the scenes, s.substring(1, 2) behaves as if it is performing the following (approximate) steps:

  1. Create a wrapper String object from s, equivalent to using new String(s)
  2. Call the substring() method with the appropriate parameters on the String object returned by step 1
  3. Dispose of the String object
  4. Return the string (primitive) from step 2.

A consequence of this is that while it looks as though you can assign properties to primitives, it is pointless because you cannot retrieve them:

var s = "foo";
s.bar = "cheese";
alert(s.bar); // undefined

This happens because the property is effectively defined on a String object that is immediately discarded.

Numbers and Booleans also behave this way. Functions, however, are fully-fledged objects, and inherit from Object (actually Object.prototype, but that's another topic). Functions therefore can do anything objects can, including having properties:

function foo() {}
foo.bar = "tea";
alert(foo.bar); // tea
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 17
    This answer should be on top: while the chosen answer is good enough for practical purposes, this one is way more thorough (and interesting!) Thanks! – theabraham Aug 30 '12 at 23:34
  • 11
    This is the right answer. Not everything is an object. Almost everything is an object.See https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript for the types in javascript. – Srinivas Mar 09 '13 at 14:49
  • 5
    Good answer. Interestingly, though, if you use `var s = new String('foo');`, then `s.bar` will keep the value `cheese`. – Fenton Mar 15 '14 at 19:58
  • 6
    @SteveFenton: Yes, because `new String('foo')` produces a `String` object, which behaves like any other object because it inherits from `Object.prototype`. – Tim Down Mar 16 '14 at 10:04
  • 2
    Great explanation! Practically everything is an object except primitive types. – Fillip Peyton Mar 10 '15 at 17:06
  • 1
    Not only functions but even arrays inherit from Object, so using something like `var test = []` and later if we use `test['custom_key'] = 1;` sets a property of `custom_key` .... – Mr. Alien Apr 12 '15 at 07:22
  • This is a very interesting and informative answer. Thank you! – incutonez Jan 30 '16 at 17:59
  • @TimDown: "Functions, however, are fully-fledged objects, and inherit from Object (actually Object.prototype, but that's another topic)" - can you share a link to any post which explains this behavior? – darKnight Aug 27 '18 at 18:14
  • @darKnight: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function – ☝️First line – Kamafeather Sep 12 '20 at 02:31
39

That’s right: in JavaScript, almost everything is an object. But these objects are bit different from what we see in Java, C++ or other conventional languages. An object in JS is simply a hashmap with key–value pairs. A key is always a string or a symbol, and a value can be anything including strings, integers, booleans, functions, other objects etc. So I can create a new object like this:

var obj = {}; // This is not the only way to create an object in JS

and add new key–value pairs into it:

obj['message'] = 'Hello'; // You can always attach new properties to an object externally

or

obj.message = 'Hello';

Similarly, if I want to add a new function to this object:

obj['showMessage'] = function(){
  alert(this['message']);
}

or

obj.showMessage = function() {
  alert(this.message);
}

Now, whenever I call this function, it will show a pop-up with a message:

obj.showMessage();

Arrays are simply those objects which are capable of containing lists of values:

var arr = [32, 33, 34, 35]; // One way of creating arrays in JS

Although you can always use any object to store values, but arrays allow you to store them without associating a key with each of them. So you can access an item using its index:

alert(arr[1]); // This would show 33

An array object, just like any other object in JS, has its properties, such as:

alert(arr.length); // This would show 4

For in-depth detail, I would highly recommend John Resig’s Pro JavaScript Techniques.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
craftsman
  • 15,133
  • 17
  • 70
  • 86
  • 10
    Just an addendum, not really relevant to this topic, the `length` property does not return the number of elements in an array. It returns the `lastIndex + 1` for that array. For example, in `var x = []; x[100] = 5; alert(x.length)` will alert `101`. – Rohan Prabhu Feb 02 '12 at 09:19
  • 24
    No, not everything in JavaScript is an object. Strings, numbers, booleans are not, although they have object counterparts. – Tim Down Feb 02 '12 at 10:06
  • 3
    Tempted to downvote because of "That's right, in javascript, everything is an object."... – David Winiecki Sep 13 '14 at 18:43
  • 1
    "Although you can always use any object to store values, but arrays allow you to store them without associating a key with each of them." According to spec this is not true. There is no array in JS there is only ARRAY OBJECTS. The way they work is they auto give each of the property the property name which is the index of the element in the array. This is the 15.4 of the spec. You can use the bracket notation to get em, for instance myArray["0"] will give 1st object – DanteTheSmith Dec 26 '18 at 13:17
  • 1
    @DavidWiniecki You’re right: this should be downvoted, because the explanation is wrong. While you can access `"hello"[2]` or call `(4).toString(2)`, this is not because these primitive values are objects, but because they are _coerced_ to objects before the properties are read. Very soon we might have three categories of ECMAScript values, which will add even more to the confusion: primitives, [compound primitives](https://github.com/tc39/proposal-record-tuple), and objects. – Sebastian Simon Apr 11 '21 at 18:01
11

The sentence "In JavaScript, ALMOST everything is an object" is correct, because the MAIN code-units (objects, functions, arrays) are JavaScript-objects.
JavaScript code uses 9 different-units plus 1 (multiple):
- 01. array
- 02. boolean
- 03. function
- 04. null
- 05. number
- 06. object
- 07. regexp
- 08. string
- 09. undefined
- 10. multiple

BUT JavaScript-objects:
- are NOT same creatures as the 'objects' in other object-oriented-languages.
- they are a collection of name-value-pairs.
- all have a function of creation (its constructor).
- all INHERIT the members of the prototype-object of its constructor and this is its prototype.
- all functions are objects BUT NOT all objects are functions.
- functions have scope, objects NOT (a design flaw in my opinion).
- Object, Function, Array, String, ... with first CAPITAL are functions!!!
- it is more important the differences of JS objects and functions, than its commonnesses.
- the name 'instance' in JS has different meaning with the name 'instance' in knowledge-theory where an instance inherits the attributes of its generic-concept. In JS denotes only its constructor. JavaScript got the name 'instance' from 'class-based-inheritance' ool (java) where it is an appropriate name because those objects inherit the attributes of classes.
A better name for the JS-keyword 'instanceof' is 'objectof'.

JS-functions ARE JS-objects because:
1) they can have members like JS-objects:

    > function f(){}
    undefined
    > f.s = "a string"
    "a string"
    > f.s
    "a string"

2) they have a constructor-function, like all JS-objects, the Function function:

    > (function f(){}) instanceof Function
    true

3) as all JS-objects, their prototype-object is the same with its constructor prototype:

    > (function f(){}).__proto__ === Function.prototype
    true
    > ({}).__proto__ === Object.prototype
    true
    > (new Object).__proto__ === Object.prototype
    true

4) of course, JS-functions as SPECIFIC JS-objects have and extra attributes, like all functions in programming-languages, that JS-objects do not have like you can call (execute) them with input and output information.

EVERYTHING is NOT an object, because, for example, we can NOT add members to a literal string:

    > var s = "string"
    undefined
    > s.s2 = "s2string"
    "s2string"
    > s.s2
    undefined
synagonism
  • 135
  • 1
  • 4
  • 4
    What is multiple? I don't find any reference to a multiple type googling around. – David Winiecki Sep 11 '14 at 23:17
  • 'multiple' is a unit that can be|contain different types, eg a variable in which we store a string, a number, an array, ... – synagonism Sep 13 '14 at 17:40
  • Code, like text, is composed from simpler entities to more complex one. In texts we have letters, words, names, sentences, paragraphs, ... These are text-units. In the same way we have code-units. – synagonism Aug 21 '15 at 05:55
  • 1
    This answer causes more confusion than it clears; it’s kind of all over the place. The “code units” that you’re referring to are not a thing… – Sebastian Simon Apr 11 '21 at 18:14
10

Not everything is an object in javaScript. JavaScript has primitives and objects. There are six primitives-null,undefined,string,number,boolean and symbol. It might seem like everything is acting as an object because of the properties and function that can be accessed.for example-

var stringvar="this string";
typeof stringvar; // "string"
stringvar.length; //11

now since "stringvar" is a string type ,which is a primitive type,it should not be able to accesss property length.It can do so because of something called Boxing.Boxing is the process where any primitive type is converted to an Object type and the reverse is called Unboxing.These object types or Object wrappers are created with the view that there are some common operations that one might need to perform with the primitive values.They contain useful methods and properties and are prototype linked to the primitives. As far as the Objects are concerned,key value pairs can be added to every object,even to the arrays.

var arr=[1,2,3];
arr.name="my array";
arr;  //[1,2,3,name:'my array']

this does not mean that the fourth element of the array is "name:'my array'"."name" is a property that can be called with dot notation(arr.name) or brackets notation(arr["name"]).

viery365
  • 935
  • 2
  • 12
  • 30
DEVCNN
  • 614
  • 4
  • 13
10

Based on developer.mozilla.org and also ECMAScript specification the answer is no. Technically not everything is object.

https://developer.mozilla.org/en-US/docs/Glossary/Primitive

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 7 primitive data types: string, number, bigint, boolean, null, undefined, symbol

A primitive is not an object and has no methods and It is also immutable. Except for null and undefined, all the other primitive have a wrap object around them to provide you some functions that you can use. For example String for the string primitive.

https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript

So here in the following code when you call toUpperCase() on a primitive data name JavaScript will automatically wrap the string primitive and call toUpperCase function of String object

var name = 'Tom';
console.log(name);

name.toUpperCase();
console.log(name); 

In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

Also note that JavaScript distinguishes between String objects and primitive string values.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects

var nameP = 'Tom';
var nameO = new String(nameP);

typeof nameP // "string"
typeof nameO // "object"
Saman
  • 5,044
  • 3
  • 28
  • 27
  • 1
    Thank you for your answer. It's cool to provide the information in the document as a reference! – Andy Mar 01 '21 at 23:35
  • All factory functions produce "object" no matter what their name, so even constructors such as Function and String produce objects. Thanks for the answer. – aderchox May 17 '21 at 05:44
0

I would say "Everything in Javascript is not an object (because of primitives) but everything in javascript leads back to an object (because of wrappers and Object constructor)"

Nikhil Jadhav
  • 51
  • 1
  • 1
  • 4