JavaScript object meaning - javascript

I'm currently doing a bit of JavaScript and I have some troubles trying to explain myself one thing.
If I do that :
var text = new String("Enter any value here");
We all agree that "text" is an object, right?
But what should be "String" called then? Because I see everywhere that String is also an object, but wouldn't it be simpler to call it a class like in PhP.
Is there an other name, more precise than just object for String?
If someone can explain me the subtlety, I would be very happy. Thank you!

I think the source of your confusion is unfamiliarity with Prototypal Inheritance model. I suppose you are well versed with 'Classical Model' where classes are constructed using Classes as blueprint. On the other hand in JavaScript other Objects are created using an Object as a prototype or using an empty object and then pinning new properties in it.
If you try logging typeof(String) you will get output as function. Here when we do a new String('hello, world'), we get a new String object Hello, World. Thus String is a constructor in JavaScript.

By design, JavaScript (the implementation of the ECMAScript standard) has no class. So String cannot ever be called a class.
String here is but an object, just as almost everything in JavaScript is (as some the answers have already stated).
console.log(String instanceof Object); // true
Actually a special object: a function.
console.log(typeof String); // "function"
console.log(String instanceof Function); // true
And even a special function: a function that should be called as a constructor, hence the capital 'S'.
Even more special function: it is a built-in function (it is "present in the language" and therefore provided by the host environment -the browser or node, for example).
This special function allows you to instantiate an object of type String:
var aString = new String("A string");
But this is the wrong way to do it: you should write this:
var aPrimitiveString = "A string";
which interestingly, by the way, doesn't make text a String (Object), but a string (primitive).
console.log(typeof(aString)); // "object"
console.log(aString instanceof String); // true
console.log(aString instanceof Object); // true
console.log(typeof(aPrimitiveString)); // "string"
console.log(aPrimitiveString instanceof String); // false
console.log(aPrimitiveString instanceof Object); // false
Even in ECMAScript 6 (AKA ES6, AKA Harmony, AKA ES2016), there won't be any classes in the acception you have of it, "classes" in ES6 will still be an object, of type function, with prototypal inheritance.
One more thing: String can also be used to explicitly coerce a value into a string primitive:
var number = 1;
var numberAsString = String(1);
console.log(number); // 1
console.log(numberAsString); // "1"
console.log(typeof number); // "number"
console.log(typeof numberAsString); "string"
for the sake of completeness, I hope you guessed that:
number is a primitive number
numberAsString is a primitive string
new number(1) would be an object, instance of Number and Object
Number('0') would be a primitive number
same goes for Boolean
There are no classes in JavaScript, there won't ever be (I don't want any of it, anyway), that is what make the language so flexible, expressive and powerful.
Maybe you would want to take a look at this: http://javascript.crockford.com/inheritance.html (and the whole site and work of Douglas Crockford).

JavaScript is an object oriented language without classes.
However, you can apply many object oriented paradigms in JavaScript. It has its own mechanisms to do so.
In JavaScript, instead of classes you use objects. That's really about it already. You can think of String as a class if you want, but sometimes it can lead to confusion, because it is easy to confuse concepts known from Java or C++ with JavaScript. The implementation is just different.
I suggest you omit to think of it as a class, and call it an object. And try not to apply terminology of other languages like PHP with JavaScript.
Now, the confusion might be that in other OO languages you define a class and then you create instances from that class, which we refer to as objects.
In JavaScript you simply create a new copy of another object.
Please refer to this link and...
...note that JavaScript distinguishes between String objects and
primitive string values. (The same is true of Boolean and Numbers.)

