Search code examples
node.jstypescriptstring-concatenation

NodeJS string concatenation unusual behaviour


I am trying to construct this string for printing one message.

"At position #[" + index + "][" + _subIndex + "] TLPHN_DVC_TYP " +
                                    + _telNum?.TelephoneDeviceType.toString() + " ,allowed " + telephoneDeviceTypeEnum.join(',');

from watch is VsCode: where index =0;_subIndex =0;telNum.TelephoneDeviceType =Mobile;telephoneEnum=["Mobile","Landline"];

It's returning :

At position #[0][0] TLPHN_DVC_TYP NaN ,allowed Mobile,Landline

Full Code:

if (_telNum?.TelephoneDeviceType && !(telephoneDeviceTypeEnum.indexOf(_telNum.TelephoneDeviceType) > 0)){
    console.log( "At position #[" + index + "][" + _subIndex + "] TLPHN_DVC_TYP " +
                                        + _telNum?.TelephoneDeviceType.toString() + " ,allowed " + telephoneDeviceTypeEnum.join(','));
    }

the condition should not satisfy but not sure why it's going inside the if and NaN returning. any suggestion?


Solution

  • It's the two plus signs: "] TLPHN_DVC_TYP " + + _telNum?// ...etc. The second one is parsed as the unary +, or a conversion to number, which obviously fails. Compare:

    console.log("foo" + "bar"); 
    
    console.log("foo" + + "bar");

    Added #1:

    if (_telNum?.TelephoneDeviceType && !(telephoneDeviceTypeEnum.indexOf(_telNum.TelephoneDeviceType) >= 0)){
        console.log( "At position #[" + index + "][" + _subIndex + "] TLPHN_DVC_TYP " +_telNum?.TelephoneDeviceType.toString() + " ,allowed " + telephoneDeviceTypeEnum.join(','));
        }