+2  A: 
var foo = myarray[myarray.length - 1];

The preferred term is element, rather than key.

EDIT: Or do you mean the last index? That is myarray.length - 1. Keep in mind, JavaScript arrays can only be indexed numerically (though arrays are also objects, which causes some confusion).

Matthew Flaschen
It can be wrong,you should have a look at that post.
What "can be wrong"?
Matthew Flaschen
@user198729 Arrays in JavaScript work differently than PHP. PHP implements them as sparse arrays which is why the index of the first/last element aren't always 0/len-1. In JavaScript all arrays are dense arrays, zero-base, fully populated (maybe undefined) index elements from 0 to .length-1.
nicerobot
+1  A: 

The last key of an array is always arr.length-1 as arrays always start with key 0:

var arr = new Array(3);  // arr === [], arr.length === 3
arr.push(0);             // arr === [undefined, undefined, undefined, 0], arr.length === 4
arr[arr.length-1]        // returns 0

var arr = [];            // arr === [], arr.length === 0
arr[3] = 0;              // arr === [undefined, undefined, undefined, 0], arr.length === 4
arr[arr.length-1]        // returns 0
Gumbo
+1  A: 

If it's a flat array, this would do:

return array.length - 1;

However, if you have an associative array, you'd have to know the key and loop through it. Please note though that JavaScript knows no such thing as an "associative array", as most elements in JavaScript are objects.

Disclaimer: Usage of associative arrays in JavaScript is generally not a good practice and can lead to problems.

var x = new Array();
x['key'] = "value";
for (i in x)
{
    if (i == 'key')
    {
        alert ("we got "+i);
    }
}
Aron Rotteveel
Why use an `Array`? You're not using the arrayness of it (i.e. the magic `length` property) so you might as well use an `Object`. Also, the JavaScript spec makes no guarantee about the order of the keys when using a `for...in` loop, so there's no such thing as the "last key"
Tim Down
In the first example, I used the length property. Since this property is not available on associative arrays, I added the second example, which cleary demonstrates a use case of a "simulated last key". Since the OP would know the name of the last key, it would be possible to get the actual element with the above method.
Aron Rotteveel
Re. the length property, I was referring to the second example, not the first.
Tim Down
Ah, I understand. OP specifically asked how to get a key in an `Array`, so that's why (even though it is technically still an `Object`). There are probably more refined ways to do this.
Aron Rotteveel