Search code examples
javascriptnative-code

why i get [native code] when use my function


I'm trying to create a function which inverts string's letters case, so the string "John" will be "jOHN".

Here is my code:

const upperLower = function(string){
  let newString ="", newChar ="";

  for(let i = 0; i < string.length; i++){
    if (string.charAt(i) === " "){
      newChar = " "
    } else if (string.charAt(i) === string.charAt(i).toUpperCase()){
      newChar = string.charAt(i).toLowerCase;
    } else {
      newChar = string.charAt(i).toUpperCase;
    }
    newString += newChar;
  }
  return newString;
}

When I'm using it, what i get is something like this:

"function toLowerCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] } function toLowerCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toUpperCase() { [native code] }function toLowerCase() { [native code] }"

Where i'm getting wrong, and why my result looks like that? Thanks


Solution

  • You're not actually calling toLowerCase or toUpperCase in your else conditions. You're referencing them, so you get the default string representation of the functions.

    {newChar = string.charAt(i).toLowerCase}      // <=- Not calling
    else {newChar = string.charAt(i).toUpperCase} // <=- Not calling
    

    You need the () to actually call the function, like you do with toUpperCase().

    Unrelated, but the formatting of your code makes it quite difficult to read.

    Making it easier to read makes it easier to debug and think about. If everything wasn't all mushed up the error would be very clear.

    const upperLower = function(string){
      let newString ="", newChar ="";
      for (let i=0; i < string.length; i++) {
        if (string.charAt(i) === " ") {
          newChar = " "
        } else if (string.charAt(i) === string.charAt(i).toUpperCase()) {
          newChar = string.charAt(i).toLowerCase()
        } else {
          newChar = string.charAt(i).toUpperCase()
        }
       newString += newChar;
      }
    
      return newString;
    }
    
    console.log(upperLower("hELLO"));