Javascript arrays? - javascript

This may be completely stupid but given I type this into my browser console:
var arr = [];
arr.item = 'val';
console.log( arr );
arr;
What is the arr; syntax doing behind the scenes? I'm assuming console.log( arr ); is iterating all the properties of the arr object but what is arr; doing? Also does [] tell me I'm dealing with an object of type array and {} tells me I'm dealing with an object of type object literal? So [ item: 'val' ] is an object with a prototype of array and { item: 'val' } is an object of prototype object literal?
Edit: Another way to ask this might be why are console.log and arr; different?

Sorry, started to type the comment and realized it was actually a full answer.
console.log yields an implementation dependent string representation of the argument. It does not iterate the properties of an object in most I've seen. String serializtions using the default toString method look like [object Foo] where 'Foo' is the internal class property of the object. You can see this for arrays by using Object.prototype.toString.call([]);.
The last line on the other hand, is just the value. How that gets represented as an evaluated expression in your browser console is implementation-dependent, but for all intents and purposes it does nothing and there is no reason you would want to write that.
Note that adding a property to an array with the . operator is almost never what you want: it does not add to the contents of the array but treats the array as an object. Iterating the indicies of the array will not yield that property, nor will its methods such as .map include it. Use .push. If you want string-keyed properties, use an object.

What is the arr; syntax doing behind the scenes?
This is an ExpressionStatement. The JavaScript engine tries to evaluate the expression by reading the value of the variable, and then does nothing with it. If it occures inside a javascript function, it will do nothing (except when arr is not a variable, it will throw an error). If you just write arr; into the developer console, most browsers will echo the value of the last typed in expression, so you will see the value of arr as a result. The echoing mechanism is often implemented similar to console.log;
I'm assuming console.log( arr ); is iterating all the properties of the arr object
console.log prints a value to the developer console. If the value is a string, then the string gets printed. If the value is an object, then it is browser-dependent what happens. Most browsers, like Chrome will show an interactive representation of the object, like this:
Other browser might just call toString on the object, which in fact will iterate over the elements, and join them by commas.
Also does [] tell me I'm dealing with an object of type array and {} tells me I'm dealing with an object of type object literal?
Yes and yes. [1, 2, 3] is an array literal, which will evaluate to a new instance of an array containing those values. [] is just an empty array. Arrays are instances of the type Array. {a:1,b:2} is an object literal, will evaluate to a new instance every time. {} is an empty object with no fields. Object literals evaluate to instances of the type Object.
So [ item: 'val' ] is an object with a prototype of array and { item: 'val' } is an object of prototype object literal?
No and yes. [ item: 'val' ] is invalid syntax. Array literals have elements separated by commas, they cannot have colons in them.
[ item: 'val' ]
VM154:1 Uncaught SyntaxError: Unexpected token :(…)
The : is the unexpected token, the expression can't be evaluated because it has syntax errors.
On the other hand { item:'val' } is a completely regular object literal with type Object and will have a single field named item with value 'val'.
About object properties
In javascript, object do not have a fixed set of properties. Properties can be dynamically added and removed by writing them and by using the delete keyword. Every object has string (or Symbol) field names. An array can be seen as an object, optimized for integer keys. But still, keys are strings, so a[0] means the same as a["0"].
var arr = [1, 2];
arr.item = 'val'; // assigns a new field to the object, called item
arr['item'] = 'val'; // does exactly the same as the previous
arr[1] = 3; // sets the second item in arr to 3
arr['1'] = 3; // does exactly the same as the previous
console.log(arr);
// prints [1, 2, item: "val"]
So arbitrary named fields can be assigned on an array, and when printed, Chrome does notice the object being an array, so uses array notation, but also prints the 'other' assigned values. It's important to mention that not every field gets printed, as arr.length is a fully featured property. It is the way guys at Google chose to print arrays. It is not a valid JavaScript syntax, it is just a (pretty good) visualisation of data inside an array.
About classes and prototypes
We say that foo is of class Foo if foo has the prototype Foo.prototype, in other words foo.__proto__ === Foo.prototype. Here foo is an object, Foo is a constructor function. As Foo itself is a function, Foo.__proto__ === Function.prototype.
If subtypes are involved, then we can say bar is an instance of Foo, if bar has Foo.prototype in it's prototype chain, i.e.: bar.__proto__ === Foo.prototype || bar.__proto__.__proto__ === Foo.prototype || .... Explicitly accessing an object's .__proto__ property is considered a bad practice and is strongly discouraged. Altering the __proto__ value leads to serious performance drop, because it breaks the browser's optimisation strategies. So how to check if an object is of a type? You can use the instanceof operator.

Related

What are "non-existent property values" in ECMA spec for ARRAY:SORT

