1

When I Define variables in JS like this:

var a, b, c = 10;

I found out when call a,b,c this phrase (Or any other term that can be used) gives 10 value.

Now, i'm wondered and my question is what is that? and what type of this phrase? (Returned Number in console)

What is its use?

var a, b, c = 10;

a,b,c;       //10
a,   b,c;    //10
Amir
  • 1,184
  • 2
  • 9
  • 20
  • 2
    Uh, that will only assign the value `10` to `c` - the rest will be `undefined` but declared. – VLAZ Sep 09 '19 at 12:20
  • [That is the effect of the JavaScript `comma` operator.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) – Pointy Sep 09 '19 at 12:20
  • @VLAZ I think the OP is asking why typing something like `a,b,c` into the console will print `10`. (after such a declaration) – Pointy Sep 09 '19 at 12:20
  • 1
    @Pointy but...it doesn't print `10`. It prints `undefined` since it's treated as a declaration. – VLAZ Sep 09 '19 at 12:21
  • The question is clearer now @VLAZ. – Pointy Sep 09 '19 at 12:22
  • 2
    `c; // undefined`??? it should be `10` – VLAZ Sep 09 '19 at 12:22
  • @VLAZ thanks. I understood – Amir Sep 09 '19 at 12:25
  • 1
    Also relevant: https://stackoverflow.com/questions/9579546/when-is-the-comma-operator-useful – VLAZ Sep 09 '19 at 12:27
  • Thanks guys, I was careless – Amir Sep 09 '19 at 12:28
  • @pointy In this context the comma is used in combination with the var keyword for multiple assignments and is not the JavaScript comma operator. – Will Taylor Sep 09 '19 at 12:39
  • @WillTaylor look at the updated question. The comma is used in the code posted both in the context of a `var` declaration *and* in the context of a simple expression typed at the console. – Pointy Sep 09 '19 at 12:43

1 Answers1

2

The comma has 2 different means depending on context.

You use it in both these ways in your code sample - this is probably causing some confusion.

1) Multiple variable assignment using var

var a,b,c = 10;

Here the var keyword is used to assign multiple variables on a single line, in your case you only assign the final variable c, and so a and b are undefined.

Here is an example which makes its usage clearer:

var a = 1, b = 2, c = 3;

a; // 1
b; // 2
c; // 3

2) JavaScript Comma Operator

a,b,c; // 10

The JavaScript comma operator evaluates a comma separated list of expressions and returns the result of the last one.

Will Taylor
  • 1,232
  • 3
  • 20