JavaScript – First key from associative array

First element of an array - JavascriptWorking with arrays is very beneficial for every developer in every language. But in different languages some operations are done differently. Very good example is retrieving first key from an associative array in JavaScript. In PHP you could use “foreach“, “list“, “array_pop“, “array_slice“, etc. But in JavaScript we don’t have all that functions so we have to stick to what the language offers us. Here is the actual tip:
[cc escaped=”true” lang=”javascript”]function getFirstKey( data ) {
for (elem in data )
return elem;

var myArray = {a: 1, b: 2, c: 3, d: 4};
// This will give us “a”
var firstKey = getFirstKey(myArray);
// This will give us “1”
var firstValue = myArray[firstKey];


Just a guy with strong interest in PHP and Web technologies

Tagged with: , , ,
One comment on “JavaScript – First key from associative array
  1. Kamran Saeed says:

    Great tip! Worked perfectly for me. Thanks!!!

Leave a Reply to Kamran Saeed Cancel reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.