Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How JS forEach works with ternary and if operators?

I am trying to understand about 2 hours what I am doing wrong in third and fourth line of code. The console thows out SyntaxError: Unexpected token if or SyntaxError: missing ) after argument list. The first and the second line works as expected.

let arr = ['Custy Stomer', 'C. Oostomar', 'C.U.S. Tomer', 3432434, 'Custo Mer', 'Custopher Ustomer', 3432435, 'Kasti Yastimeur'];

let checkArr = (arr) => arr.forEach(el => console.log(typeof el !== 'string'))

let checkArr = (arr) => arr.forEach(el => if (typeof el !== 'string') { console.log(`Type error: ${el} should be a string!`)} )

let checkArr = ((arr) => { arr.forEach(el => typeof el !== 'string' ? console.log(`Type error: ${el} should be a string!`) : null; )})

checkArr(arr);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Line 3:

Wrap the forEach callback body in brackets

let checkArr = (arr) => arr.forEach(el => {
  if (typeof el !== 'string') { 
    console.log(`Type error: ${el} should be a string!`);
  } 
})

Line 4:

Remove semi-colon

let checkArr = (arr) => { 
  arr.forEach(el => typeof el !== 'string' ? console.log(`Type error: ${el} should be a string!`) : null )
}

Recommended:

const checkArr = (arr) => {
  arr.forEach(el => {
    if (typeof el !== 'string') { 
      console.log(`Type error: ${el} should be a string!`);
    } 
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading