
Array Size Method
javascript Array size method is not a method that exists in an array because the array has a length property that provides the length of the array. But in javascript, we can create a new method that attaches to the array prototype.
So, new method can be created and attach to array. Let’s have an syntax of array prototype
Array.prototype.clear = function(){
// statement
}
For more detail about the javascript array prototype click here.
JavaScript Question
In this javascript quiz, find out can array has the size method like a set because the array has a length property, not a size method.
First, we add a prototype method to the array with a method name size in which we return the length of the array.
Array.prototype.size = function(){
return this.length;
}
In the next step, we create an variable with name array and assign an javascript array which contain only number.
let array = [1, 2, 3];
Now we use the size method and print it’s value using console log.
console.log(array.size());
Any idea what should be the output of above code statement.
JavaScript Quiz Test
Here is the full javascript code snippet for you to solve.
Array.prototype.size = function(){
return this.length;
}
let array = [1, 2, 3]
console.log(array.size()); // output => 🧐 ?
// Made with ❤️, by @jsstartup
Answer – 3
Click To Run Code
Explanation
Now, you know the answer is “3“. But why because array doesn’t have a size method. Let me explain.
So, first, we add javascript size method in array as prototype which means it can directly use that method.
And inside that, we can see that it return length with this keyword. Because this holds the array.
As a result, the size() method works because we can create a custom array prototype method.
At last, That’s why we get an answer “3“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
Check out our other javascript quiz –
- JS Quiz – effect of misplaced semicolon after if statement
- JS Quiz – what does triple value compare 10 > 9 > 8 return
- JavaScript Quiz – does it shift array element to the right
- JavaScript Quiz – does false compare with false return false
Conclusion
To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.