Borislav Hadzhiev
Tue Mar 08 2022·2 min read
Photo by Rodolfo Carvalho
The JavaScript error "Identifier directly after number" occurs when a variable starts with a digit or we try to call a method directly on a digit. To solve the error, rename your variables to not start with a digit and wrap numeric literal in parenthesis when calling methods.
Here are 2 examples of how the error occurs.
// 👇️ Because we call method directly on digit // ⛔️ SyntaxError: Identifier directly after number const result1 = 5.toFixed(2); const result2 = 5.toString() // 👇️ Because variable (or identifier) starts with digit // ⛔️ SyntaxError: Identifier directly after number const 501employee = 'James Doe'
In the first example, we call a method directly on a numeric literal and get the error.
To get around this, we have to wrap the numeric literal in parenthesis.
const result1 = (5).toFixed(2); console.log(result1); // 👉️ "5.00" const result2 = (5).toString(); console.log(result2); // 👉️ "5"
JavaScript won't allow us to call a method directly on a numeric literal, so we had to wrap it in parenthesis to solve the error.
An alternative solution is to extract the number into a variable.
const num = 5; const result1 = num.toFixed(2); console.log(result1); // 👉️ "5.00"
You might also get the error if you have declared a variable whose name starts with a digit.
// ⛔️ SyntaxError: Identifier directly after number const 501employee = 'James Doe'
_
or a dollar sign $
. Which means you aren't allowed to start a variable name with a digit.However, you are able to use digits for the subsequent characters of a variable name.
const employee501 = 'James Doe'; console.log(employee501); // 👉️ "James Doe"
This rule also applies to object properties and any other identifiers.
const company = { // ⛔️ Identifier starts with number 501employee: 'James Doe', }
Make sure to start the names of your identifiers with a letter, an underscore
_
or a dollar sign $
to avoid this error.
const company = { employee501: 'James Doe', }; console.log(company.employee501); // 👉️ "James Doe"