Using a global variable in JavaScript - javascript

How do I do this?
My code is something like this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
var number = '10';
alert('' + [number] + '');
}
The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call?

By using var when setting number = '10', you are declaring number as a local variable each time. Try this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
number = '10';
alert('' + [number] + '');
}

Remove the var in front of number in your function. You are creating a local variable by
var number = 10;
You just need
number = 10;

The problem is that you're declaring a new variable named number inside of the function. This new variable hides the global number variable, so the line number = 10 assigns only to this new local variable.
You need to remove the var keyword from var number = 10.

Like in C, you need to define your variable outside of the function/method to make it global.
var number = 0;
function playSong(artist,title,song,id)
{
alert('old number was: '+[number]+'');
number = '10';
alert(''+[number]+'');
}

Let me explain in detail. To declare global variables and local variables in JavaScript
var firstNumber = 5; // Local variable
secondNumber = 10; // Global variable or window object
When your program is like this
var number = 1;
function playSong() {
alert(number);
var number = 2;
alert(number);
}
As per the JavaScript compiler, all declarations/initializations of variables will move to the top. This concept is called hoisting.
As per the compiler, the program will execute like:
var number; // Declaration will move to top always in Javascript
number = 1;
function playSong() {
var number;
alert(number); // Output: undefined - This is a local variable inside the function
number = 2;
alert(number); // Output: 2
}
If you need to access the global variable inside the function, use window.number.
var number = 1;
function playSong() {
var number = 2;
alert(window.number); // Output: 1 - From a global variable
alert(number); // Output: 2 - From local variable
}

You can also access it in any function like window.number, after removing var inside the function.

I’ve come across this answer in 2020 and after searching some more online I have found that apparently in the JavaScript definitions if you place variables outside of functions or even create a file called globals.js and just put all your globally required variables in that file, make that file the first user .js file in your script tags after jQuery and any other plugins you need, globals will load before your other scripts and allow you to call variables from globals.js within any script on the page.
W3C JavaScript Scope
I have tested this theory within a PHP application that I am building and I have been able to call variables from the globals.js file within a page that is loaded via Ajax to a jconfirm dialog for a troubleshooting wizard to set up the return values for when the dialog is closed.

Related

Create global variable and generate random number and update the variable when the function is called in Javascript

I am kinda new in this coding environment and trying to challange myself with exercises.
I am trying to create global variable called quoteNumber and generate a random number and update this variable every time when the function is called.
However with the code below, every time I call the function quoteNumber variable stays the same and not updated with new random number.
I can solve this putting all variables inside the function but since I am using those variables in different functions I guess it is better for me to create global variable for it.
What are your suggestions?
var quotes = [{"quote":"Knowledge speaks, but wisdom listens.","author":"Jimi Hendrix"}];
var quoteNumber = 0 ;
var generatedQuote = quotes[quoteNumber].quote;
var generatedAuthor = quotes[quoteNumber].author;
function quoteGenerator () {
quoteNumber = Math.floor(Math.random() * 80) + 1;
document.getElementById("text").innerHTML = generatedQuote;
document.getElementById("author").innerHTML = generatedAuthor;
}
function share() {
document.getElementById("tweet-quote").attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&text=' + encodeURIComponent('"' + generatedQuote + '" ' + generatedAuthor));
}
PS- I have shortened the quotes variation and put here not to create confusion
When calling the function you are properly updating the quoteNumber-variable. However, both generatedQuote and generatedAuthor are still the value you set from the beginning.
So, after setting the quoteNumber to a new value, you will have to do
generatedQuote = quotes[quoteNumber].quote;
generatedAuthor = quotes[quoteNumber].author;
To update those variables as well.

How to change a variable used as argument for function

