verystrongjoe
verystrongjoe

Reputation: 3921

What is the difference between giving value inside function and give value out of function?

I can't understand. maybe I need javascript concept.

var test = function() { var x = '3'; var y = '4'; };
console.log(test.x);

the result is undefined

var test = function() { var x; var y; };

test.x = '3'; 
test.y = '4';

console.log(test.x);

It is working.

I can't understand why.

Upvotes: 0

Views: 71

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075597

In your first example:

var test = function() { var x = '3'; var y = '4'; };

you're creating a function that declares two local variables that only have meaning within the function. Since you never create an x property on the function object, console.log(test.x) is indeed undefined.

In your second example:

var test = function() { var x; var y; };

you're again creating local variables that have no meaning outside the function. Then, completely unrelated to those, you do this:

test.x = '3'; 
test.y = '4';

which creates properties on the function object for x and y. That x and y have nothing whatsoever to do with the local variables inside your function.

Since you've added those properties to the function object, console.log(test.x) shows the value of x.


In a comment, you've said:

I want to make java script variable for sending to other page. and the java script variable have to include member variables. How can I do?

If you mean, you want to create an object with properties, you'd do it like this:

var test = {x: '3', y: '4'};

No function required, example:

var test = {x: '3', y: '4'};
snippet.log(test.x); // 3
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 2

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36441

Javascript functions are objects, so you can add properties to them. In both cases, there are local variables to the code of the function which are not available outside. In the second case you add properties to the function object and access them as usual.

Upvotes: 3

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

You haven't set object property in the first case because of which you are not getting any value. Try return.

console.log(test.x);

On the other case you are setting the object property and then calling its value so it is working.

test.x = '3'; 
test.y = '4';

console.log(test.x);

Hope this helps you

Upvotes: 0

Related Questions