1

Hello, I am having a trouble with creating an object in Javascript.
I found something strange that when I used console in Chrome:

function person(){this.Name = "John";}
var a = new person()

Result: undefined

But if I do this

b = new person()

Result: Person {Name: "John"}

Is there any difference between using var keyword or not using it, when creating an object in javascript?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
pion123
  • 23
  • 4
  • Works fine here http://jsbin.com/nilef/1/edit. Omitting `var` creates a global variable. – elclanrs Feb 07 '14 at 01:43
  • duplicate of [What is the function of the var keyword in ECMAScript 262 3rd Edition/Javascript 1.5?](http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-in-ecmascript-262-3rd-edition-javascript) for the question. The strangeness just comes from what Chrome Console displays (or not). A *`var` statement* does not have a result value, while an *assignment expression* has. – Bergi Feb 07 '14 at 01:54

4 Answers4

3

Check the value of a, it's actually the same as b. undefined is just the result of the evaluation of the expression var a = new person().

Mr_Pouet
  • 4,061
  • 8
  • 36
  • 47
0

Inside a function, all undeclared variables are global. Only those declared with var are local. So in terms of scope yes it differs. If you are assigning value inside a function and printing outside, that explains your situation.

Serif Emek
  • 674
  • 5
  • 13
0

Chrome returns undefined for any statement that doesn't explicitly return a value.

e.g.

var j = "Jenny from the block";

returns

undefined

To fully run your code try

function person(){this.Name = "John";}
var a = new person();
console.log(a.Name);
jasonscript
  • 6,039
  • 3
  • 28
  • 43
0

It's just how the browser console works. It returns the returns value of whatever you execute. In this case, your statement returns undefined. Not scoping issues since the console runs under window scope. Happens in both firefox and chrome.

Console returns undefined

Community
  • 1
  • 1
clouddreams
  • 622
  • 1
  • 4
  • 13