# Format a phone number function

Here is a function that formats a phone number and adds a country code prefix if it is not included in it.

So, as an in input value it could be, for example, '23581010' or '4923581010' and in output it would become via the formatNumber function '(02) 358 10 10'.

Is the positioning of the let assignment ok in this code ? If something else feels not ok can you tell me ?

import { formatNumber } from 'libphonenumber-js';

export const formatGermanPhoneNumber = phoneNumber => {
if (!phoneNumber) {
return '';
}

const phoneNumberString = ${phoneNumber}; let prefix = ''; if (!phoneNumberString.startsWith('49')) { prefix = '49'; } return formatNumber(+${prefix}\${phoneNumberString}, 'National');
};

• @DDA This and your last question ask to review some (hypothetical?) stub code without giving any further context. You can check our help center how to ask good questions. Also we cannot know what the agreed coding standards and guidelines are at your company. Your peer reviewer probably simply relies on these. Jan 25, 2020 at 10:17
• Sorry I don't know what 'stub code' means ? I have added the import line as well of the third party library being used.
– DDA
Jan 25, 2020 at 10:30
• Does this help? Jan 25, 2020 at 10:35
• This question is missing an exact description of which countries this code is intended to cover. Jan 25, 2020 at 16:00
• Good point. I have renamed the function to "formatGermanPhoneNumber()" to be more specific.
– DDA
Jan 25, 2020 at 20:05

I don't know of any coding standards or other reasons why you should have to move it higher. Generally it's just personal preference and whichever is more readable.

As for the fact that you'd need to create a variable unnecessarily in some cases, creating a variable like this uses very little memory so it shouldn't be an issue unless the function is being looped over thousands of times.

You could also consider another option, which is to use a ternary rather than mutating a variable: let prefix = phoneNumberString.startsWith('49') ? '49' : ''

• Thank you for your answer. My co-workers are a little allergic to the use of ternary. They think it makes the code less readable. I guess it is a question of preference there too :)
– DDA
Jan 25, 2020 at 9:52
• That ?: is backwards. Jan 25, 2020 at 12:27

While your coworkers may dislike ?:, I would recommend putting the blank line before the declaration/initialization of prefix instead of after. This groups the setting of prefix together.

• Good point. Thank you.
– DDA
Jan 25, 2020 at 20:07