-4

I am seeing sort of strange behaviour with javascript. I am new to this language, but from what I can see, if you increment a variable (or change it in any way) from within a console.log() method, this actually globally changes the variable.

var a = 0;

console.log(a); //prints 0

console.log(a++); //prints 0, a becomes 1
console.log(a++); //prints 1, a becomes 2
console.log(a++); //prints 2, a becomes 3

console.log(a); //prints 3

Is this something peculiar to javascript? I would have thought that the variable would not get affected globally and that the last print statement would show a as being 0.

Baba.S
  • 154
  • 1
  • 11
  • Related: [javascript i++ vs ++i](https://stackoverflow.com/q/6867876/5894241) – Nisarg Aug 07 '17 at 09:25
  • using `a++` is using a `post-increment` operation.. I don't see anything wrong here – kukkuz Aug 07 '17 at 09:26
  • Yes that is perfectly normal. The console runs with the same scope as the `window`, or the page you are on. You're not running those bits of code in isolated scope, so they affect the page and its contents. – Reinstate Monica Cellio Aug 07 '17 at 09:26
  • Its not the increment operator I have a problem with. It is the fact that statements from within a console.log() function can globally modify a variable. – Baba.S Aug 07 '17 at 09:28
  • You're not using it "within" `console.log`, whatever that means. Your code is equivalent to `var b = a++; console.log(b);`. Not sure why you think inlining it into a function call would somehow isolate `a`. – deceze Aug 07 '17 at 09:29

1 Answers1

1

Using ++ will affect the variable, if you want to do it only for log purposes, you must use +1 , this is how it works in javascript ^^

var a = 0;

console.log(a); //prints 0

console.log(a+1);
console.log(a+1);
console.log(a+1);

console.log(a); //prints 0
Marco Salerno
  • 4,889
  • 2
  • 8
  • 27