Why Is Accessing JavaScript Object Key Name With Scientific Notation Returning undefined?

Find out why JavaScript object property name with e-notation returns undefined

Numeric literals (including scientific notation) are valid object property names, that can be specified without quotes. Such properties can only be accessed using the bracket notation (i.e. object[number] syntax).

A common mistake people make is to access numeric literals using quotes, as it makes no difference with non-scientific notation numbers:

const obj = { 123: 'foo' };

console.log(obj[123]); // 'foo'
console.log(obj['123']); // 'foo'

However, the same is not true for scientific numbers, as the interpreter does not know whether you mean to access the object property name using string literal or numeric literal, as they're both valid, and distinct properties:

const obj = {
    12e3: 'foo',
    12e34: 'bar',
    12e+36: 'baz',
    1.23e+5: 'qux',
};

console.log(obj['12e3']); // undefined
console.log(obj['12e34']); // undefined
console.log(obj['12e+36']); // undefined
console.log(obj['1.23e+5']); // undefined

To access such properties, you should use the actual, unquoted, numeric literal represented by the e-notation (similar to how you would access array indexes), for example, like so:

const obj = {
    12e3: 'foo',
    12e34: 'bar',
    12e+36: 'baz',
    1.23e+5: 'qux',
};

console.log(obj[12e3]); // 'foo'
console.log(obj[12e34]); // 'bar'
console.log(obj[12e+36]); // 'baz'
console.log(obj[1.23e+5]); // 'qux'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.