According to w3schools:
In JavaScript, almost "everything" is an object.
Booleans can be objects (or primitive data treated as objects)
Numbers can be objects (or primitive data treated as objects)
Strings can be objects (or primitive data treated as objects)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are objects
In JavaScript, all values, except primitive values, are objects.
Primitive values are: strings ("John Doe"), numbers (3.14), true,
false, null, and undefined.
MDN says in javascript everything are objects.
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.
Creating new objects
JavaScript has a number of predefined objects. In addition, you can
create your own objects. You can create an object using an object
initializer. Alternatively, you can first create a constructor
function and then instantiate an object using that function and the
new operator.
So in javascript the idea of class doesn't really exist like in other languages. It's just an instantiated object or function if you prefer.
typeof 1.00 // number
typeof 1 //number
typeof "string" //string
typeof String("string") //string
typeof new String("string") //object
typeof {} //object
typeof [] //object
Demo
It seems possible to create classes in ECMAScript 6
It is said that:
Defining classes
Classes are in fact functions, and just like you can define function
expressions and function declarations, the class syntax has the two
opponents:
class expressions and class declarations.

Related

Are all variables in js converted to objects before being executed?

From what I have understood, primitive data types such as a string can also have properties ie string can have .includes . Does that mean all primitive data types are converted to objects before being executed. If yes, what is the point of having distinct difference between primitive data types and objects.
Whenever you try to refer to a property of a string s, JavaScript converts the string value to an object as if by calling new String(s). This object inherits string methods and is used to resolve the property reference. Once the property has been resolved, the newly created object is discarded.
Numbers and booleans have methods for the same reason that strings do: a temporary object is created using the Number() or Boolean() constructor, and the method is resolved using that temporary object.
source Javascript: The Definitive Guide. David Flanagan
When you call a property on a string (lower case) primitive, the JS runtime creates a new instance of a String (upper case) object and copies the string primitive value into the new "wrapper" object, then the property or method that you originally called gets called on the wrapper object and then that wrapper object is garbage collected when the statement is completed. This makes it only seem like some primitives have properties when they actually don't.
If yes, what is the point of having distinct difference between
primitive data types and objects.
The point is that primitives are lightweight entities that have a low memory footprint, whereas Objects can do more and therefore require a larger memory footprint. Also, you can't inherit from a primitive, whereas you can from an Object.
If you'll only be doing limited Object operations, using a primitive is the best approach, but if you know that you'll be using many properties of an Object, it's more efficient to create the Object using a constructor from the start to avoid the constant creation and destruction of wrapper objects.

Why are Strings JavaScript Primitives? [duplicate]

MDN states:
primitive, primitive value
A data that is not an object and does
not have any methods. JavaScript has 5
primitive datatypes: string, number,
boolean, null, undefined. With the
exception of null and undefined, all
primitives values have object
equivalents which wrap around the
primitive values, e.g. a String object
wraps around a string primitive. All
primitives are immutable.
So when we call a "s".replace or "s".anything is it equivalent to new String("s").replace and new String("s").anything?
No, string primitives do not have methods. As with numeric primitives, the JavaScript runtime will promote them to full-blown "String" objects when called upon to do so by constructs like:
var space = "hello there".indexOf(" ");
In some languages (well, Java in particular, but I think the term is in common use) it's said that the language "boxes" the primitives in their object wrappers when appropriate. With numbers it's a little more complicated due to the vagaries of the token grammar; you can't just say
var foo = 27.toLocaleString();
because the "." won't be interpreted the way you'd need it to be; however:
var foo = (27).toLocaleString();
works fine. With string primitives — and booleans, for that matter — the grammar isn't ambiguous, so for example:
var foo = true.toString();
will work.
The technically correct answer is "no".
The real-world answer is "no, but it will work anyway". That's because when you do something like
"s".replace()
the interpreter knows that you want to actually operate on the string as if you had created it with
var str = new String("s")
and therefore acts as if you had done that.

Everything is an object?

