I am new to JavaScript. I have created a indexof function in but it is not giving the correct output: Question is: /* Implement a function called indexOf that accepts two parameters: a string and a character, and returns the first index of character in the string. */

This is my code:

function indexOf(string, character) {
  let result = string;
  let i = 0;
  let output = 1;

  while (i < result.length) {
    if (result[i] === character) {
      output = output + indexOf[i];

  return output;

I want to know what i am doing wrong. Please Help.

3 Answers

Geuis On Best Solutions

Assuming from your question that the exercise is to only match the first occurrence of a character and not a substring (multiple characters in a row), then the most direct way to do it is the following:

const indexOf = (word, character) => {
  for (let i = 0; i < word.length; i++) {
    if (word[i] === character) {
      return i;

  return -1;

If you also need to match substrings, leave a comment on this answer if you can't figure it out and I'll help you along.

yourfavoritedev On

indexOf() is a built in method for strings that tells you the index of a particular character in a word. Note that this will always return the index of the FIRST matching character.-

You can write something like:

function indexOf(string, character){
   return string.indexOf(character)

So if I were to use my function and pass in the two required arguments:

indexOf("woof", "o") //this would return 1
Mark Meyer On

You are making things a little harder than you need to. If you want to do this without calling the built-in indexOf(), which I assume is the point of the exercise, you just need to return from the function as soon as your condition matches. The instructions say "return the first index" — that's the i in your loop.

If you make it through the loop without finding something it's traditional to return -1:

function indexOf(string, character) {
    let i=0;
    while(i < string.length){
        if(string[i] == character){  // yes? just return the index i
            return i
        i++                          // no? increase i and move on to next loop iteration
    return -1;                       // made it through the loop and without returning. This means no match was found.
console.log(indexOf("Mark Was Here", "M"))
console.log(indexOf("Mark Was Here", "W"))
console.log(indexOf("Mark Was Here", "X"))