Aloalo Aloalo - 1 month ago 10
Javascript Question

Trying to set a global variable with javascript function

So I am making a small flash card app in rails and I am using javascript for the card logic. I am new to JS and I am having some trouble

resetting
the
variables
I am using for the cards
front
and
back
based on the outcome of my
randomizing function


<script>
var card_list = "<%=j @deck.cards.to_json.html_safe %>";
console.log(card_list)

/* Parse the Json and get all the cards */
var cards = JSON.parse(card_list);

/* Return json object count */
var length = Object.keys(cards).length;
console.log(length)

/* Grab a random card from the card list */
var rand = cards[Math.floor(Math.random() * cards.length)];
console.log(rand)

/* Set the front label from random value */
var front = rand.front;
console.log(front)

/* Set the back label from random value */
var back = rand.back;
console.log(back)

/* Grab the div and set the label */
var elem = document.getElementById("card-face");
elem.innerHTML = rand.back;

/* Grab another random card from the card list */
function randomCard() {
var rand = cards[Math.floor(Math.random() * cards.length)];
console.log(rand)
if (typeof front !== 'undefined') {
alert("Undefined");
}
else{
var front = rand.front;
var back = rand.back;
console.log("Should now be updated?")
};
var elem = document.getElementById("card-face");
elem.innerHTML = rand.back;
}

/* Flip the card front to back */
function flipper() {
var elem = document.getElementById("card-face");
if (elem.innerHTML== rand.front) elem.innerHTML = rand.back;
else elem.innerHTML = rand.front;
console.log(elem)
}
</script>


When I run the
randomCard
function
elem.innerHTML = rand.back;
is updated with the new 'rand.back' but when I flip the card 'rand.front' and
rand.back
returns the initial values I set when the session started. How can I updated these values specifically?

Answer

Inside your randomCard function, you are creating new front and back variables inside this function's local scope every time you are executing the function and declare the variables with var.

Since variables with the names front and back now live inside this function's local scope, the assignment happens on the local front and back variables, since they exist in the immediate context; it doesn't have to look to the context outside of the randomCard function where the front and back variables you want to update live.

In order to get the behaviour you want simply do not declare the front and back variables with the var keyword, inside your randomCard, so that any assignments to them happen to the outer front and back

Comments