2

If I write in console,

var x=0;

output=> undefined

And If write in console,

x=0;

output=> 0

Why so?

Tuhin
  • 3,335
  • 2
  • 16
  • 27
  • 12
    var x = 0 is a declaration and returns undefined(nothing). x=0 is assignment and returns the assigned value – Senthil Sep 01 '16 at 07:01
  • It is as @Senthilnathan said about declaration and assigment. Check this other question for more info: http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration – Jorgeblom Sep 01 '16 at 07:03
  • To be honest,using `var` depends on your scope, so if both were defined outside any scoped block (like, say, a function), they should both output 0. However, always declare your variables properly using `var` or the new block-scoped `let` or general `const`! – somethinghere Sep 01 '16 at 07:04
  • But when I am writing- var x=0; that means I am declaring as well as assigning. isn't? – Tuhin Sep 01 '16 at 07:07
  • Yes it is. Read the other question again. (Your question is worded more clearly, but it is asking the same thing.) – nnnnnn Sep 01 '16 at 07:11
  • Yes ,You are right @nnnnnn. Previously I went to Bommox link. Sorry – Tuhin Sep 01 '16 at 07:14
  • 1
    Well to answer your earlier comment about `var x = 0;` declaring as well as assigning, yes it is. But what the console then displays is the "result" of the `var` *statement*, which is `undefined` in that `var` doesn't return anything. (Whereas the result of the expression `x = 0` *without* the `var` is the value `0`. Which is why statements like `x = y = z = 0` work to assign `0` to all three variables.) – nnnnnn Sep 01 '16 at 07:15
  • Thanks man. It was blowing my head – Tuhin Sep 01 '16 at 07:16

0 Answers0