Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How is var making a difference?

Tags:

javascript

var

See the below snippets. First one errors out, which is expected. Second one passes. What is the reason, or difference between the two snippets.

var myvar = 4,7 //Error

myvar2 = 3,4 //No error
like image 370
anand patil Avatar asked Sep 02 '26 09:09

anand patil


2 Answers

In the first line, you are separating declaration by comma (Variable Statement), here is missing a variable name.

The second line is using the Comma Operator, which works fine, even there is no need for it.

The question arised

If second was a comma operator, then the value in myvar2 would be 4. but it is 3!

It is because of the Operator Precedence of comma versus equal. The assignment is made and the comma is evaluated later.

like image 190
Nina Scholz Avatar answered Sep 04 '26 22:09

Nina Scholz


The first line basically translates to this:

var myvar = 4,
7

So the "second line" throws the error because the JavaScript intepreter expects you want to assign two variables but cannot find a name for the second one. For example you could assign your variables like this

var first = 0,
    obj = {},
    s = "my string",
    array = [1,2,3,4,5];

Without getting an error since it is valid JavaScript and every value has a variable name it can be assigned to.

In the second example you are only assigning the last number - without the var keyword JavaScript does not throw an error and just assigns the first value. It is kind of like writing the following

myvar = 3
4

So the first value is assigned. I previously mixed this up (see history). When passing myvar = 3,4 to the console it looks like 4 would be assigned, however it is just printed into the console - in other words the part behind the , is evaluated. You can see this when you paste the following into the console

myvar = 3, _this_function_doesnt_exist()

Here the parser will throw an error: Uncaught ReferenceError: _this_function_doesnt_exist is not defined(…) - the previous expression (myvar = 3) is still executed so myvar will be 3.

I used to write all my variables with only one var keyword but found it rather confusing and ugly. In general I advice to use one assignment per line and var in front of every variable (or const, let, etc. if you write ECMAScript 2015/ES6)

like image 36
Kevin G. Avatar answered Sep 05 '26 00:09

Kevin G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!