Passing local variables from a function out to become global variables - javascript

I've spent the last two hours trying to figure out how to do this but nothing is working. Here is a short sample of some of my code. I want to get arrtime and several other similar variables out of the function so I can use them globally. Any ideas? Nothing too complicated please, I'm no expert (obviously).
function showTest(str) {
........
var arrayvals = JSON.parse(xmlhttp.responseText);
var arrtime= (arrayvals[0]);
}
var testvar=arrtime;
document.getElementById("testing").innerHTML=testvar;

The clean way to do this is using js-object notation:
function showTest(str) {
//other code
return {arr: arrayvals, tm: arrtime};
}
var func_result = showTest("blah-blah");
var testvar =func_result.tm;
var testvar2=func_result.arr;
But it's generally a bad idea to have global vars. Why do you need it?
Update sample code with global object
globals = {};
function q(){
globals['a'] = 123;
globals[123] = 'qweqwe';
}
function w(){
alert(globals.a);
//alert(globals.123); //will not work
alert(globals[123]); //that's OK.
}
q();
w();

You can declare the variables outside of the function.
var arrtime, arrayvals;
function showTest(str) {
arrayvals = JSON.parse(xmlhttp.responseText);
arrtime= (arrayvals[0]);
}
var testvar=arrtime;
alert (testvar);

var testvar;
function showTest(str) {
........
var arrayvals = JSON.parse(xmlhttp.responseText);
var arrtime= (arrayvals[0]);
testvar = arrtime;
}
alert (testvar);
The global is to be declared outside of the score of the function but assigned inside the scope of the function.

You simply have to omit var which indicates a variable that is only accessible from the function scope.

Related

Javascript use variable outside a function issue

I am currently learning node.js and already meet several times the same problem that seems very simple but I can't still understand how to solve it.
Code:
var SRC_PORT = 6025;
var dgram = require('dgram');
var clientUDP = dgram.createSocket("udp4");
var test
clientUDP.bind(SRC_PORT, function () {
multicastNew()
});
function multicastNew() {
var test = 777
console.log(test);
}
Problem
Cant use variable test content outside the function multicastNew()
In the function multicastNew() I have a variable var test. In that function multicastNew() I gave to test = 777. When I want to console.log(test) in the same function multicastNew() everything works,it outputs 777. The problem is that when I want to console.log(test) outside function multicastNew() it outputs undefined.
Can you please explain me how to solve this issue and why it is.
Thank you!
You should change var test = 777; to test = 777; in mulitcastNew(). Your code should be as such:
var SRC_PORT = 6025;
var dgram = require('dgram');
var clientUDP = dgram.createSocket("udp4");
var test;
clientUDP.bind(SRC_PORT, function () {
multicastNew();
});
function multicastNew() {
test = 777;
console.log(test);
}
A note on scope. In Javascript, functions create scope. Any variable defined with var inside of a function is a local variable, invisible outside the function. It's only local to the wrapping function, and if there is no wrapping function, it becomes a global variable.
Consider the following:
//this is global scope
var a = "Chris";
var b = "Inspired";
function nameChange(){
var a = "inspired"; // local to the function nameChange()
b = "Chris"; //without var we are changing the global variable
console.log(a); //will output inspired
}
nameChange(); // inspired
console.log(a); // Chris
console.log(b); // Chris
It's all about function scope. When u declare var test = 777, then u are creating new variable in scope of your function multicastNew(). This variable covers your 'main' variable from the global scope... So your function works from now on your local variable, not on the one from the global scope. JavaScript always look for variables inside scope it is called. In your example, when u try to call test outside the multicastNew(), then current scope is GLOBAL, so it finds your var test from the begining of your code. It's always work from inside to outside (closures). You can read:
Scopes

jQuery: How to set the global variable from one function and access it to another function?

