W3docs

How to Get the First Key Name of a JavaScript Object

Read this JavaScript tutorial and learn about two methods of getting the first key name of an object. Get one-liner codes and make your work done properly.

In this tutorial, we will discuss the two methods of getting the first key of a JavaScript Object.

Object.keys

Since objects do not have index referencing, you can't complete your task by just calling for the first element or last element.

For that purpose, you should use the Object.keys method to get access to all the keys of the object.

Then you can use indexing like <kbd class="highlighted">Object.keys(objectName)[0]</kbd> to get the first key:

JavaScript Object.keys method

javascript— editable

The for...in Loop

The second method is for...in loop. Try it and break after the first iteration so as to get the first key of the object:

JavaScript for..in loop and break

for (let prop in obj) {
  console.log(prop);
  break;
}

Example:

JavaScript for..in loop and break after the first iteration

javascript— editable

Object.keys() and for...in

<kbd class="highlighted">Object.keys()</kbd> returns an array of the object's own enumerable string-keyed properties in insertion order.

<kbd class="highlighted">for...in</kbd> iterates over all enumerable properties of an object, including those inherited from the prototype chain. An enumerable property is a property where the internal [[Enumerable]] attribute is set to true.