Only half of if statement works

Wondering if anyone can spot where I am going wrong in my code. (It is part of a larger function)

split.map((x, i) => {
    if(x.match(/[A-Z]/)){
      let result = res.toString()
      final = (result[i].toUpperCase() + res.slice(1)).replace(/,/g, '')
    } else {
      final = res.join('')
    }
  })

The first half works fine when there is no else statement after it (or before it) but doesn’t work when there is the else statement. Basically it just always runs the else statement… ?

Looks like final was never declared.

Check what match returns (hint: it isn’t a Boolean). I suspect you wanted the regex method test instead.

1 Like

Do I check it like this?

let split = ['a', 'B', 'c']

split.map((x, i) => {
    if(x.match(/[A-Z]/)){
      return; 
    }
})

It returns [undefined, undefined, undefined]
Not sure what to conclude from this… but thanks I will look into .test()

a function that returns nothing returns undefined

try to console log the expression with the match method, or check the documentation

1 Like

Sorry for being dim - what does check the documentation mean?

I tried console logging but not sure how this helps me work out my issue… I tried it with .test() instead of .match() too and it is the same outputs

let split = ['a', 'B', 'c']

split.map((x, i) => {
    if(x.match(/[A-Z]/)){
      console.log(x);  // B
    }
    return x // ['a', 'B', 'c']
})

Also tried doing this instead of regex:

if(x === x.toUpperCase()) {
  .....
} else {
.....

but again, it’s always the lowercase version that runs.

So maybe it’s something to do with the rest of my code, will have a deeper dig!! Thanks :slight_smile:

actually put the match method in the console.log
or check the description of the match method, for example on devdocs.io

console.log(str.match(...))

map producing a new array with every one of the new values the result of running that callback function on the original value.

So if I remove the condition here you basically have:

['a', 'B', 'c'].map(character => {
  console.log();
});

If you extract that function, and run it, what is the return value?

function mappingFunc (string) {
  console.log(string);
}

Whatever that return value is, that’s going to be what the respective value in the new array is.


Next, check what match returns as @ilenia says:

"B".match(/[A-Z]/)

Is it a true or a false value? Because you’re using it in an if statement, and you want the test you’re doing on the string to return true or false depending on what x is. Does match do this?