specifications - JavaScript increment unary operator (++) on strings - Stack Overflow

I am on Chromium Version 53.0.2785.143 Built on Ubuntu, running on Ubuntu 16.04 (64-bit)According to th

I am on Chromium Version 53.0.2785.143 Built on Ubuntu, running on Ubuntu 16.04 (64-bit)

According to the ECMAScript® Language Specification, prefix increment operator is evaluated as follows:

With this in mind, I cannot explain this result:

++'1';
> Uncaught ReferenceError: Invalid left-hand side expression in prefix operation

when the following code works like a charm:

var x = '1'; 
++x;
> 2

As far as I understand, in both cases the first 3 bullet points of the second step are true, whereas for ++'1' case the fourth bullet is also true (but why?) and for the ++x case it is false, raising no error. Am I right?

PS: Firefox throws a SyntaxError: invalid increment operand instead of a ReferenceError

I am on Chromium Version 53.0.2785.143 Built on Ubuntu, running on Ubuntu 16.04 (64-bit)

According to the ECMAScript® Language Specification, prefix increment operator is evaluated as follows:

With this in mind, I cannot explain this result:

++'1';
> Uncaught ReferenceError: Invalid left-hand side expression in prefix operation

when the following code works like a charm:

var x = '1'; 
++x;
> 2

As far as I understand, in both cases the first 3 bullet points of the second step are true, whereas for ++'1' case the fourth bullet is also true (but why?) and for the ++x case it is false, raising no error. Am I right?

PS: Firefox throws a SyntaxError: invalid increment operand instead of a ReferenceError

Share Improve this question asked Oct 12, 2016 at 13:56 iulianiulian 5,8423 gold badges32 silver badges40 bronze badges 2
  • 1 You get the same error if you do ++1, by the way – Joseph Young Commented Oct 12, 2016 at 13:58
  • 1 PutValue('1', 2) throws an error because it cannot assign to a string literal. You need a variable or some other kind of Reference. – Bergi Commented Oct 12, 2016 at 13:59
Add a ment  | 

2 Answers 2

Reset to default 10

The problem is that your ++ operator implicitly involves an assignment, and you can't assign a new value to a string constant. Note that

++2;

is also erroneous for the same reason.

In my understanding, ++ is similar to += 1.

So it will work for ++x as it will be evaluated to x+=1 or x=x+1, but ++'1' is a string literal and does not has left hand side value to assign, hence it fails

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

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信