Science Knowings: JavaScript Course For Social Media

Object.getOwnPropertyNames() Method

Object.getOwnPropertyNames() Method

Welcome back! In this session, we'll dive into the Object.getOwnPropertyNames() method, a powerful tool for inspecting and working with JavaScript objects.

What is Object.getOwnPropertyNames() Method?

The Object.getOwnPropertyNames() method returns an array of all the property names (both enumerable and non-enumerable) of a given object.

Syntax of Object.getOwnPropertyNames() Method

Object.getOwnPropertyNames(obj)

Parameters of Object.getOwnPropertyNames() Method

  • obj: The object whose property names are to be returned.
  • Return Value of Object.getOwnPropertyNames() Method

  • An array of all the property names of the given object.
  • Use Cases of Object.getOwnPropertyNames() Method

  • Iterating over all the properties of an object.
  • Getting a list of all the enumerable properties of an object.
  • Checking if a property exists on an object.
  • Example of Object.getOwnPropertyNames() Method

    const obj = { name: 'John', age: 30 };
    const propertyNames = Object.getOwnPropertyNames(obj);
    console.log(propertyNames); // Output: ['name', 'age']

    Advantages of Object.getOwnPropertyNames() Method

  • Easy to use.
  • Works on both enumerable and non-enumerable properties.
  • Returns an array of property names, which is convenient for further processing.
  • Disadvantages of Object.getOwnPropertyNames() Method

  • Does not return the values of the properties.
  • Does not return the prototype properties of the object.
  • Conclusion

    The Object.getOwnPropertyNames() method is a versatile tool for working with JavaScript objects. It allows you to easily get a list of all the property names of an object, regardless of their enumerability.

    Next topic will be: Object.getOwnPropertySymbols() Method

    In the next session, we'll explore the Object.getOwnPropertySymbols() method, which allows you to get a list of all the symbol properties of a given object. Follow us to learn more!