You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

135 lines
10 KiB

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Learning Website</title>
<link href="/styles/styles.css" rel="stylesheet" type="text/css">
<link href="/webdevelopment/styles/styles.css" rel="stylesheet" type="text/css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<article>
<h1 class="coursetitle">JavaScript Essential Training</h1>
<h2 class="lecturer">LinkedIn Learning : Morten Rand-Hendriksen</h2>
<h1 class="episodetitle">Loops</h1>
<h2 class="sectiontitle">Loops</h2>
<p>JavaScript uses a standard for loop, so the general syntax for this is</p>
<p class="inset">
1. for(initial_state, condition, increment) {
2. code block;
3. }
</p>
<p class="caption">Figure 105 - the general syntax of a for loop</p>
<p>To give a more concrete example, let's say we want a loop that will log the numbers 0 to 9 (inclusive) to the console. The for loop to do that would be</p>
<pre><code>
1. for(var i=0; i &lt; 10; i++) {
2. console.log(i);
3. }
</code></pre>
<p class="caption">Figure 106 - an example of a for loop</p>
<p>We can also use a while loop and the general syntax for this is</p>
<pre><code>
1. while(condition){
2. some code;
3. }
</code></pre>
<p class="caption">Figure 107 - the general syntax of a while loop</p>
<p>Note that there are a couple of things which I have omitted because, unlike the for loop, these are not a standard part of the loop. For example, the condition can be checking some variable created for the purpose of running a while loop, but it could also be some other condition such as whether the user has typed something.</p>
<p>Similarly, the general syntax has ignored the fact that some variable needs to change for the loop to terminate. Again, this can be some variable set up for the purpose or it might be some Boolean variable whose value changes in response to some event. It is important to remember that if the condition is based on something that never changes or changes in such a way that the condition will never evaluate to false, the loop will run indefinitely (an infinite loop).</p>
<p>Conversely, if the condition is such that it can never evaluate to true, the loop will never execute.</p>
<p>An example of a simple while loop is</p>
<pre><code>
1. var i=0;
2. while(i&lt;10) {
3. console.log(i);
4. i++;
5. }
</code></pre>
<p class="caption">Figure 108 - an example of a while loop</p>
<p>This does exactly the same thing as the for loop shown in figure 106. The variable, i, has been created and initialised outside of the loop and acts as a control variable. We have also added a line of code to increment i inside the loop so that it will eventually hold a value of 10 at which time, the condition evaluates to false and execution of the loop stops.</p>
<p>JavaScript also has a do while loop which is very similar to a while loop. The difference is that where the while loop evaluates some condition and executes a block of code if the condition evaluates to true, the do while loop executes the block of code before evaluate the condition and continues executing if the condition evaluates to true.</p>
<p>In other words, the while loop might never execute if the condition evaluates to false the first time, but a do while loop will always execute at least one, regardless of the result of the first evaluation of the condition.</p>
<p>The general syntax of a do while loop is</p>
<pre><code>
1. do {
2. some code;
3. } (condition);
</code></pre>
<p class="caption">Figure 109 - the general syntax of a do while loop</p>
<p>If we re-write our while loop from figure 108 as a do while loop, it would look like this.</p>
<pre><code>
1. var i=0;
2. do {
3. console.log(i);
4. i++;
5. } while(i&lt;10);
</code></pre>
<p class="caption">Figure 110 - an example of a do while loop</p>
<p>Essentially, we have just taken the condition and placed it at the end of the loop.</p>
<h1 class="sectiontitle">Looping Through Arrays</h1>
<p>Since an array is a collection of objects or data items, we will quite often want to iterate through it using a loop. As an example, a call to querySelectorAll will generally return an array.</p>
<p>To illustrate this, we will go back to the sample Moonwalk website and we want to implement some code that will add a target attribute for all external links with a value of "_blank". Note that for the purpose of this exercise, we can assume that external links all have an absolute path (including http or https) and all internal links have a relative path.</p>
<p>To start with, we want to create an array and use querySelectorAll to populate it.</p>
<pre><code>
var extLinks = document.querySelectorAll('a[href^="http"]');
</code></pre>
<p>I think that the querySelectorAll argument looks a little strange and seems to be peculiar to JavaScript so it may be worth delving a little deeper into it. Firstly, let’s the argument on it's own is</p>
<pre><code>
'a[href^="http"]';
</code></pre>
<p>Note that the argument has been put in single quotes so we are able to express the href value as a string in double quotes. Doing this the other way round works as well.</p>
<p>As a reminder, we would normally use querySelectorAll with a string argument containing one or more selectors. For example</p>
<pre><code>
const matches = document.querySelectorAll("div.note, div.alert");
</code></pre>
<p>creates a constant called matches and returns a list of all &lt;div&gt; elements in the document that have a class of either note or alert. This example is taken from the <a href=" https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll">MDN Web Docs</a>.</p>
<p>We are doing something similar in our example, but we are only specifying one match item. That is an &lt;a&gt; element with a specified value in square brackets. That value is an href attribute whose value starts (this is what the ^ symbol is specifying) with 'http'. This would include any link that starts with 'https'.</p>
<p>Having retrieved our array of links, it is a good idea to make sure we have correctly populated the array by logging extLinks to the console and the result of this is shown in figure 111.</p>
<img src="images/image50.png">
<p class="caption">Figure 111 - the list of links obtained with querySelectAll (shown in the console)</p>
<p>We can now create a loop and we will use a for loop since we want to iterate through the array a fixed number of times (equal to the number of links in the array). We will create a control variable called i and the number of times to iterate through the loop is going to be the length of the array.</p>
<p>Inside the array, we will reference each link in turn and give it the appropriate attribute. We will put this inside a conditional statement so that we can check whether the link already has a target attribute using the hasAttribute function and if it doesn't, we can add a target attribute with a value of "_blank" using the setAttribute function. This gives us the following loop.</p>
<pre><code>
1. for (var i=0; i <extLinks.length; i++) {
2. if ( !extLinks[i].hasAttribute("target") ) {
3. extLinks[i].setAttribute("target","_blank'");
4. }
5. }
</code></pre>
<p class="caption">Figure 112 - the for loop that adds a target attribute to each of the links in the array (assuming the link doesn't already have one)</p>
<p>In the browser, we can inspect the links (in this case, they are all social media links at the bottom of the page) and see that each of them does have the target attribute with a value of "_blank". We can confirm that this was added by our JavaScript file simply be looking at the links in the HTML file. Remember that JavaScript updates the elements in the DOM, it does not modify the original HTML file so in this case, we will see that the links in that HTML file do not have a target attribute.</p>
<h1 class="sectiontitle">Break and Continue Loops</h1>
<p>I don't think that it is necessary to look at these in any detail because they work exactly as they would in most programming languages.</p>
<p>The break statement will completely exit a loop whereas the continue statement will exit the current iteration of the loop and go on to the next one.</p>
<p>So, if you have a loop with, let's say 10 lines of code and the 5th line is a statement that executes a break or continue, depending on some condition, in both cases, the last 5 lines of code inside the loop will be skipped over.</p>
<p>In the case of the break statement, the code will continue executing from the first line of code after the loop. In the case of the continue statement, the loop will continue with the next iteration. It is worth bearing in mind that if the loop is on its final iteration, the continue statement will actually have more or less the same effect as the break statement. The difference is that the continue statement will check to see if the loop needs to continue executing, the break statement will not.</p>
</article>
<button class="previous" onclick="window.location.href='typingspeedtester.html';">
Previous Chapter - Project: Typing Speed Tester
</button>
<button class="next" onclick="window.location.href='responsiveimages.html';">
Next Chapter - Project: Automated Responsive Images Markup
</button>
<button class="coursebutton" onclick="window.location.href='javascriptessentialtraining.html'">
Course Contents
</button>
<button class="webdevbutton" onclick="window.location.href='/webdevelopment/webdevelopment.html'">
Web Development Page
</button>
<button class="homebutton" onclick="window.location.href='/index.html'">
Home
</button>
</body>
</html>