Drup
Drup

Reputation: 79

Variable values are populating incorrectly while multiple declaration

I am learning JavaScript basics. While doing multiple variable declaration in a single statement, getting different results.

var jhon, kate = " kate";
console.log(jhon + kate);
var jhon = "jhon ", kate = " kate";
console.log(jhon + kate);

Question : Why first console.log prints value for kate not for jhon?

Upvotes: 0

Views: 49

Answers (4)

Mayank Dudakiya
Mayank Dudakiya

Reputation: 3869

You should use = to assign a value to the variable not ,

var jhon = kate = "kate";
console.log(jhon + kate);

// Output will be : kate kate

Following approach is easily solve your issue which very easy to handle.

let
  jhon = 'kate',
  kate = 'kate',
  cena = 'foobar'
;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

For following a will equal 10 and b will equal 20.

var a, b;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

Upvotes: -1

kcsujeet
kcsujeet

Reputation: 522

what you want is

var jhon = kate = " kate";
console.log(jhon + kate);
var jhon = "jhon ", kate = " kate";
console.log(jhon + kate);

Upvotes: -1

Dng
Dng

Reputation: 131

var jhon,kate = " kate";

You defined 2 variables, but you only set value for kate. Due to the jhon is not set value, when you console.log it, it will be print undefined

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44125

Because doing this:

var jhon, kate = " kate";

Is equivalent to:

var jhon;
var kate = " kate";

Which is:

var jhon = undefined;
var kate = " kate";

Which, when concatenated, gives:

undefined kate

You simply haven't given jhon a value in the first example.

Upvotes: 4

Related Questions