I've looked around a little bit, and I haven't found a clear answer as to why when this proceeding code is ran, it returns myInt as 0. I've read posts about how the variable is only changed inside the function, but from my perspective, I don't see any reason why myInt cannot be changed. For refrence, this is in Javascript.
var myInt = 0;
function changeVar(x) {
x += 1;
}
changeVar(myInt);
console.log(myInt);
The reason myInt is not changing is that x has local scope (anything you do to x only affects the value of x inside of changeVar).
Here's how you could change myInt from changeVar():
var myInt = 0;
function changeVar() {
myInt += 1;
}
changeVar();
console.log(myInt);
If you want to change a variable by passing it as an argument, you should pass an object instead:
var myObject1 = {value: 0}
var myObject2 = {value: 10}
function changeVar(x) {
x['value'] += 1;
}
console.log(myObject1['value']);
console.log(myObject2['value']);
changeVar(myObject1);
console.log(myObject1['value']);
console.log(myObject2['value']);
I will expand on the example given by #N.Kern - here is a better example of how to change the initial variable passed in the function:
var myInt = 0;
function changeVar(x) {
return x += 1;
}
var y = changeVar(myInt);
console.log(y);
Now, the reason for this is offered by #Shekhar Chikara in the comment. Essentially, the value you're passing to the function is modified within the local scope of the function, but it's not actually assigned back (or saved in memory) to the globally declared variable. So when you log the original global variable, you get the unchanged value back. Thus, you want to simply save your functions' returned value to it's own variable.
This will get you started on researching more.
Hope this helps.

Convert string value as variable name in js, like in php [duplicate]

I’ve looked for solutions, but couldn’t find any that work.
I have a variable called onlyVideo.
"onlyVideo" the string gets passed into a function. I want to set the variable onlyVideo inside the function as something. How can I do that?
(There are a number of variables that could be called into the function, so I need it to work dynamically, not hard coded if statements.)
Edit: There’s probably a better way of doing what you’re attempting to do. I asked this early on in my JavaScript adventure. Check out how JavaScript objects work.
A simple intro:
// create JavaScript object
var obj = { "key1": 1 };
// assign - set "key2" to 2
obj.key2 = 2;
// read values
obj.key1 === 1;
obj.key2 === 2;
// read values with a string, same result as above
// but works with special characters and spaces
// and of course variables
obj["key1"] === 1;
obj["key2"] === 2;
// read with a variable
var key1Str = "key1";
obj[key1Str] === 1;
If it's a global variable then window[variableName]
or in your case window["onlyVideo"] should do the trick.
Javascript has an eval() function for such occasions:
function (varString) {
var myVar = eval(varString);
// .....
}
Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need
function SetTo5(varString) {
var newValue = 5;
eval(varString + " = " + newValue);
}
or if using a string:
function SetToString(varString) {
var newValue = "string";
eval(varString + " = " + "'" + newValue + "'");
}
But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()
As far as eval vs. global variable solutions...
I think there are advantages to each but this is really a false dichotomy.
If you are paranoid of the global namespace just create a temporary namespace & use the same technique.
var tempNamespace = {};
var myString = "myVarProperty";
tempNamespace[myString] = 5;
Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)
var myString = "echoHello";
window[myString] = function() {
alert("Hello!");
}
echoHello();
Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/
You can do like this
var name = "foo";
var value = "Hello foos";
eval("var "+name+" = '"+value+"';");
alert(foo);
You can access the window object as an associative array and set it that way
window["onlyVideo"] = "TEST";
document.write(onlyVideo);
The window['variableName'] method ONLY works if the variable is defined in the global scope. The correct answer is "Refactor". If you can provide an "Object" context then a possible general solution exists, but there are some variables which no global function could resolve based on the scope of the variable.
(function(){
var findMe = 'no way';
})();
If you're trying to access the property of an object, you have to start with the scope of window and go through each property of the object until you get to the one you want. Assuming that a.b.c has been defined somewhere else in the script, you can use the following:
var values = window;
var str = 'a.b.c'.values.split('.');
for(var i=0; i < str.length; i++)
values = values[str[i]];
This will work for getting the property of any object, no matter how deep it is.
It can be done like this
(function(X, Y) {
// X is the local name of the 'class'
// Doo is default value if param X is empty
var X = (typeof X == 'string') ? X: 'Doo';
var Y = (typeof Y == 'string') ? Y: 'doo';
// this refers to the local X defined above
this[X] = function(doo) {
// object variable
this.doo = doo || 'doo it';
}
// prototypal inheritance for methods
// defined by another
this[X].prototype[Y] = function() {
return this.doo || 'doo';
};
// make X global
window[X] = this[X];
}('Dooa', 'dooa')); // give the names here
// test
doo = new Dooa('abc');
doo2 = new Dooa('def');
console.log(doo.dooa());
console.log(doo2.dooa());
The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.
// For each element with an id (example: 'MyDIV') in the body, create a variable
// for easy reference. An example is below.
var D=document;
var id={}; // All ID elements
var els=document.body.getElementsByTagName('*');
for (var i = 0; i < els.length; i++)
{
thisid = els[i].id;
if (!thisid)
continue;
val=D.getElementById(thisid);
id[thisid]=val;
}
// Usage:
id.MyDIV.innerHTML="hello";
let me make it more clear
function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file

