En lugar de mis explicaciones complicadas aquí están mis ejemplos de código...
¿Qué me perdí?
(objX[elmX] ?? [400]).forEach(x=>{ console.log(x) })
o
(objX[elmY] ?? [400]).forEach(y=>{ console.log(y) })
líneas ?
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 }