0

Rather than my complicated explanations here are my code examples...

What did I miss on

(objX[elmX] ?? [400]).forEach(x=>{ console.log(x) })
or
(objX[elmY] ?? [400]).forEach(y=>{ console.log(y) })
lines ?

const objX = 
  { 'aa' : [ 101, 102, 103 ] 
  , 'bb' : [ 201, 202, 203 ]
  , 'cc' : [ 301, 302, 303 ]  
  } 

const elmX = 'bb' // valid key for objX
const elmY = 'yy' // invalid key for objX


console.log("objX[elmX] -->", JSON.stringify(objX[elmX] ?? [400])  ) // [ 201, 202, 203 ]
console.log("objX[elmY] -->", JSON.stringify(objX[elmY] ?? [400])  ) //  [400]
 
console.log( '? isArray( elmX )', Array.isArray( (objX[elmX] ?? [400]) ))  // true
console.log( '? isArray( elmY )', Array.isArray( (objX[elmY] ?? [400]) ))  // true

console.log( '? length( elmX )', (objX[elmX] ?? [400]).length )  // 3
console.log( '? length( elmY )', (objX[elmY] ?? [400]).length )  // 0

let arrX = objX[elmX] ?? [400]  // 


console.log( '- elmX - arrX -------->')
arrX.forEach(x=>{ console.log(x) })
console.log( '----------------<')

console.log( '- elmX ---------------->')
(objX[elmX] ?? [400]).forEach(x=>{ console.log(x) })  // --> error console.log(...) is not a function
console.log( '----------------<')

console.log( '- elmY --------------->')
(objX[elmY] ?? [400]).forEach(y=>{ console.log(y) })  // --> error console.log(...) is not a function
console.log( '----------------<')
 
.as-console-wrapper {max-height: 100%!important;top:0 }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • Which of those many lines are you confused about? Only the ones at the bottom? – CertainPerformance Jan 15 '22 at 23:05
  • @CertainPerformance I have updated my question to show my confusing lines – Mister Jojo Jan 15 '22 at 23:08
  • 4
    I'd suggest always using semicolons unless you're an expert and can avoid the pitfalls of ASI - add them at the end of statements and your problem will disappear – CertainPerformance Jan 15 '22 at 23:09
  • 3
    Missing semicolons causes the JS engine to expect `console.log()` to return a function, because it will be interpreted as `console.log(...)(objX[elmX] ?? [400])`. This has nothing to do with null coalescing operating, but the fact that you're wrapping it inside `(...)`, which indicates a function call when concatenated with `console.log()` without semicolons. – Terry Jan 15 '22 at 23:10
  • thank you all, I tested all sorts of things for hours, but not the semicolon thing – Mister Jojo Jan 15 '22 at 23:14

0 Answers0