At one popular blog, the author asked his audience what was their “Ah ha!” moment for JavaScript and most of the people said that it was realizing that everything in JavaScript is an object.
But being new to JS and programming in general I don't quite get what that means. It doesn't seam like it's related to actual JS Object - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
Or it does?
If it doesn't could you please explain what do they mean by "everything in JavaScript is an object".
Or it's all about OO Programming in general and reading something on this subject will help to understand it? Can you recommend what to read on this topic?
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.
What they mean, most likely, is that any data that can be assigned to a variable has properties (and therefore methods) that can be accessed in an object like fashion.
// strings
"asdf".length; // 4
"asdf".replace('f', 'zxc'); // "azxc"
// numbers
(10).toFixed(2); // "10.00"
// booleans
true.someProp; // undefined (point is it doesn't crash)
They even have prototypes they inherit from.
"omg".constructor; // function String() { [native code] }
String.prototype.snazzify = function() {
return "*!*!*" + this + "*!*!*";
};
"omg".snazzify(); // "*!*!*omg*!*!*"
However, these are primitives, and while they behave object like in a lot of ways, they are different from other "real" JS objects in a few ways. The biggest of which is that they are immutable.
var s = "qwerty";
s.foo; // undefined, but does not crash
s.foo = 'some val'; // try to add a property to the string
s.foo; // still undefined, you cannot modify a primitive
Do note though that functions are real mutable objects.
var fn = function(){};
fn.foo; // undefined
fn.foo = 'some val'; // try to add a property to the function
fn.foo; // "some val"
So while it's not technically true that "everything in JS is an object", under most circumstances you can treat them mostly like objects in that they have properties and methods, and can potentially be extended. Just be sure you understand the caveats.
NOT everything in JavaScript is an object.
All data in JavaScript must fall into one of six primitive types, or the object type. Primitive types includes boolean, null, undefined, string, number and symbol; everything that is not a primitive is an object.
This means functions are objects, arrays are objects, ES6 classes de-sugars into a function which are objects.
The confusion arises because primitive values have object wrappers. When you try to access the length property on the string literal, JavaScript creates a temporary object wrapper around the primitive and access the length property of that object wrapper. After the property has been retrieved, the object wrapper is discarded. This is known as autoboxing.
Essentially, it is implemented similar to the following:
const foo = "bar";
// When you run `foo.length`, it's similar to
tmp = String(foo);
tmp.length;
delete tmp;
Or
const foo = "bar";
(new String(foo)).length;
The string, number and boolean primitives have object wrappers, but null and undefined do not. So trying to access a property or method from those primitives would throw an error.
null.length; // Uncaught TypeError: Cannot read property 'length' of null
undefined.length; // Uncaught TypeError: Cannot read property 'length' of undefined
Not everything is an object in JavaScript. For example a number is not an object.
Different languages have different definition of "object". For JavaScript, the official definitions can be found in the ECMAScript Language Specification, which states:
In ECMAScript, an object is a collection of zero or more properties
each with attributes that determine how each property can be used (...) Properties are containers that hold other objects,
primitive values, or functions. A primitive value is a member of one
of the following built-in types: Undefined, Null, Boolean, Number,
BigInt, String, and Symbol; an object is a member of the built-in type
Object; and a function is a callable object.
So by this definition it is clear that primitive values (like numbers) are not objects. Even strings are not objects, which is different from most other OO languages.
So why do some people say "everything is an object"? You have to ask them! But I suspect it is because they are getting confused by the built-in objects Number, Boolean, String etc. which can be used as wrappers around the corresponding primitive values. This wrapping sometimes happen automatically, which can make primitive values look like object and for example allow you to (seemingly) access properties on primitives. But in reality the properties are on the wrapper object.
'ALMOST everything is an object' because the MAIN code-units are JS-objects. On primitives you can NOT add members for example as on all objects. My answer why JS-functions are JS-objects here: https://stackoverflow.com/a/24811539

Why use {} instead of new Object() and use [] instead of new Array() and true/false instead of new Boolean()?

