user1767962
user1767962

Reputation: 2109

javascript - Uncaught ReferenceError: keys is not defined

I am getting an error when I run the following command in an included script. But if I run the command from the google chrome console, it works properly.

var a = {};
console.log(keys(a));

Error:

 Uncaught ReferenceError: keys is not defined 

What's going on here? How can I use the keys function in an included script?

Upvotes: 45

Views: 28965

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 187242

console.log(keys(a))

keys() is not function provided by the browser for use in your code. You probably want Object.keys()

a = {};
console.log(Object.keys(a));

Sometimes the console has extra functions exposed to it for ease of use debugging that aren't available in your actual code. keys() sounds like one, and copy('some text') is another.

I'm failing to find a link which lists them, sadly. But I'm quite sure there are more than those 2 functions.

Upvotes: 54

David G
David G

Reputation: 96845

Whenever you get an error like this, try to search for a definition of the function/variable that's been reported as undefined. If it is defined, try looking for a reason this might not be working. Did you know that the keys function is apart of the Object constructor? You can't call it as if it's a free-standing function. Though if you get into the habit of doing this, try making your own function to allow this:

function key( object ) {

    return Object.keys( object );

}

Your code should pass given a definition like this.

Upvotes: 1

Related Questions