r/JavaScriptTips • u/[deleted] • Feb 20 '22
Learning Javascript, trying to understand camelCase. Why does capitalization matter in the left side of the equation, but not in the right? Example included.
Learning Javascript, trying to understand camelCase. Why does capitalization matter in the left side of the equation, but not in the right? Example included.
Trying to learn Javascript and using FreeCodeCamp's example. Having a difficult time learning how capitalization is applied and why it matter in some instances, but not others.
See example problem below!
// Setup
const lastName = "Lovelace";
// Only change code below this line
const secondToLastLetterOfLastName = lastName[lastName.length - 3]; // Change this line
If the const is defining Lovelace as forever and it will never change, doesn't that mean I have to write lastName as intended too, with the lower level "L"?
Why is in the second const, I have to capitalize the L in Last? That would make it not constant or const, no?
Unless the rules don't apply, and it's camelCase only to the right side of equation? but in the left, it has to follow camelCase? Or does camelCase always apply everywhere?
We are defining lastName as a const, so shouldn't it also be lastName and NOT LastName?
3
u/punkmuppet Feb 20 '22
Essentially the capitalisation is for humans, not computers. Other fairly common formats are using_underscores_between_words or using-dashes. It usually doesn't matter which one you use, but camelCase is likely the most popular as it's just the easiest to type while still being readable. Just as an example, I found this style guide from Google which says to use CAPITALS_WITH_UNDERSCORES when using const, and it lets you know at a glance that it's a constant. I haven't seen this taught in any tutorials I've done though. Just remember it's a fluid thing, it's always being improved, and the styles will change and improve too. Things like naming conventions will only really matter once you start working with other people. Just make sure you use names that clearly state what the variable is, and that aren't too hard to read.
I think what you're asking is why should you be using secondToLastLetterOfLastName instead of secondToLastLetterOflastName? If I'm right, then you absolutely can, it wouldn't make a difference, but the program doesn't understand from the name that secondToLastLetterOflastName has any connection to lastName. The connection is made after the = sign.
If it helps you keep track though there's nothing wrong with using it that way.
However not using the given variable names might cause you to fail the tests on FreeCodeCamp, but that doesn't mean the code isn't valid, just that it can't find the variables it's expecting.