Home Making a local scope inside a for loop, into a global scope
Reply: 3

Making a local scope inside a for loop, into a global scope

Andyg123
1#
Andyg123 Published in 2017-12-05 18:37:24Z

I have been searching but I cant get a clear answer. (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. For Example : I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. Is this allowed or is there a different approach?

 var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'
bamberjp
2#
bamberjp Reply to 2017-12-05 18:57:57Z

I think if I understand what you are trying to achieve, this should help ...

var movieDb = [
    {
    haswatched : "i",
    title : "In Burges",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : 0,
  },
];

for (var i = 0; i < movieDb.length ; i++) {
   var w = prompt("did you watch the movie " + movieDb[i].title + "?")
   if (w === 'yes'){//first IF
      movieDb[i].haswatched = "you have watched";
      var r = prompt("would you like to rate us?");
      if (r === "yes") {//nested in first IF
          var stars = prompt("Enters Stars");
          movieDb[i].rating = stars;
          alert("Thanks for rating & Watching!")
      } else if(r === "no"){ //nested in second IF
          alert("You did not rate, Thanks for watching!")
      }
   } else if (w === "no"){ //first ELSE IF
      movieDb[i].haswatched = "you have not seen";
   }
}

console.log(movieDb);

https://jsfiddle.net/ramsmxms/

Vatsal
3#
Vatsal Reply to 2017-12-05 18:47:16Z

var in javascript have function scope. So even if you define it inside for loop they will be available outside the loop. If you do console.log before the loop, the value will be undefined and if you do it after the loop, the value will be last value available inside the loop. To make things block scoped ( local scope inside the loop ), use let & const. They are available in ES6 and with all the major browsers support them.

Hope this will help

Happy Learning

Vatsal

Zyigh
4#
Zyigh Reply to 2017-12-05 19:04:51Z

I'm not sure I understood quite well your question so don't hesitate to correct me if I say something stupid or answer to a question you didn't ask.

The best way to define a variable inside a for loop scope is to declare it with let.

var i = "aaa";

for (let i = 0; i < 10; i++) {
    console.log(i); // => 0...9
}

console.log(i); // => "aaa"

I think the problem you are facing is that stars doesn't exist.
You can either set it to false or null (or whatever value), and then set it to the number you get with the prompt, or just set it when you have the value :

{
haswatched : "i",
title : "In Burges"
}

...

movieDb[i].stars = stars;

I don't know if it is quicker to set it to an Int value at first, but that would be such a tiny improvement in this case that I'm not sure it would matter much.

Hope it helps

Edit :

About let scope inside a loop, here's an example :

<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
</ul>

<script>
var lis = document.querySelectorAll('li');
for (let i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>

When clicking on li, show position (from 0 to 4) although :

<script>
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>

Would display 5 (i is incremented before leaving the loop)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.347514 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO