[SOLVED] What's wrong with my camel case method?

Goal: Write a method that turns a string into camel case.

My code:
String.prototype.camelCase=function(){ if (this === "") { return ""; } else { var arr = this.trim().split(' '); for (var i = 0; i < arr.length; i++) { arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1); } return arr.join(''); } }

The code works fine except for when the input is an empty string, "". like "".camelCase();.

The console gives me this error

TypeError: Cannot read property 'toUpperCase' of undefined at String.camelCase at Test.describe._ at /runner/frameworks/javascript/cw-2.js:179:21 at Promise._execute at Promise._resolveFromExecutor at new Promise at Object.describe at Object.handleError at ContextifyScript.Script.runInThisContext at Object.exports.runInThisContext
This is from codewars.
It seems that the empty string is bypassing the if statement and the code stops when .toUpperCase() is called on "".

Not sure why this is happening, thanks for any help!

edit: Solved thanks to @kevcomedia! Switched this === '' to this.length === 0

I think it’s because this is an object (not a string), so (this === '') always returns false. How about using this.length === 0?

1 Like

is ok

Please don’t post screenshots of your code. You can format your code in the comment box with three backticks.
See this post for details.

That worked great, thanks Kev! Studying this has been on my to-do list for awhile.