how can I declare,set and access global variable from one function to another?
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The code above was just my sample to make it easy to understand on what I am trying to do. This is just for educational purposes. I just want to get the result in that way. Or is there a way to set a Global variable within a function and use it to another function outside that function?
What do to?
Creating variables in the Global scope is very bad practice. You shouldn't do it because it can cause conflicts especially in future JavaScript versions.
You can run the functions from a scope or object, try:
var shared = {};
$(document).ready(function () {
test1.call(shared);//undefined
test2.call(shared);
test1.call(shared);//foo
});
function test1 () {
alert(this.testvar);
}
function test2 () {
var a = 'foo';
this.testvar = a;
}
How it works
In simple terms, this will store all the variables in the object (shared). You can declared a "shared variable" by using this. instead of var. By using .call() we can choose to run the function in the scope of the object. I'm not the best at explaining, learn more here
Fiddle
Global Variables are always accessible from everywhere. But this might help you understand it better:
var testvar;
$(document).ready(function(){
console.log(testvar); // outputs: undefined
test2();
console.log(testvar); // outputs Hello World
console.log(test1()); //outputs Hello World
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return test2();
}
function test2(){
var a = "Hellow World";
testvar = a;
}
console.log(testvar);
test2() is not called. It needs to be called in order to redeclare the variable
https://jsfiddle.net/uwzapwrk/
I use this method and it works for me
function somefunctionname(){
// Some action
anotherfunctionname(put_your_value);
}
function anotherfunctionname(put_parameter_as_you_want){
var some_var = put_parameter_as_you_want;
// Some action with your var
}
This method work after somefunctionname() was execute and you can execute the anotherfunctionname() with variable was store on somefunctionname()

Swapping variables within a method

I'm trying to learn some OOP, so bear with me. I need to use a variable I defined in one function, elsewhere. Here is my example code (I want INTERCEPT!! to be logged, but it returns undefined):
function Talk() {
var greeting;
var pleaseStop; // declare it
this.A = function () {
greeting = 'hello';
console.log(greeting);
var intercept = function () {
pleaseStop = 'INTERCEPT!';
}
}
this.B = function () {
greeting = 'goodbye';
console.log(pleaseStop); // this returns undefined!
console.log(greeting);
}
}
var activateTalk = new Talk();
activateTalk.A();
activateTalk.B();
This whole code logs the following:
hello
undefined
goodbye
I have also tried intercept.pleaseStop() but it still returns undefined. Would anyone know of a solution?
EDIT:
I've removed the var the second time, but it still returns undefined:
http://jsfiddle.net/d654H/2/
var pleaseStop = 'INTERCEPT!';
You're declaring a new, function-local variable here; drop the var to assign to the existing variable in scope.
Then, you need to actually call intercept; at the moment you only define it.
It's your choice as to when you call that function; in this live example I simply do so immediately after the definition, for the purposes of exposition.
Remove var in front of the assignment to pleaseStop.
This assigns a new value to the pleaseStop declared inside the constructor, which is visible also from inside B:
var intercept = function () {
pleaseStop = 'INTERCEPT!';
}
This declares a new local variable pleaseStop, completely unrelated to the other pleaseStop, that is not visible outside intercept:
var intercept = function () {
var pleaseStop = 'INTERCEPT!';
}
If you do the latter instead of the former, you end up changing the value of another variable than the one you intended.
Your problem is you never set pleaseStop. You have declared intercept as a function, but you never called it. Therefore, pleaseStop is undefined.
Firstly you have't called intercept() anywhere and also u did something
var pleaseStop = 'INTERCEPT!';
which will create new variable instead of initializing global variable
You can do something like this
function Talk() {
var greeting;
var pleaseStop; // declare it
this.A = function () {
greeting = 'hello';
console.log(greeting);
var intercept = function () {
pleaseStop = 'INTERCEPT!';//changed
}
intercept(); //..Added
}
this.B = function () {
greeting = 'goodbye';
console.log(pleaseStop); // this returns undefined!
console.log(greeting);
}
}
var activateTalk = new Talk();
activateTalk.A();
activateTalk.B();
Without var keyword.
var pleaseStop = "A";
function foo(){
pleaseStop = "B"; // overwriting to "B"
}
foo();
alert(pleaseStop); // shows "B"
With var keyword.
var pleaseStop = "A";
function foo(){
var pleaseStop = "B"
// This defines a new variable 'pleaseStop'
// in the scope of function foo(){}.
}
foo();
alert(pleaseStop); // shows "A"
Variable Scope
JavaScript has function-level scope. In most languages which have block-level variable scope, variable are accessible whithin their block surrounded by curly brackets ({and}). But JavaSciprt doesn't terminate scopes at the end of blocks, but terminate them at the end of functions.
I'm sure there are many articles and documents about it. I googled it and found an intresting introductory article.
http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
Hope this helps.

How to access array/object inside function in javascript ?

Hello I have array outside function like below :
var daily = [];
daily["data"]=[];
daily["data"].push('hello');
function demo()
{
console.log(daily); // not working here
}
How to declare this object as global in Javascript ?
It could be because your function is being hoisted. Try this instead for your function.
var demo = function(){
console.log(daily);
}
You might also considering just passing that daily variable into your function like so,
var demo = function(d){
console.log(d);
}
then when you want to call it.
demo(daily);

Define private variable outside of the function which going to be used by new creation pattern

This question is simplified version of my old question Adding scope variable to a constructor. Question is simple can I add priv variable to the fu()'s scope without changing the function? (not adding inside of the function block)
Here is fiddle
Here is the code:
fff = function() {
alert('constructed');
//alert(priv);
};
pro = {
pub: 'public'
}
var make = function(fu, pro) {
var priv = 'private';
fu.prototype = pro
return function() {
return new fu();
};
};
var cls = make(fff, pro);
var obj = cls();
alert(obj.pub);​
As you can see if you de-comment the
//alert(priv);
line Uncaught ReferenceError: priv is not defined error.
I need a way to redifine the scope of the fu() function object.
I don't see the fu object listed, but I think the answer is "yes", you can add a private variable without changing the "function". Now, I may be missing something, but if I follow you, here is what you want:
var fu = {
DoStuff: function(someVar){
alert(someVar);
}
};
Then later in your code:
fu["NewPrivateVar"] = "something!";
Or in dot notation:
fu.NewPrivateVar = "someting!";
Finally:
fu.DoStuff(fu.NewPrivateVar);
Results in:
"something!"
Is that what you are looking to do?
You can't change the scope of the function by calling it from inside an object or a closure.
You can however add the variable to the scope of the function, i.e. in the global scope:
window.priv = 'private';
That will make the function work without changes, but the variable isn't very private...

Categories

Resources