In JavaScript, there are two main categories of properties and methods associated with arrays: static properties/methods and instance properties/methods. These categories differ in how they are accessed and what they are used for:
Static Properties/Methods:
Static Methods:
- Static methods are called directly on the constructor function, which, in the case of arrays, is
Array. - They are not called on specific instances of arrays but rather on the array constructor itself.
- Static methods are used for creating new arrays or transforming data into arrays.
- Examples of static methods include
Array.of(),Array.from(), andArray.isArray().
const newArray = Array.of(1, 2, 3); // Static method- Static methods are called directly on the constructor function, which, in the case of arrays, is
Static Properties:
- Static properties are properties associated with the constructor function.
- They are accessed using the constructor name (
Array) and the property name. - An example of a static property is
Array.length, which returns the number of arguments expected by the constructor.
const length = Array.length; // Static property
Instance Properties/Methods:
Instance Methods:
- Instance methods are called on specific instances of arrays (i.e., array objects that you create).
- They operate on the array instance and return a result based on the content of that specific array.
- Instance methods are used for array manipulation, iteration, and other operations.
- Examples of instance methods include
push(),pop(),concat(), andforEach().
const myArray = [1, 2, 3]; myArray.push(4); // Instance methodInstance Properties:
- Array instances also have properties that provide information about the array.
- These properties are accessed on specific arrays and provide details like the
lengthof the array. - Instance properties are used to query or get information about a particular array instance.
const myArray = [1, 2, 3]; const length = myArray.length; // Instance property
In summary, the key difference is that static properties/methods are associated with the array constructor itself (Array) and are used for creating or transforming arrays and providing information about the constructor. In contrast, instance properties/methods are associated with individual array instances and are used for performing operations on specific arrays and accessing information about those arrays.