How is almost everything in Javascript an object?
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.
Everything is an object?
Go back to first principles.
What's an object? It's a software component that encapsulates state and behavior together into a single entity in memory.
By that definition, you can see where everything can be thought of as an object. Functional programmers make functions first class objects. Data folks would say that data, even that without behavior, can be thought of as an object (albeit not a very smart one).
I don't see what this changes.
JavaScript treats functions as objects.
I'm not sure what effect this insight will have on your programming.
If everything in javascript is object then why typeof operator returns function for object?
Because Object
is the constructor for an object.
Is `Object` a function in JavaScript?
You seem to be confused between "object" (the data structure) and Object
(the function).
An object is a concept in JavaScript that is a generic container for some data. An object contains properties with keys and associated values.
In JavaScript, everything that is not a primitive is an object. This includes functions, which are basically a special type of object that can be "called" with the ()
syntax.
JavaScript provides a number of built-in functions that have various purposes. Two such functions happen to be called Object
and Function
. So in other words Object
is a function and thus also an "object" (data structure).
Let's take your function Foo
as an example:
function Foo() {
var a = "3";
}
Foo
is a function. This means that Foo
can be called, eg. var f = Foo()
. In this case f
will be undefined
since Foo
doesn't return anything.
Because Foo
is a function, it is also an object. This means we can also add and read properties from it:
Foo.bar = 5;
Foo.bar++;
console.log(Foo.bar); // prints 6
Please note that this "object" part of Foo
is not related to the contents of the function. That means that the code you declared (var a = "3"
) is irrelevant. You cannot access var a
in any way here because it does not exist until you call the function. If you were to do Foo.a
, you are not manipulating var a
inside the function; you are working with the property a
on the object Foo
.
You can however do it the other way around and access properties on Foo
inside of the function:
function Foo() {
var a = "3"; // a is local to this scope, you cannot get to it from outside
console.log(a); // prints 3 - local variable a is accessible inside the scope of this function
console.log(Foo.a); // prints 5 - a is a property on object Foo, and is accessible here
}
// var a inside Foo cannot be accessed here
Foo.a = 5;
Foo();
Edit: Re. your question regarding "this" in the comments. this
is a special keyword in JavaScript that refers to an object. However, this object is not the function itself, it is a new object that is created when you call a function using the new
keyword:
function Bar() {
this.a = 10;
console.log(this == Bar); // prints false
}
var bar = new Bar();
console.log(bar.a); // prints 10
A function that is meant to be called with the new
keyword is referred to as a "constructor function". Object
and Function
are both examples of constructor functions, which is why their names start with an uppercase letter (a convention in JavaScript).
When you create an object with a constructor function, the property prototype
of this function is used as the prototype (accessible through __proto__
) of the created object.
console.log(bar.constructor == Bar) // prints true
console.log(bar.__proto__ == Bar.prototype) // prints true
this
is also used for other things, but that is a broad subject and way out of scope for this question.
What exactly is an object? [JavaScript]
An object is a complex data type, that stores values and lets them be accessible with a specific key. A key/value combination inside an object is called a property.
JavaScript is an object-oriented programming language. This means that nearly every value is an object. Some kinds of values are called primitives, and they are seen as the "foundation", as simple data types. These primitives are strings, numbers, booleans, null
, and undefined
.
(Note that apart from booleans, null
and undefined
, all primitives are secretly objects as well, because only objects can have methods - you have String.split
, Number.toString
, etc.)
There are also many other data types, which are a specific kind of object:
- Arrays store values in an indexed fashion, and guarantee order (unlike objects)
- Functions receive values, execute code, and may return a value for later use
- Sets are similar to an array, but store only unique values
An object literal, however, is what many people think of when they think "object". It looks like this:
const myObject = {
name: "Jack",
cool: false,
friends: 0
pets: ["Dog", "Cat", "Snake"]
};
You can see that object properties are in the format of key: value
, with a comma ,
afterwards if there are more properties (in ES6, trailing commas are allowed).
Objects can also contain methods:
const myObject = {
name: "Jack",
sayHello: function() {
console.log(`Hello, my name is ${this.name}!`);
}
};
Note: When making methods within an object, the highest-level function (in this case, the part directly after sayHello
), must be an ES5-style function in order for references to this
to function correctly. If nested functions (like setTimeout
) need to refer to the object as well, they must be ES6-style functions, because arrow functions (=>
) do not carry their own this
binding.
Objects can also be constructed using constructors (ES5) or classes (ES6).
A constructor needs to be an ES5 function, and within it, you assign all the properties (usually from passed parameters):
function MyObject(name, cool) { this.name = name; this.cool = cool;}
var jack = new MyObject("Jack", false);var bob = new MyObject("Bob", true);
console.log(jack);console.log(bob);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Related Topics
How to Access Svg Elements with JavaScript
How to Check If Dst (Daylight Saving Time) Is in Effect, and If So, the Offset
How to Get the Non-Enumerable Inherited Property Names of an Object
JavaScript Regex: How to Put a Variable Inside a Regular Expression
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array
Jqgrid Incorrect Select Drop Down Option Values in Edit Box
Code Within D3.JSON() Callback Is Not Executed
How to Draw Smooth Curve Through N Points Using JavaScript HTML5 Canvas
How to Check for an Undefined or Null Variable in JavaScript
How to Sort 2 Dimensional Array by Column Value
How to Bind Fancybox to Dynamic Added Element
How to Cancel an Http Fetch() Request
How to Decode a String with Escaped Unicode
Seedable JavaScript Random Number Generator
Adding Click Event Listener to Elements with the Same Class