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'; };

the result is undefined

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

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


It is working.

I can't understand why.

T.J. Crowder

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>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment


Related Related