I am trying to make a function which could return a string in to Camelcase.
so For example if i enter "Adamsmith", it should return "aDaMsMiTh".
The below code has some error but can't figure out.
function crazyCaps (string1) {
const lower_string = string1.toLowerCase();
let crazystring = '';
for (let i=0; i<lower_string.length; i++) {
const Crazy = lower_string[i];
if (i%2 ===1) crazystring +=Crazy[i].toUpperCase();
else crazyString +=Crazy[i];
}
return crazystring;
}
Top comments (2)
The above code contains multiple issues, that'll try to explain and how they can be fixed.
Original
Running the above function
crazyCaps('Adamsmith')
within the console produced the first error:This is due to the fact you've interchanged the variable name crazystring with crazyString, these need to reference the same variable name. As you've declared the crazystring variable then I would suggest that the crazyString is changed to crazystring.
Refactor 1
Running the above function
crazyCaps('Adamsmith')
within the console produced the second error:This is due to the fact the Crazy variable is being accessed with an indexer
Crazy[i]
, but it's not an array, it's a string. So we need to change all references to Crazy[i] to just Crazy.Working Version - Refactor 2
Ultimately the above issues / errors could've been avoid if a static typing language was used such as TypeScript or Flow. Also think about adding unit tests via Jest or another testing framework.
TypeScript Version - Refactor 3
TypeScript Playground Version
Hope this makes sense and let me know if you need any further help with the explanation.
What does the error say?