Many people say that you should avoid new Object, new Array()and instead use {}. [], and true/false.
What are the benefits of using the literal constructs to get a new instance of an Object or Array rather than using new? I konw that Crockford doesn't like new but is that the main argument?
The advantages of object and array literals over using the respective constructors are:
Shorter and more readable
Safer: literals will still work when the Array or Object constructors have been overridden
Possibly faster, though it's unlikely to be a major consideration (any bottlenecks will almost certainly originate elsewhere in code)
In the case of arrays, there's an additional advantage of a literal: it's impossible to create an array with a single member using the Array constructor alone. For example, [3] will create an array with one element which is the number 3, while new Array(3) creates an array of length 3.
Update: the following paragraph is no longer relevant now the question has been edited.
Regarding Booleans, you seem to have a misconception: new Boolean(false) is not the same as false. The Boolean() constructor creates a Boolean object whereas false and true are Boolean primitives. In fact, new Boolean(false) evaluates to true when coerced into a Boolean in, for example, an if statement. In short, there's very rarely a reason to use the Boolean() constructor. Use true and false instead. Similarly, other primitives such as strings and numbers have corresponding String() and Number() constructors that produce String and Number objects that are different to primitive strings and numbers and should generally be avoided.
For example, if you want to do this:
{name:"bla",address:"address"}
the new Object() way would be:
var o = new Object();
o.name="bla";
o.address="address";
The first one is much shorter. And I think that it would be faster in many browsers, too (jsperf testcase).
I think it's mostly about succinctness.
Why write new Array() when you can write [], or new Object() when you can write {}?
Also new Boolean() is entirely redundant. A boolean is always going to need to be either true or false, so you should definitely use the built in constants for that.
In most cases an object literal or array literal is sufficient and easier to use. You can even call or apply prototype methods (e.g. [].prototype.slice.call(someObj)) It's mostly faster too.
You'll may want to notice that {} and []‘s constructor cannot be overwritten and that
Object and Array are constructors where {} and [] are instances.
One reason not yet mentioned is the ambiguity when passing parameters to the Array constructor. It's all specified behavior, it's just quirky.
new Array(1,2,3); // [1,2,3], that's OK
new Array(1); // [undefined], some may expect to get [1] instead
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number. (See below.) Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Syntax

Every Object is a function and every function is Object - Which is Correct?

