Home > Net >  Javascript functions not working in console
Javascript functions not working in console

Time:03-29

So I have this code:

<script>
    function add7(n) {
        let x = n   7;
        console.log(x);
    }
    function lastLetter(theString) {
        let x = lastIndexOf(theString);
        console.log(x);
    })
</script>
<script>
    function multiply(a, b) {
        let ans = a * b;
        console.log(ans);
    }
</script>
<script>
    function capitalize(word) {
        if (word = String) {
            toLowerCase(word);
            charAt(0).toUpperCase(word);
            console.log(word);
        } else {
            console.log("not a string");
        }
    }
</script>

I write functionName(chosenVariable) in the console and expected to see a clear answer but add7 and lastLetter just returns ReferenceError (function) not defined. and the other 2 get undefined as an answer. I know that I am blind but am I also a bit stupid? I've looked at the code and tried different changes but cant get it to work.

CodePudding user response:

There were a few errors with your code

  • Extra ) at the end of the first script block
  • lastIndexOf is not defined anywhere on your script
  • word = String will just assign the value of the String class to the word variable (and always return true)
  • Strings are immutable, so you can't edit an existing string you can however create a new string based on another, so using word.toLowerCase() on it's own won't do anything, you need to reassign the value

add7(2);
lastLetter("123123");
multiply(2, 3);
capitalize("asd");

function add7(n) {
  let x = n   7;
  console.log(x);
}

function lastLetter(theString) {
  let x = theString[theString.length - 1];
  console.log(x);
}

function multiply(a, b) {
  let ans = a * b;
  console.log(ans);
}

function capitalize(word) {
  if (typeof word === "string") {
    word = word.toLowerCase();
    word = word[0].toUpperCase()   word.substring(1);
    console.log(word);
  } else {
    console.log("not a string");
  }
}

  • Related