Javascript on click event not reading else statement or variables

I'm trying to make a click handler that calls a function; and that function gets a string and basically slices the last character and adds it to the front, and each time you click again it should add the last letter to the front.
It seem so easy at first that I thought I could just do it using array methods.
function scrollString() {
var defaultString = "Learning to Code Javascript Rocks!";
var clickCount = 0;
if (clickCount === 0) {
var stringArray = defaultString.split("");
var lastChar = stringArray.pop();
stringArray.unshift(lastChar);
var newString = stringArray.join('');
clickCount++;
} else {
var newArray = newString.split("");
var newLastChar = newArray.pop();
newArray.unshift(newLastChar);
var newerString = newArray.join("");
clickCount++;
}
document.getElementById('Result').innerHTML = (clickCount === 1) ? newString : newerString;
}
$('#button').on('click', scrollString);
Right now it only works the first time I click, and developer tools says newArray is undefined; also the clickCount stops incrementing. I do not know if it's an issue of scope, or should I take a whole different approach to the problem?
Every time you click you are actually reseting the string. Check the scope!
var str = "Learning to Code Javascript Rocks!";
var button = document.getElementById("button");
var output = document.getElementById("output");
output.innerHTML = str;
button.addEventListener("click", function(e){
str = str.charAt(str.length - 1) + str.substring(0, str.length - 1);
output.innerHTML = str;
});
button{
display: block;
margin: 25px 0;
}
<button id="button">Click Me!</button>
<label id="output"></label>
It is, in fact, a scoping issue. Your counter in inside the function, so each time the function is called, it gets set to 0. If you want a counter that is outside of the scope, and actually keeps a proper count, you will need to abstract it from the function.
If you want to keep it simple, even just moving clickCount above the function should work.
I do not know if it's an issue of scope
Yes, it is an issue of scope, more than one actually.
How?
As pointed out by #thesublimeobject, the counter is inside the function and hence gets reinitialized every time a click event occurs.
Even if you put the counter outside the function, you will still face another scope issue. In the else part of the function, you are manipulation a variable (newString) you initialized inside the if snippet. Since, the if snippet didn't run this time, it will throw the error undefined. (again a scope issue)
A fine approach would be:
take the counter and the defaultString outside the function. If the defaultString gets a value dynamically rather than what you showed in your code, extract its value on page load or any other event like change, etc. rather than passing it inside the function.
Do not assign a new string the result of your manipulation. Instead, assign it to defaultString. This way you probably won't need an if-else loop and a newLastChar to take care of newer results.
Manipulate the assignment to the element accordingly.
You can use Javascript closure functionality.
var scrollString = (function() {
var defaultString = "Learning to Code Javascript Rocks!";
return function() {
// convert the string into array, so that you can use the splice method
defaultString = defaultString.split('');
// get last element
var lastElm = defaultString.splice(defaultString.length - 1, defaultString.length)[0];
// insert last element at start
defaultString.splice(0, 0, lastElm);
// again join the string to make it string
defaultString = defaultString.join('');
document.getElementById('Result').innerHTML = defaultString;
return defaultString;
}
})();
Using this you don't need to declare any variable globally, or any counter element.
To understand Javascript Closures, please refer this:
http://www.w3schools.com/js/js_function_closures.asp

