why isnt .length a method that requires () - javascript

In JavaScript why doesn't the keyword length require ()? It seems all the other functions such as splice(), shift() require parenthesis.

We can only speculate why it was made a plain property and not a method.
However, the .length is a constant value for each string/array, it does not modify anything when being computed (it's not "executed" like a method), and it would not take any parameters anyway. Therefore it qualified well as an accessor property.
Also, assigning to .length allows us to control the size of the array (shrinking/expanding it). It's more convenient (or at least: idiomatic) to use the existing property as a setter than to introduce an extra .setLength(…) method.

Length is not a method. It is a property. See MDN
When calling properties you do not need parentheses.
A property is something that an object "knows" about it self. An array or a string in javascript knows its length. A method is something that needs to be calculated.
Length could have been a method on javascript strings if javascript had really needed to count the letters each time you want the length.
When get a value from a property you can make an assumption that it is quicker to get its value than it would be getting a value from a method call. (Although this is not always the case)

splice and shift are operations that calculate something based on the current state and/or their parameters. Furthermore they change the array. length in contrast is constant for a given array, no operation need to retrieve it. There is no need to make it a function.

length is a property, not a function. therefore it doesn't need brackets().
The length property is calculated and updated when the objects changes, while calling a function length() would calculate this value upon each single call.

Adding to my comment
The JavaScript array length property returns the number of elements in an array.
It is always one greater than the largest index value of the array
One can if required( not advisable) change the length property
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
The EcmaScript language specification, designed the length to be a property.
Read Here

Related

How do I access the 'str' value in my object?

I am trying to return the value under the key 'str' in an Object but I am having trouble accessing the value.
This is what is returned in the console:
Currently I am using a map function to go over the array and just return the _str value like so:
let idx = currentArray.map(function(x) {
return x._id._str;
});
However it is still returning the value as an object. How can I get just the value of the _str key?
Here is the full array without specifying the id field. This is what is returned if you jsut return 'x' in the map function.
You've clarified that the screenshot is of x._id. So to access _str, you'd use x._id[0]._str: The _str property is in the object referenced by the 0 property (the first entry in the array x._id refers to).
Note that in general, _-prefixed properties are meant not to be accessed by code outside the code responsible for the objects in question. You don't seem to be responsible for them, so accessing those properties is likely to make your code rely on undocumented properties that may change in the next "dot" release of whatever lib you're using. It's just convention, but it's a very common convention.
If you right click on the property, most browser consoles offer the ability to copy property path.
Based on this SO post and the docs, it appears that you can probably use x._id.str.
If I understand correctly, you are receiving the str value but it is an object instead of the string literal. In other words, you are getting _str: "598..." instead of "598....". A possible solution would be to use the mongo javascript function to convert the str value to a string.
In your case, I think something like return x._id.str; may work as _id is a MongoID.ObjectID.
I've also linked the documentation below for reference.
https://docs.mongodb.com/manual/reference/method/ObjectId/
Here's a relevant SO answer as well: Convert ObjectID (Mongodb) to String in JavaScript
I think you should write x[_id]._str because _id is one of the array objects.

Property is faster than method? Need reason for it

As I google this question so one person give answer that property is faster than method and give one example of size() and length.
He said length is faster than size because length is property. Can you please let me know is it correct ? Or If you will give example then it will be great for me.
size internally calls the length
//http://code.jquery.com/jquery-latest.js
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
So if you are using length then you are avoiding one extra method call. The Jquery docs says:
The .size() method is functionally equivalent to the .length property;
however, the .length property is preferred because it does not have
the overhead of a function call.
I am assuming that you want to get the length of a String or the number of elements in an Array.
size() is not a method of the Array or String objects. Thus if it exists some library or you yourself have added this method to the respective prototypes. length on the other hand is a default property and (should) exist in any JS runtime.
Unless you cannot use length, the size function will just add unneeded overhead and I would go for the property.
Check the following to links:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype
If you will read length property then only time required to access an object property will be needed.
However if you will call size() then first of all a function will be called, this function will read length property internally and then return that value to the caller.
You can clearly see that you are doing the same thing in both cases. But if you call the function then it will include time for calling a function + returning that value too..
Length returns the same thing and is slightly faster according to the jQuery documentation.
Source: http://api.jquery.com/size/

strange ng-model behaviour (ng-model mapped to array element)

What should be the right behaviuor when you have a ng-model declaration like this one?
data-ng-model="elements[0]"
The way it works, if elements is already defined in the scope as an array, it works as I'd expected assigning the first element of the array.
But if elements is not declared it assigns this value :
elements = {0:'anyvalue'}
(which makes sense if I'd had written data-ng-model="elements['0']")
In this case :
elements[0]='anyvalue';
elements['0']='anyvalue';
and I cannot read the value of the propery using "dot" notation (elements.0 or elements.'0').
So it looks correct, but a bit weird.
Is this behaviour correct, or it should instantiate an array when the scope variable is not defined?
An array is just a special type of object. If you look at an array in a debugger, all of the values are listed as properties with numeric keys, like the one you show. If you don't initialize the object as an array, it would still accesses the object in the same way, which just means you now have an object with numeric keys and none of the helpful functions from the Array prototype.

Difference between defining and assigning property

What is the difference between assigning a property to an object and defining it?Which one is better and how?
This
Object.defineProperty(obj,p,propDesc)
Or simply
obj.p="someValue";
Object.defineProperty lets you set a whole bunch of options about that property. Like enumerable and writable.
When you do obj.p = 'something';, you're setting a property with the "default" options.
Neither is "better", they each have their own uses. Which one you use depends on your requirements.
As found on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
"
This method allows precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults."

Can a DOM object be an index/key in Javascript array?

Would like to maintain a map/hash of DOM objects. Can they serve as key objects? If not, what are the alternatives, please? If there are better ways - kindly enlist them as well.
You can put anything as the key, but before actual use it is always converted to string, and that string is used as a key.
So, if you look at what domObject.toString() produces, you see it is not a good candidate. If all of your dom objects have an id, you could use that id.
If not, and you still desperately need a key based on DOM object, you probably could do with using, for example, _counter attribute with automatic counter in background putting new unique value in a DOM object if _counter is not yet present.
window already maintains all DOM objects as properties. Instead of putting your own keys for each 'DOM object' try to use window or document object and methods that uses index based on the layout of DOM tree.
No, because object keys are strings.
You'd have to "serialise" your objects by id or something, then perform a lookup later. Probably not worth it, depending on what your actual goal is here.
No, but you can set an attribute on the DOM element that contains a number, which you would have as the index in a numerically-indexed array.
Easiest is to set a data-attribute on the element instead.
Not exact. But I think you want something like below. You can do with jquery,
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types
Refer below link :
http://api.jquery.com/serializeArray/

Categories