How to access value of the global variable in other function javascript - javascript

Here is one of the similar example
var global=0;
function somefunction()
{
global++;
}
var temp=global;
function somefunctiontwo()
{
var x=temp;
}
here I am getting x=0
I want x=1
how can I assign newly assigned value of global variable to x

Use an object as global variable; that will be assigned by reference instead of 'by value' as for the simple (number) type:
var global = { value: 0 };
var temp = global;
in function:
global.value++;
now is:
temp.value == 1

temp and global refer to two different variables. Assigning to global will not change the value in temp.
Simply change var x=temp to var x=global. It's not clear why you need an intermediate variable.

var global=0;
var temp;
function somefunction(){
global++;
}
function somefunctiontwo() {
var x=temp;
console.log(x);
}
somefunction();
temp=global;
somefunctiontwo();
This will give what you expect. Pay attention on how/where you call the functions.

Your structure seems a little off, not sure if this is for a reason we can't see... Will presume it is. Can have a function that resyncs the temp value to global.
function syncGlob(){
return temp = global;
}
Returns temp as well so you can call it when creating x.
var x = syncGlob();

You're setting the value of temp to global PRIOR to the on ready firing - at this point global is 0. If you increment global at on ready, temp already has a value of 0.
When you click somefunction2 and assign x the value of temp, temp has a value of 0, because at the time of temp initiation, global had a value of 0 NOT 1

Related

Should a variable be declared before it is used as an argument in a function in Javascript?

Example:
var num;
function mySquare(num) {
var sq = num * num;
}
Is var num statement necessary or that statement can be neglected?
In you specific case, the statement var num; is useless. It won't even be used.
When you declare a function, the arguments represent local variables that are created specifically for the function block.
num is a local variable inside function mySquare so you can ignore var num;
function parameters will be declared and initialized before passing them into the function.
function a(helloWorld) {
console.log(helloWorld)
}
a("test") //test
var b = "hallo welt"
a(b) //hallo welt
a(c) //undefined
greetings
By specifying num as the name of an argument in the parameter list, you have already declared it as a local variable. Explicitly adding var num inside the function would be redundant and JSLint would warn you that you are redeclaring num if you tried.
Explicitly adding var num outside the function would create a global variable with the same name… that you never use. This is also redundant.

Defining variable within if statement in javascript

I want to assign a value to a variable when a condition is verified like this
if (k<12){
var Case=4;
}
The problem when i call this variable to be printed in the body of the page i get undefined
document.write(Case);
Basically your var statement gets hoisted and assigned with undefined.
Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.
Order of execution:
var Case; // hoisted, value: undefined
if (k < 12) {
Case = 4;
}
You are getting undefined because you have not actually defined it. You are defining it when the condition is true. You should write the code like this.
var Case = null;
var k = 0;
if(k > 14) {
Case = 3;
}
document.write(Case);
I hope it was helpful.
var Case = 0;
if(k<12){
Case = 4;
}
document.write(Case);
You need to define it first so if k<12 == False it wont be undefined.

Get all values of variable using JS

So in my js code I have some global variable that changes its value several times, for example
var x = 0;
...
x = 10;
...
x = 5;
Is there any possibility to get "history" of x without saving its value in other variables? Like, is there some function to detect that at some point of time x was equal to 10?
No, once a value is assigned to a variable, that variable's previous value is overwritten. It isn't retained anywhere. (If it were, it would be a nightmare for memory management.)
You could make an object property that retained a history if you wanted, by using a setter function; rough example:
var obj = {
_fooValue: undefined,
fooHistory: [],
set foo(value) {
this.fooHistory.push(this._fooValue);
this._fooValue = value;
},
get foo() {
return this._fooValue;
}
};
obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);
In that example, the history doesn't contain the current value, just the previous ones, and it stores the current value in another object property which means code could bypass the setter. There are lots of tweaks you could do. If you thought it was important, you could lock it down more:
var obj = (function() {
// These two vars are entirely private to the object
var fooHistory = [];
var fooValue;
// The object we'll assign to `obj`
return {
set foo(value) {
fooHistory.push(fooValue);
fooValue = value;
},
get foo() {
return fooValue;
},
get fooHistory() {
// Being really defensive and returning
// a copy
return fooHistory.slice(0);
}
}
})();
obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);
You can use variable like array and unshift next value to this array. And to use it take first element:
var x = [];
...
x.unshift(10);
...
x.unshift(5);
var currentX = x[0];
var allValues = x;
Yes there is. Using the Time Travelling debugging in Microsoft Edge browser. Check this out.
I'm not JS specialist, but as common idea for any OOP language, I would suggest to create special class for x (inherited from Integer in your example), which has overriden setter and some history array list. So, when you set a new value it stored in your history.
You need change only the variable type, not the code, which works with that. I also don't think there is some standard solution for this in any language. Probably, some dynamic introspectors, but those would be even more complex than my idea.

What is the use of just declaring variables