In an answer for this question (which otherwise I can fully understand/etc), there'a this curious quite:
From the spec, 15.4.4.11 :
Because non-existent property values always compare greater than
undefined property values, and undefined always compares greater than
any other value, undefined property values always sort to the end of
the result, followed by non-existent property values.
I've checked in the latest version available now and it's "note 1" at the end of sort spec, and it's basically the same as it was when that answer from 2011 was written.
Regarding undefined property values always sort to the end of the result, followed by non-existent property values -- how can it be? what are "non-existent property values"(*)? if we write a.foo and a doesn't have such property, we'll get undefined, so how can it be differentiated?
The sort is called either without any parameter, or with a comparer-style function, and in the latter case, it's our function, and we're bound to read the non-existent property and get undefined.. The sort can't inspect the object's keys for us to decide whever an inspected object has a property or not (in contrast to i.e. certain underscore/lodash helpers where you define a 'path' like i.e. pluck or get). I just dont see how we could trigger this "non-existent property values" case at all.
(*) I've found something that looks like a definition of this term here:
A non-existent property is a property that does not exist as an own property on a non-extensible target.
(...)
If the target is non-extensible and P is non-existent, then all future
calls to [[GetOwnProperty]] (P) on the target must describe P as
non-existent (i.e. [[GetOwnProperty]] (P) must return undefined).
This must-describe-as-nonexistent and must-return-undefined seem to support my doubt.
I've also noticed that the pseudo-code for SortIndexedProperties (used to define sort) actually contains bits like 3.b. Let kPresent be ? HasProperty(obj, Pk).. So maybe that non-existent property part in sort spec meant to cover some case like the array being mutated by the comparer function and certain keys are removed from it?
A non-existent property on an array will be "included" when sorting only if the array is sparse. Here's an example, look at the comments:
const arr = []; // 0-length array
arr[2] = 'foo'; // Turns into 3-length array. Does not have own properties 0 or 1
arr.sort();
console.log(arr[0]); // Sort result includes a value from defined property
console.log(arr.hasOwnProperty(1)); // But not from the sparse elements
console.log(arr.length); // But the array will have the same length as originally
As you can see, the properties that didn't exist on the original sparse array are "sorted" to the end of the array, and don't exist on the resulting sorted array either, except for the .length of the sorted array. It started out as an array with a length of 3 and only one own-property, and ended up as an array with a length of 3 and only one own-property (but with that own-property at a different index).
if we write a.foo and a doesn't have such property, we'll get undefined, so how can it be differentiated?
It's equivalent to a .hasOwnProperty check:
const obj1 = {};
const obj2 = { foo: undefined };
console.log(obj1.hasOwnProperty('foo'));
console.log(obj2.hasOwnProperty('foo'));
const arr1 = ['abc'];
const arr2 = [, 'def']; // sparse array
console.log(arr1.hasOwnProperty(0));
console.log(arr2.hasOwnProperty(0));
Best approach to all of this - never use sparse arrays to begin with, they're too confusing.

Extra Object in prototype chain of Number object [duplicate]

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...
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:
Create a wrapper String object from s, equivalent to using new String(s)
Call the substring() method with the appropriate parameters on the String object returned by step 1
Dispose of the String object
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
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.
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
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"
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"]).
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)"

Why does the isArray() Javascript method in this example returns true, if the array has been redefined as a standard object?