Is it possible to assign a variable with a function? [duplicate]

I’ve looked for solutions, but couldn’t find any that work.
I have a variable called onlyVideo.
"onlyVideo" the string gets passed into a function. I want to set the variable onlyVideo inside the function as something. How can I do that?
(There are a number of variables that could be called into the function, so I need it to work dynamically, not hard coded if statements.)
Edit: There’s probably a better way of doing what you’re attempting to do. I asked this early on in my JavaScript adventure. Check out how JavaScript objects work.
A simple intro:
// create JavaScript object
var obj = { "key1": 1 };
// assign - set "key2" to 2
obj.key2 = 2;
// read values
obj.key1 === 1;
obj.key2 === 2;
// read values with a string, same result as above
// but works with special characters and spaces
// and of course variables
obj["key1"] === 1;
obj["key2"] === 2;
// read with a variable
var key1Str = "key1";
obj[key1Str] === 1;
If it's a global variable then window[variableName]
or in your case window["onlyVideo"] should do the trick.
Javascript has an eval() function for such occasions:
function (varString) {
var myVar = eval(varString);
// .....
}
Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need
function SetTo5(varString) {
var newValue = 5;
eval(varString + " = " + newValue);
}
or if using a string:
function SetToString(varString) {
var newValue = "string";
eval(varString + " = " + "'" + newValue + "'");
}
But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()
As far as eval vs. global variable solutions...
I think there are advantages to each but this is really a false dichotomy.
If you are paranoid of the global namespace just create a temporary namespace & use the same technique.
var tempNamespace = {};
var myString = "myVarProperty";
tempNamespace[myString] = 5;
Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)
var myString = "echoHello";
window[myString] = function() {
alert("Hello!");
}
echoHello();
Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/
You can do like this
var name = "foo";
var value = "Hello foos";
eval("var "+name+" = '"+value+"';");
alert(foo);
You can access the window object as an associative array and set it that way
window["onlyVideo"] = "TEST";
document.write(onlyVideo);
The window['variableName'] method ONLY works if the variable is defined in the global scope. The correct answer is "Refactor". If you can provide an "Object" context then a possible general solution exists, but there are some variables which no global function could resolve based on the scope of the variable.
(function(){
var findMe = 'no way';
})();
If you're trying to access the property of an object, you have to start with the scope of window and go through each property of the object until you get to the one you want. Assuming that a.b.c has been defined somewhere else in the script, you can use the following:
var values = window;
var str = 'a.b.c'.values.split('.');
for(var i=0; i < str.length; i++)
values = values[str[i]];
This will work for getting the property of any object, no matter how deep it is.
It can be done like this
(function(X, Y) {
// X is the local name of the 'class'
// Doo is default value if param X is empty
var X = (typeof X == 'string') ? X: 'Doo';
var Y = (typeof Y == 'string') ? Y: 'doo';
// this refers to the local X defined above
this[X] = function(doo) {
// object variable
this.doo = doo || 'doo it';
}
// prototypal inheritance for methods
// defined by another
this[X].prototype[Y] = function() {
return this.doo || 'doo';
};
// make X global
window[X] = this[X];
}('Dooa', 'dooa')); // give the names here
// test
doo = new Dooa('abc');
doo2 = new Dooa('def');
console.log(doo.dooa());
console.log(doo2.dooa());
The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.
// For each element with an id (example: 'MyDIV') in the body, create a variable
// for easy reference. An example is below.
var D=document;
var id={}; // All ID elements
var els=document.body.getElementsByTagName('*');
for (var i = 0; i < els.length; i++)
{
thisid = els[i].id;
if (!thisid)
continue;
val=D.getElementById(thisid);
id[thisid]=val;
}
// Usage:
id.MyDIV.innerHTML="hello";
let me make it more clear
function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file

Categories

Resources