javascript - conditional ternary operator is giving error: Expected an assignment or function call and instead saw an expression

I would like to set a param for knowing what uri to use when a certain port is called.Here is my code

I would like to set a param for knowing what uri to use when a certain port is called.

Here is my code:

  var portConfig = '443';
    (portConfig === '443') ? uri = 'wss://' : uri = 'http://';
    console.log(uri);
    var Ip = uri + "hereis.myurl";
    var port = portConfig;
    console.log(Ip);

I am getting the following error:

Expected an assignment or function call and instead saw an expression

I have even set the uri's to be inside of a function testA testB but the same error occurs. I have read up on the issue and it just seems like an erroneous error. Should I use the if statement instead -- which works fine?

I would like to set a param for knowing what uri to use when a certain port is called.

Here is my code:

  var portConfig = '443';
    (portConfig === '443') ? uri = 'wss://' : uri = 'http://';
    console.log(uri);
    var Ip = uri + "hereis.myurl.";
    var port = portConfig;
    console.log(Ip);

I am getting the following error:

Expected an assignment or function call and instead saw an expression

I have even set the uri's to be inside of a function testA testB but the same error occurs. I have read up on the issue and it just seems like an erroneous error. Should I use the if statement instead -- which works fine?

Share Improve this question edited Jul 22, 2016 at 20:19 nicael 19.1k13 gold badges62 silver badges92 bronze badges asked Jul 22, 2016 at 20:18 Christian MatthewChristian Matthew 4,3895 gold badges37 silver badges47 bronze badges 1
  • A ternary can't contain assigment, the returned value could however be assigned. – adeneo Commented Jul 22, 2016 at 20:21
Add a ment  | 

2 Answers 2

Reset to default 7

The correct way per documentation is:

uri = (portConfig === '443') ? 'wss://' : 'http://';

It does indeed expect the assignment, not the expression.

In fact, the way you use could be eaten and parsed without the errors by the browser, since an assignment returns the assigned value. But it's not the remended way, since the ternary operators were designed to return the value (and they do it always, even if you don't use the value afterwards), unlike if() conditions, and it's considered not wise to use it like you use if().

This is how you should write it

uri =  (portConfig === '443') ? 'wss://' : 'http://';

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744198260a4562757.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信