How to debug anonymous functions

Hi when i run the following code, it will skip the logic and go straight to the end bracket without analysing line by line, which is what i intend to do. why does it not do this? and how can i fix this?

[i thought i could put a bracket at the start of anonymous functions to allow for this?]

String.prototype.toAlternatingCase = function () {

    let str = '';

    for (let i = 0; i <this.length; i++) {
  
        if (this[i].toUpperCase == true ) {
        str += this[i].toLowerCase()
    } else { 
  if (this[i].toLowerCase == true) {
  
        str += this[i].toUpperCase()
    }
   
  } 
    
     return str
  }

From my experience, functions aren’t debugged until they are called. so you have to call it afterwords to trigger for debugging.

a quick look at this and I can see that both if statements are not as you are intending.

(this[i].toUpperCase == true ) is not a true/false question

1 Like

hi thanks your help is appreciated! i understand the actual code but i am not really familiar with the function acting on the string prototype.

in this situation you posted, we must console.log(“original string”,callfunction())? This i don’t really understand. Can you please explain?


As for the second example below, i don’t understand why in my console log it return 1) the answer 2) undefined. why does it return two values?

String.prototype.toJadenCase = function () {
  return this.split(' ').map(word => {
    return word[0].toUpperCase() + word.slice(1);
  }).join(' ');
};

var str = "How can mirrors be real if our eyes aren't real";
var jadenStr = str.toJadenCase();
console.log(jadenStr);

See code at bottom, maybe this will answer both questions:

#1 you wrote:

var str = "How can mirrors be real if our eyes aren't real";
var jadenStr = str.toJadenCase();
console.log(jadenStr);

as @camperextraordinaire provided in example, the same as:

console.log("How can mirrors be real if our eyes aren't real".toJadenCase());

As for number 2; I don’t see any errors on my end. The first letter of each word is Uppercase and I didn’t see any undefined. I added 'toJadenCase test: into the console.log so you can verify you’re seeing a double callback from this.

Try this:

String.prototype.toJadenCase = function () {
  return this.split(' ').map(word => {
  	return word[0].toUpperCase() + word.slice(1);
  }).join(' ');
};

console.log('toJadenCase test: ' , "how can mirrors be real if our eyes aren't real".toJadenCase());

edit: note: this will break if you have more than 1 space …

  1. sorry i dont think i am being clear.
    why do we invoke like this: ‘haveFunToday’.toAlternatingCase())

i haven’t seen a function be invoked like this. usually the argument comes after the function and is inside the brackets e.g. toAlternatingCase(‘haveFunToday’). is there something i should know about this difference?

  1. thanks for that :slight_smile: