Reputation: 61
I have been trying to understand dot notion and how can we create dot notion
Simply state, consider this example
const a = [1,2,3,4,5,7].reduce((a, i) => a*i)
Here how can we use dot
notion.
From my understanding, we use dot notion in case of object.
probably Array
have a prototype named reduce
? and reduce
accepts 4 arguments.
But how do we tell reduce to iterate over the loop. We aren't passing it the entire array?
Upvotes: 0
Views: 422
Reputation: 18619
Arrays are special objects. But the usability of dot notation doesn't depend on the object, but rather the property you want to access.
Also note that foo.bar
is the same as foo['bar']
.
You can always use bracket notation. On the other hand, dot notation can only be used if the property is a valid identifier (consists of letters, numbers, $
s and _
s, and can't begin with a number).
That shows the reason why we can't access arrays' indices with it, as they are numbers (so they also begin with numbers).
The bracket notation is also required if you want to access a key named the result of evaluating an expression.
So:
const object = {
0: 1,
foo: 2,
'key with spaces': 3,
'3D': 4,
'D3': 5
}
const array = [1, 2, 3]
//These are okay...
object.foo
object['foo']
array.reduce
array['reduce']
object[0]
array[0]
object['0']
array['0']
object['key with spaces']
object['3D']
object.D3
object['D3']
object['f' + 'o'.repeat(2)]
array[array.length-2]
//...but these are not:
object.0
array.0
object.key with spaces
object.3D //begins with a number
Upvotes: 0
Reputation: 25
The reduce function is a built in javascript function which works only with arrays.
You don't tell explicitly to 'reduce' to iterate all over the array because it(reduce function) is already coded such that it does something(add, sum, multiply, whatever expression you may provide) with that array.
If you really want to know what is going on the background, you can see this torque file which is from V8 engine's source code==>https://github.com/v8/v8/blob/master/src/builtins/array-reduce.tq
From what I understood, it also uses a for loop inside the function.
For that you should also have understanding of TorqueScript.
You can check any open source engine for that matter.For more details about how to view the code and where exactly, visit this link==>https://stackoverflow.com/questions/22300206/how-to-see-the-source-of-built-in-javascript-functions
So to answer your question => it simply just calls reduce and rest of the work is taken care by it in the background, that's not really associated with 'dot notion'.
Upvotes: 0
Reputation: 36564
When we add any method to prototype
of the class we can always access the instance of the class on which this method is called by this
.
Array.prototype.test = function(){
console.log(this);
};
[1,2,3].test()
Upvotes: 1