I have been using python for a while now, and have just started learning javascript. In javascript you can, as I understand it, declare a variable without assigning a value to it (var cheese compared to var cheese = 4) in what situation would you want to declare a variable but not assign a value to it straight away?
Consider this snippet.
if (someCondition) {
var x = 5;
} else if (someOtherCondition) {
var x = 4;
}
if (x) {
doFunc();
}
Since x needs to exist for the doFunc to run, you simply add an undefined declaration above. var x; so that the if (x) doesn't return an error.
You do this when you want the value of the variable to be undefined.
var cheese;
console.log(cheese); // undefined
It's simpler than
var cheese = undefined;
The undefined value doesn't seem much useful, but this will allow to assign some other value later.
var cheese; can be perfectly useful (even if you never assign anything to it). Of course it's a shorter way to type var cheese = undefined;, but that's not the only reason…
Using var declares a local variable, and this has a nice property: it hides variables from parent scopes.
There's another part to your question:
If we're going to assign a value to var cheese anyway: why not assign immediately?.
Answer: it may be fine for your algorithm to return cheese without ever assigning anything to it — i.e. "undefined is valid".
Here's an example which illustrates how var hides variables from parent scopes:
var a = 3;
console.log(a); // prints 3; "a" is defined in this scope
function findEvenNumber(numbers) {
var a; // we declare this local variable, to ensure that we do _not_ refer to the variable that exists in the parent scope
numbers.forEach(function(number) {
if (number % 2 === 0) {
a = number;
}
});
return a; // if no even number was found, it returns undefined (because we never assigned anything to a)
}
findEvenNumber([1, 2]); // returns 2;
console.log(a); // prints 3; the "a" in this scope did not get overwritten by the function
Speculation: maybe the var cheese; syntax exists in ECMA to enable programmers to declare all variables at the beginning of their function. Such a convention was enforced by the C89 compiler, and some people grew fond of it.

Determine original name of variable after its passed to a function

I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";
This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.
You're right, this is very much impossible in any sane way, since only the value gets passed into the function.
This is now somehow possible thanks to ES6:
function getVariableName(unknownVariableInAHash){
return Object.keys(unknownVariableInAHash)[0]
}
const foo = 42
const bar = 'baz'
console.log(getVariableName({foo})) //returns string "foo"
console.log(getVariableName({bar})) //returns string "bar"
The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.
As you want debugging (show name of var and value of var),
I've been looking for it too, and just want to share my finding.
It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.
It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :
foo = 'bar';
debug('foo');
function debug(Variable) {
var Value = this[Variable]; // in that occurrence, it is equivalent to
// this['foo'] which is the syntax to call the global variable foo
console.log(Variable + " is " + Value); // print "foo is bar"
}
Well, all the global variables are properties of global object (this or window), aren't they?
So when I wanted to find out the name of my variables, I made following function:
var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = "Hello World!";
console.log(getName(helloWorld)); // "helloWorld"
Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.
Global w/string method
Here is a technique that you can use to keep the name and the value of the variable.
// Set up a global variable called g
var g = {};
// All other variables should be defined as properties of this global object
g.foo = 'hello';
g.bar = 'world';
// Setup function
function doStuff(str) {
if (str in g) {
var name = str;
var value = g[str];
// Do stuff with the variable name and the variable value here
// For this example, simply print to console
console.log(name, value);
} else {
console.error('Oh snap! That variable does not exist!');
}
}
// Call the function
doStuff('foo'); // log: foo hello
doStuff('bar'); // log: bar world
doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!
This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.
ES6 object method
In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.
function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}
var foo = 'hello';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);
This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.
Credit goes to this tweet.
Converting a set of unique variable into one JSON object for which I wrote this function
function makeJSON(){ //Pass the variable names as string parameters [not by reference]
ret={};
for(i=0; i<arguments.length; i++){
eval("ret."+arguments[i]+"="+arguments[i]);
}
return ret;
}
Example:
a=b=c=3;
console.log(makeJSON('a','b','c'));
Perhaps this is the reason for this query
I think you can use
getVariableName({foo});
Use a 2D reference array with .filter()
Note: I now feel that #Offermo's answer above is the best one to use. Leaving up my answer for reference, though I mostly wouldn't recommend using it.
Here is what I came up with independently, which requires explicit declaration of variable names and only works with unique values. (But will work if those two conditions are met.)
// Initialize some variables
let var1 = "stick"
let var2 = "goo"
let var3 = "hello"
let var4 = "asdf"
// Create a 2D array of variable names
const varNames = [
[var1, "var1"],
[var2, "var2"],
[var3, "var3"]
]
// Return either name of variable or `undefined` if no match
const getName = v => varNames.filter(name => name[0] === v).length
? varNames.filter(name => name[0] === v)[0][1]
: undefined
// Use `getName` with OP's original function
function getVariableName(unknownVariable){
return getName(unknownVariable)
}
This is my take for logging the name of an input and its value at the same time:
function logVariableAndName(unknownVariable) {
const variableName = Object.keys(unknownVariable)[0];
const value = unknownVariable[variableName];
console.log(variableName);
console.log(value);
}
Then you can use it like logVariableAndName({ someVariable })

Categories