What is The Purpose of "For " & "Loop" in javascript?

by 4 replies
5
I could not understood the function and purpose of "for " & "Loop" in javascript. For what they are used .(and also increament , decreament etc)?
#programming #javascript #loop #purpose
  • Here is a basic explanation: https://www.w3schools.com/js/js_loop_for.asp

    It is used for walking, or iterating, through an array or object.

    Do you have a piece of code you are stuck on, or a process you can't get to work? Post it. Let's see if we can't get it to work.

    edit: code for fun

    I have an object called markers (lat/lon locations from an api).

    this is actually JS, but I used the php code viewer

    PHP Code:
    // Here I create the loop and iterate through it markers.length times
      
    for (var 0markers.lengthi++) {
       
    // confirm the individual marker has data
        
    if (markers[i]!=null) {
          
    // take that data and split it at the comma (lat,lon)
          
    var data markers[i].split(',');
         
    // assign the marker object the data and icon
          
    var marker L.marker([data[0],data[1]], {
              
    iconicon,
            });
          
    // add that marker to a layer
          
    allpins.addLayer(marker);
        }
      }

    // add that layer to a map
      
    map.addLayer(allpins); 
    hopefully that helps in the understanding
    • [ 1 ] Thanks
    • [1] reply
    • I got some knowledge but still could not understood completely . Can you give me a real example (like a reference of a website`s section where these functions/loops are used)
      • [1] reply
  • [DELETED]
  • to make it simple and not give other words you might not understand yet its just a way to go over some data or situations

    you have ten movie names in your database and you what to get them and have them lsited on your web page

    You'd use a "for" to go through and get them all printed out - for every item found it will print out the movie name


    or you wanted to count from 1 to 10 in your pgramming you'd use a loop

    0 incremented by 1
    1 incremented by 1
    2 incremented by 1
    3 incremented by 1
    4 and so on

    the loop will stop when your conditionis met - in this case when you ahve reached 10
    • [ 1 ] Thanks

Next Topics on Trending Feed