Is using data types like 'string' as parameters bad practice?

Simple question but is using the word ‘string’ as a parameter bad practice? I feel it may be but struggling to find a definitive answer.

Below I use string as a parameter as I am expecting a string.

const logWord = string => return console.log(string);

Any thought be appreciated thank you. :grinning:

1 Like

Hello @bitace66152, welcome to the forums! In general, it is considered bad practise, for two reasons: firstly, it can make the reader think you are using a keyword or similar (and can thus be confusing), or it can actually be a keyword, and is therefore very confusing. I would recommend something like strng or similar (which reads very similarly to string), but isn’t.

2 Likes

Welcome to the forums. :slight_smile:

If you want to get technical about it, since JS is a case-sensitive language you’d want to avoid String as that’s how the primitive and its constructor are identified. string, all lowercase, isn’t strictly a reserved word… but may not be the best choice for the situation.

Consider:

Personally it would make more sense to me to have the parameter word, like so:

const logWord = word => console.log(word);

Doing this for the function in question works fine, as you have a single parameter - but if you had a more complex function which took more than one string, it may not be as useful to someone reviewing the code to have parameters named string1, string2, etc over a descriptive name reflecting their purpose within the function, e.g. forename, surname, salutation

I get why you’d want to do some type hinting, so that it’s clearer what you’re expecting to be provided, since JS has a very lax concept of type. If this is your thing, you might want to consider TypeScript which takes JavaScript but extends it to include things like type.


I’ve also dropped the return, as since you’ve written a one-liner using arrow notation the return is implied. (You may find that the function as you’ve written it also doesn’t work…)

2 Likes

Hey mate. Thank you so much for taking the time this is so helpful.

All makes sense for sure. I guess coming from a little c++ and always explicitly showing types is what I was trying to do, but your implementation of ‘word’ in this case makes more sense and in programs like you mentioned using more descriptive words like firstName, lastName etc makes sense to.

I did not know about Typescript but am intrigued now so will definitely take a look thank you.

JavaScript seems so ambiguous at times, so I guess Typescript tries to create a more structured best practices approach which seems great.

Thanks again for your help.

Hey! Thanks so much for taking the time. Makes sense for sure. Using more descriptive parameters like word, or firstName etc is the way to go then.

Thanks again for taking the time.

1 Like