I was reading this link JavaScript_syntax
This seems to be cyclic - that every function is an Object and every Object itself is a function. Which is the atomic one? Can someone explain in a better way?
Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript. That means function inherits from object.
Object instances can contain more instances which can be functions. That's what we call a "method" (since it has an automatic this variable).
Since you can't "call" every Object instance, not every object is a function.
I think this concept is often misunderstood.
A utility to visualize JS types relationship http://jstype.herokuapp.com/#/home
Javascript Data Types
Primitive types - numbers, strings, booleans, null and undefined.
All non-primitive types are object:
var foo = { };
var foo = [1, 2, 3];
var foo = function abc() { return "hello world"; };
var foo = new Number(30);
var foo = new String("Hello World");
var foo = new Boolean(true);
var foo = new RegExp(/[foo]+/);
// All 'foo` are object.
All primitive types have a corresponding Constructor Function wiz. Array, Number, String, Boolean, RegExp. As all functions are objects, they are objects too. So we can call them Constructor Function Objects.
Most of the non-primitive type has prototype property where all inherited stuff lives. Math doesn't have prototype.
All objects inherit from Object.prototype which inherits from null.
object <- Object.prototype <- null
All native functions inherit from Function.prototype which inherits from Object.prototype.
function <- Function.prototype <- Object.prototype <- null
Arrays inherit from Array.prototype which inherits from Object.prototype.
array <- Array.prototype <- Object.prototype <- null
Must read MDN: Inheritance and prototype chain
To get confused Stackoverflow: prototype in JavaScript
Stack Overflow: Function prototype explained
Every function is an object. Objects can contain functions (methods) but an object is not necessary a function.
Also Function is always a property of an object.
This mean that all functions in JavaScript is always bound to an object. If you don't specify an object to bind a function to it's bound to the window object (Also called global functions)
..fredrik
It would be better to say that in JavaScript everything can be treated as an object, that includes primitive types as well as functions types; what the JavaScript interpreter does is that it automatically promotes your primitives and functions to their object wrapper types when you interact with them.
There is also a Function object, an a number of equivalent Wrappers for the other primitives in JavaScript, that means that you can even call methods on functions instances, like:
myFunction(someArg).call(this)
That being said, not every object is in fact a function.
As others have said, functions are objects that can be passed around by reference like other javascript objects. Not all objects are functions, only those that are declared as such.
You will often see methods declared like so:
var myFunc = function(foo, bar) {
...
};
This is to reinforce the fact that the method is a function object and as such it is a property of the object where it is defined, just like any other variable you might define with var.
This is the foundation of the most important feature in javascript, closure.
Every function is an Object.
I'm not an javascript expert, but I cannot see how every Object is a function. (I can see how every object could be a function, but that's different)
Quoting from Working with Objects - MDN Docs
section Using Object Initializers last paragraph:
"In JavaScript 1.1 and earlier, you cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose. See Using a Constructor Function."
meant that all objects WERE functions! Specifically, upon evaluation, instances or instantiations of functions.
Literally, ALL objects of that vintage were created syntactically with constructs like:
"newobj = new constructFunctor(arg1,arg2){this.prop1=arg1 /* etc */}(val1,val2)"
AND in the string that makes the object "newobj" there is the word "constructFunctor", the name of a function. The statement is intentionally quoted to impress the fact that it must be eval()'d to be executed. Prior to execution "newobj" is "equated to" a function because the statement MUST have one and "is" one by virtue of "constructFunctor"'s literal existence to define newobj's value upon execution. The quoting, and not, is very intentional in order to elucidate this abstraction. However, because JavaScript DOES have an eval function, this abstraction is in fact intentionally incorporated into the JavaScript language.
The legacy of this is still fundamental to JavaScript, though some syntactic short cuts have been added as "object initializers" using the shorthand notation like: "no={}". That the paragraph quoted above is still resident in the current documentation IS significant for the very reasons noted.
Furthermore, JavaScript also exemplifies the fundamental paradigms of Functional Programming. This defines everything as a function using the abstractions of Recursive Function Theory and the Lambda Calculus! For instance 0(), 1(), 2(), ... are the constant nonary functions better known as 0,1,2,3, ...
JavaScript is completely consistent with a Functional Programming Style approach rather than the common OOPS (pun intended Object Oriented Programming Style).
Just for supplementary to Aaron Digulla's answer.
In javascript not every object is a function. But Object,Array,String and many other built-in objects are functions that used with new operator to create object. I think this is what confused most people.
javascript everything is a hashtable. Ryan Dahl said this in one of his talks. thats what json is also; a hashtable definition. thats why u can access an object using array notation or object property notation. the value of the hashtable can be a function as well which is a hashtable. or rather an associative array
type Object in the console u get { [native code] } which is a hashtable
Object is an abstract data given to a class and that class is assigned to an object. Object can have properties and properties can hold values and functions.
Or simply for the sake of making it easy to understand you can say that anything that is not primitive data type (number,string, boolean, unll & undefined) can be classified as an object.
the selected answer by Aaron Digulla's is not 100% correct because it says,
Anything that is not a primitive type (undefined, null, number,
string, boolean) is an object.
but a string is an object. That is why you can do things like:
myString="Hello World";
x = myString.length;
newString = myString.toUpperCase();
link = myString.link("http://www.hello-world.com/");
And many other methods can be applied to the string object.
You could also initialize the string like:
myString = new String("Hello, World!");
But because a string is also a datatype it is much easier to initialize it by just applying a value.
Not necessarily an answer to the question ... just a clarification/correction of Aaron Digulla's answer.
The selected answer is wrong. In JavaScript everything is a function, except primitive types. Object itself is a function which is called function Object(). Use for example the following code:
<script>
alert(Object);
</script>

Categories

Resources