I'm trying to learn Javascript - here's my issue:
In the w3schools.com javascript array examples, they show the sequent example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
document.getElementById("demo").innerHTML =
person[0] + " " + person.length;
An array "person" has been defined, but then they proceed to add some elements whit a "named" index. Then tries to print the HTML document the 0th element and the number of elements of the array, like you would do with a standard array.
The description says:
If you use a named index when accessing an array, JavaScript will
redefine the array to a standard object, and some array methods and
properties will produce undefined or incorrect results.
In fact, person[0] and person.length return respectively "undefined" and "0". Even is person was initially defined as an array, by inserting new named indexes elements, the array should be redefined as an object. But when i try do use the Array.isArray() method for checking it, it returns true:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
document.getElementById("demo").innerHTML =
person[0] + " " + person.length;
document.getElementById('test').innerHTML = Array.isArray(person);// returns true
So, why? if, as specified by the tutorial, this has been effectively redefined as a standard object, and the ECMAScript 5 has added the .isArray() method for checking if something is an array and nothing else, shouldn't this return false insted of true?
I'm sure i missed something. If i define person like this:
person = {};
then it returns false, as expected. What is happening here? I just wanted to understand arrays a little bit more, this confuses me. Is this just a broken array, but still an array?
Here's the example (without the Array.isarray() bit, just the default): https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_associative_2
First of all I want to note that the example you took from the w3schools page on arrays, is from the "Associative Arrays" section, which has this important introduction:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
This puts the example into context, because it really makes no sense to define a variable as an array and then use string keys. But this was an example to illustrate the point.
Does an Array become an Object?
That JavaScript still considers the variable to be an array is as expected. It becomes an array at the moment of assignment of [], and that does not change by adding properties to that object. Yes, arrays are objects. They just have additional capabilities.
The array did not lose any of its array-like capabilities, but those features just don't work on those string properties, ... only on numerical ones (more precisely, the non-negative integer ones).
You loosely quoted the following statement from w3schools:
If you use named indexes, JavaScript will redefine the array to a standard object.
That is wrong information and leads to your misunderstanding. There is no redefinition happening. When you add properties to any object, then the object does not change "type". It remains an instance of what it was before... An array remains an array, a date object remains a date, a regex object remains a regex, even if you assign other properties to it. But non-numerical properties do not "count" for an array: the length will remain unchanged when you add such properties. The length only reveals something about the numerical properties of the object.
This quote is yet another illustration of what the JavaScript community thinks about w3schools.com, i.e. that it is not the most reliable reference, even though it has its value for learning the language.
Example of adding useful properties to arrays
Having said the above, there are cases where you may intentionally want to make use of such properties on arrays. Let's for example think of an array of words that is sorted:
const arr = ["apple", "banana", "grapefruit", "orange", "pear"];
Now let's add something to this array that denotes that it is currently sorted:
arr.isSorted = true;
We could imagine a function that would allow one to add a value to this array, but which also verifies if the array is still sorted:
function addFruit(arr, fruit) {
if (arr.length && fruit < arr[arr.length-1]) {
arr.sorted = false;
}
arr.push(fruit);
}
Then after having added several values, it would maybe be interesting to verify whether the array needs sorting:
if (!arr.sorted) arr.sort();
So this extra property helps to avoid executing an unnecessary sort. But for the rest the array has all the functionality as if it did not have that extra property.
An object that is set up as an array and then filled as an object becomes a member of both classes. Methods of the Array class will apply to its 'array-ness':
Array.isArray(person);
returns true. Methods of the Object class will apply to its 'object-ness':
typeof(person);
returns object. When it could be either one, the 'array-ness' will prevail, because the variable was first defined as an array:
console.log(person);
will put Array [ ] on the console, because it runs the Array class's logging method. It is displayed as an empty array, since it has no numbered elements, but you could add some:
person[2]=66;
and then console.log would log Array [ <2 empty slots>, 66 ].
I think the polyfill implementation of isArray() will clear your doubt by some extent.
#Polyfill

Why is swapping characters this way valid JavaScript?

I am getting confused on how this snippet of code works. I would assume that the A would need to be 'A' in order for these two characters to swap, but it works. Also, is there a name for what this is doing? From the looks of it, I think it is destructuring, but I'm not certain.
var translations = {
A : 'U'
};
console.log(translations['A']); //returns U
I would have assumed you need to write it this way:
var translations = {
'A' : 'U'
};
console.log(translations['A']); //also returns U
https://jsfiddle.net/ud37asp8/14/
Object or property keys can be either an identifier name (i.e. identifiers + reserved words), a string literal, or a numeric literal. It does not really matter whether you call it A or 'A' in the way of accessing it. https://ecma-international.org/ecma-262/6.0/#sec-object-initializer
Property names
Property names must be strings. This means that non-string objects
cannot be used as keys in the object. Any non-string object, including
a number, is typecasted into a string via the toString method.
var object = {};
object['1'] = 'value';
console.log(object[1]);
This outputs "value", since 1 is type-casted into '1'.
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value';
console.log(object[bar]);
This also outputs "value", since both foo and bar are converted to the
same string. In the SpiderMonkey JavaScript engine, this string would
be "['object Object']".
Also what you are doing is basically creating an Object. I do not see you destroying it anywhere.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
Creating objects
However, the advantage of the literal or initializer notation is, that
you are able to quickly create objects with properties inside the
curly braces. You simply notate a list of key: value pairs delimited
by comma. The following code creates an object with three properties
and the keys are "foo", "age" and "baz". The values of these keys are
a string "bar", a number 42, and another object.
var object = {
foo: 'bar',
age: 42,
baz: {myProp: 12}
}
Accessing properties
Once you have created an object, you might want to read or change
them. Object properties can be accessed by using the dot notation or
the bracket notation. See property accessors for detailed information.
object.foo; // "bar"
object['age']; // 42
object.foo = 'baz';
One can think of an object as an associative array (a.k.a. map,
dictionary, hash, lookup table). The keys in this array are the names
of the object's properties. It's typical when speaking of an object's
properties to make a distinction between properties and methods.
However, the property/method distinction is little more than a
convention. A method is simply a property that can be called, for
example if it has a reference to a Function instance as its value.

A Function that can be an Object in JavaScript? [duplicate]

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...
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:
Create a wrapper String object from s, equivalent to using new String(s)
Call the substring() method with the appropriate parameters on the String object returned by step 1
Dispose of the String object
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
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.
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
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"
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"]).
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)"

Categories

Resources