One place for hosting & domains

      Statements

      Understanding Modules and Import and Export Statements in JavaScript


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      In the early days of the Web, websites consisted primarily of HTML and CSS. If any JavaScript loaded into a page at all, it was usually in the form of small snippets that provided effects and interactivity. As a result, JavaScript programs were often written entirely in one file and loaded into a script tag. A developer could break the JavaScript up into multiple files, but all variables and functions would still be added to the global scope.

      But as websites have evolved with the advent of frameworks like Angular, React, and Vue, and with companies creating advanced web applications instead of desktop applications, JavaScript now plays a major role in the browser. As a result, there is a much greater need to use third-party code for common tasks, to break up code into modular files, and to avoid polluting the global namespace.

      The ECMAScript 2015 specification introduced modules to the JavaScript language, which allowed for the use of import and export statements. In this tutorial, you will learn what a JavaScript module is and how to use import and export to organize your code.

      Modular Programming

      Before the concept of modules appeared in JavaScript, when a developer wanted to organize their code into segments, they would create multiple files and link to them as separate scripts. To demonstrate this, create an example index.html file and two JavaScript files, functions.js and script.js.

      The index.html file will display the sum, difference, product, and quotient of two numbers, and link to the two JavaScript files in script tags. Open index.html in a text editor and add the following code:

      index.html

      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      
          <title>JavaScript Modules</title>
        </head>
      
        <body>
          <h1>Answers</h1>
          <h2><strong id="x"></strong> and <strong id="y"></strong></h2>
      
          <h3>Addition</h3>
          <p id="addition"></p>
      
          <h3>Subtraction</h3>
          <p id="subtraction"></p>
      
          <h3>Multiplication</h3>
          <p id="multiplication"></p>
      
          <h3>Division</h3>
          <p id="division"></p>
      
          <script src="https://www.digitalocean.com/community/tutorials/functions.js"></script>
          <script src="https://www.digitalocean.com/community/tutorials/script.js"></script>
        </body>
      </html>
      

      This HTML will display the value of variables x and y in an h2 header, and the value of operations on those variables in the following p elements. The id attributes of the elements are set for DOM manipulation, which will happen in the script.js file; this file will also set the values of x and y. For more information on HTML, check out our How To Build a Website with HTML series.

      The functions.js file will contain the mathematical functions that will be used in the second script. Open the functions.js file and add the following:

      functions.js

      function sum(x, y) {
        return x + y
      }
      
      function difference(x, y) {
        return x - y
      }
      
      function product(x, y) {
        return x * y
      }
      
      function quotient(x, y) {
        return x / y
      }
      

      Finally, the script.js file will determine the values of x and y, apply the functions to them, and display the result:

      script.js

      
      const x = 10
      const y = 5
      
      document.getElementById('x').textContent = x
      document.getElementById('y').textContent = y
      
      document.getElementById('addition').textContent = sum(x, y)
      document.getElementById('subtraction').textContent = difference(x, y)
      document.getElementById('multiplication').textContent = product(x, y)
      document.getElementById('division').textContent = quotient(x, y)
      

      After setting up these files and saving them, you can open index.html in a browser to display your website with all the results:

      Rendered HTML with the values 10 and 5 and the results of the functions.js operations.

      For websites with a few small scripts, this is an effective way to divide the code. However, there are some issues associated with this approach, including:

      • Polluting the global namespace: All the variables you created in your scripts—sum, difference, etc.—now exist on the window object. If you attempted to use another variable called sum in another file, it would become difficult to know which value would be used at any point in the scripts, since they would all be using the same window.sum variable. The only way a variable could be private was by putting it within a function scope. There could even be a conflict between an id in the DOM named x and var x.
      • Dependency management: Scripts would have to be loaded in order from top to bottom to ensure the correct variables were available. Saving the scripts as different files gives the illusion of separation, but it is essentially the same as having a single inline <script> in the browser page.

      Before ES6 added native modules to the JavaScript language, the community attempted to come up with several solutions. The first solutions were written in vanilla JavaScript, such as writing all code in objects or immediately invoked function expressions (IIFEs) and placing them on a single object in the global namespace. This was an improvement on the multiple script approach, but still had the same problems of putting at least one object in the global namespace, and did not make the problem of consistently sharing code between third parties any easier.

      After that, a few module solutions emerged: CommonJS, a synchronous approach that was implemented in Node.js, Asynchronous Module Definition (AMD), which was an asynchronous approach, and Universal Module Definition (UMD), which was intended to be a universal approach that supported both previous styles.

      The advent of these solutions made it easier for developers to share and reuse code in the form of packages, modules that can be distributed and shared, such as the ones found on npm. However, since there were many solutions and none were native to JavaScript, tools like Babel, Webpack, or Browserify had to be implemented to use modules in browsers.

      Due to the many problems with the multiple file approach and the complexity of the solutions proposed, developers were interested in bringing the modular programming approach to the JavaScript language. Because of this, ECMAScript 2015 supports the use of JavaScript modules.

      A module is a bundle of code that acts as an interface to provide functionality for other modules to use, as well as being able to rely on the functionality of other modules. A module exports to provide code and imports to use other code. Modules are useful because they allow developers to reuse code, they provide a stable, consistent interface that many developers can use, and they do not pollute the global namespace.

      Modules (sometimes referred to as ECMAScript modules or ES Modules) are now available natively in JavaScript, and in the rest of this tutorial you will explore how to use and implement them in your code.

      Native JavaScript Modules

      Modules in JavaScript use the import and export keywords:

      • import: Used to read code exported from another module.
      • export: Used to provide code to other modules.

      To demonstrate how to use this, update your functions.js file to be a module and export the functions. You will add export in front of each function, which will make them available to any other module.

      Add the following highlighted code to your file:

      functions.js

      export function sum(x, y) {
        return x + y
      }
      
      export function difference(x, y) {
        return x - y
      }
      
      export function product(x, y) {
        return x * y
      }
      
      export function quotient(x, y) {
        return x / y
      }
      

      Now, in script.js, you will use import to retrieve the code from the functions.js module at the top of the file.

      Note: import must always be at the top of the file before any other code, and it is also necessary to include the relative path (./ in this case).

      Add the following highlighted code to script.js:

      script.js

      
      import { sum, difference, product, quotient } from './functions.js'
      
      const x = 10
      const y = 5
      
      document.getElementById('x').textContent = x
      document.getElementById('y').textContent = y
      
      document.getElementById('addition').textContent = sum(x, y)
      document.getElementById('subtraction').textContent = difference(x, y)
      document.getElementById('multiplication').textContent = product(x, y)
      document.getElementById('division').textContent = quotient(x, y)
      

      Notice that individual functions are imported by naming them in curly braces.

      In order to ensure this code gets loaded as a module and not a regular script, add type="module" to the script tags in index.html. Any code that uses import or export must use this attribute:

      index.html

      ...
      <script type="module" src="https://www.digitalocean.com/community/tutorials/functions.js"></script>
      <script type="module" src="https://www.digitalocean.com/community/tutorials/script.js"></script>
      

      At this point, you will be able to reload the page with the updates and the website will now use modules. Browser support is very high, but caniuse is available to check which browsers support it. Note that if you are viewing the file as a direct link to a local file, you will encounter this error:

      Output

      Access to script at 'file:///Users/your_file_path/script.js' from origin 'null' has been blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

      Because of the CORS policy, Modules must be used in a server environment, which you can set up locally with http-server or on the internet with a hosting provider.

      Modules are different from regular scripts in a few ways:

      • Modules do not add anything to the global (window) scope.
      • Modules always are in strict mode.
      • Loading the same module twice in the same file will have no effect, as modules are only executed once.
      • Modules require a server environment.

      Modules are still often used alongside bundlers like Webpack for increased browser support and additional features, but they are also available for use directly in browsers.

      Next, you will explore some more ways in which the import and export syntax can be used.

      Named Exports

      As demonstrated earlier, using the export syntax will allow you to individually import values that have been exported by their name. For example, take this simplified version of functions.js:

      functions.js

      export function sum() {}
      export function difference() {}
      

      This would let you import sum and difference by name using curly braces:

      script.js

      import { sum, difference } from './functions.js'
      

      It is also possible to use an alias to rename the function. You might do this to avoid naming conflicts within the same module. In this example, sum will be renamed to add and difference will be renamed to subtract.

      script.js

      import {
        sum as add,
        difference as subtract
      } from './functions.js'
      
      add(1, 2) // 3
      

      Calling add() here will yield the result of the sum() function.

      Using the * syntax, you can import the contents of the entire module into one object. In this case, sum and difference will become methods on the mathFunctions object.

      script.js

      import * as mathFunctions from './functions.js'
      
      mathFunctions.sum(1, 2) // 3
      mathFunctions.difference(10, 3) // 7
      

      Primitive values, function expressions and definitions, asynchronous functions, classes, and instantiated classes can all be exported, as long as they have an identifier:

      // Primitive values
      export const number = 100
      export const string = 'string'
      export const undef = undefined
      export const empty = null
      export const obj = { name: 'Homer' }
      export const array = ['Bart', 'Lisa', 'Maggie']
      
      // Function expression
      export const sum = (x, y) => x + y
      
      // Function definition
      export function difference(x, y) {
        return x - y
      }
      
      // Asynchronous function
      export async function getBooks() {}
      
      // Class
      export class Book {
        constructor(name, author) {
          this.name = name
          this.author = author
        }
      }
      
      // Instantiated class
      export const book = new Book('Lord of the Rings', 'J. R. R. Tolkien')
      

      All of these exports can be successfully imported. The other type of export that you will explore in the next section is known as a default export.

      Default Exports

      In the previous examples, you exported multiple named exports and imported them individually or as one object with each export as a method on the object. Modules can also contain a default export, using the default keyword. A default export will not be imported with curly brackets, but will be directly imported into a named identifier.

      For example, take the following contents for the functions.js file:

      functions.js

      export default function sum(x, y) {
        return x + y
      }
      

      In the script.js file, you could import the default function as sum with the following:

      script.js

      import sum from './functions.js'
      
      sum(1, 2) // 3
      

      This can be dangerous, as there are no restrictions on what you can name a default export during the import. In this example, the default function is imported as difference although it is actually the sum function:

      script.js

      import difference from './functions.js'
      
      difference(1, 2) // 3
      

      For this reason, it is often preferred to use named exports. Unlike named exports, default exports do not require an identifier—a primitive value by itself or anonymous function can be used as a default export. Following is an example of an object used as a default export:

      functions.js

      export default {
        name: 'Lord of the Rings',
        author: 'J. R. R. Tolkien',
      }
      

      You could import this as book with the following:

      script.js

      import book from './functions.js'
      

      Similarly, the following example demonstrates exporting an anonymous arrow function as the default export:

      functions.js

      export default () => 'This function is anonymous'
      

      This could be imported with the following script.js:

      script.js

      import anonymousFunction from './functions.js'
      

      Named exports and default exports can be used alongside each other, as in this module that exports two named values and a default value:

      functions.js

      export const length = 10
      export const width = 5
      
      export default function perimeter(x, y) {
        return 2 * (x + y)
      }
      

      You could import these variables and the default function with the following:

      script.js

      import calculatePerimeter, { length, width } from './functions.js'
      
      calculatePerimeter(length, width) // 30
      

      Now the default value and named values are both available to the script.

      Conclusion

      Modular programming design practices allow you to separate code into individual components that can help make your code reusable and consistent, while also protecting the global namespace. A module interface can be implemented in native JavaScript with the import and export keywords.

      In this article, you learned about the history of modules in JavaScript, how to separate JavaScript files into multiple top-level scripts, how to update those files using a modular approach, and the import and export syntax for named and default exports.

      To learn more about modules in JavaScript, read Modules on the Mozilla Developer Network. If you’d like to explore modules in Node.js, try our How To Create a Node.js Module tutorial.



      Source link

      How To Write Switch Statements in Go


      Introduction

      Conditional statements give programmers the ability to direct their programs to take some action if a condition is true and another action if the condition is false. Frequently, we want to compare some variable against multiple possible values, taking different actions in each circumstance. It’s possible to make this work using if statements alone. Writing software, however, is not only about making things work but also communicating your intention to your future self and other developers. switch is an alternative conditional statement useful for communicating actions taken by your Go programs when presented with different options.

      Everything we can write with the switch statement can also be written with if statements. In this tutorial, we’ll look at a few examples of what the switch statement can do, the if statements it replaces, and where it’s most appropriately applied.

      Structure of Switch Statements

      Switch is commonly used to describe the actions taken by a program when a variable is assigned specific values. The following example demonstrates how we would accomplish this using if statements:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              if flav == "strawberry" {
                  fmt.Println(flav, "is my favorite!")
                  continue
              }
      
              if flav == "vanilla" {
                  fmt.Println(flav, "is great!")
                  continue
              }
      
              if flav == "chocolate" {
                  fmt.Println(flav, "is great!")
                  continue
              }
      
              fmt.Println("I've never tried", flav, "before")
          }
      }
      

      This will generate the following output:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! I've never tried banana before

      Within main, we define a slice of ice-cream flavors. We then use a for loop to iterate through them. We use three if statements to print out different messages indicating preferences for different ice-cream flavors. Each if statement must use the continue statement to stop execution of the for loop so that the default message at the end is not printed for the preferred ice-cream flavors.

      As we add new ice-cream preferences, we have to keep adding if statements to handle the new cases. Duplicated messages, as in the case of "vanilla" and "chocolate", must have duplicated if statements. To future readers of our code (ourselves included), the repetitive nature of the if statements obscures the important part of what they are doing—comparing the variable against multiple values and taking different actions. Also, our fallback message is set apart from the conditionals, making it appear unrelated. The switch statement can help us organize this logic better.

      The switch statement begins with the switch keyword and is followed, in its most basic form, with some variable to perform comparisons against. This is followed by a pair of curly braces ({}) where multiple case clauses can appear. Case clauses describe the actions your Go program should take when the variable provided to the switch statement equals the value referenced by the case clause. The following example converts the previous example to use a switch instead of multiple if statements:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              switch flav {
              case "strawberry":
                  fmt.Println(flav, "is my favorite!")
              case "vanilla", "chocolate":
                  fmt.Println(flav, "is great!")
              default:
                  fmt.Println("I've never tried", flav, "before")
              }
          }
      }
      

      The output is the same as before:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! I've never tried banana before

      We’ve once again defined a slice of ice-cream flavors in main and used the range statement to iterate over each flavor. This time, however, we’ve used a switch statement that will examine the flav variable. We use two case clauses to indicate preferences. We no longer need continue statements as only one case clause will be executed by the switch statement. We’re also able to combine the duplicated logic of the "chocolate" and "vanilla" conditionals by separating each with a comma in the declaration of the case clause. The default clause serves as our catch-all clause. It will run for any flavors that we haven’t accounted for in the body of the switch statement. In this case, "banana" will cause default to execute, printing the message I've never tried banana before.

      This simplified form of switch statements addresses the most common use for them: comparing a variable against multiple alternatives. It also provides conveniences for us where we want to take the same action for multiple different values and some other action when none of the listed conditions are met by using the provided default keyword.

      When this simplified form of switch proves too limiting, we can use a more general form of switch statement.

      General Switch Statements

      switch statements are useful for grouping collections of more complicated conditionals to show that they are somehow related. This is most commonly used when comparing some variable against a range of values, rather than specific values as in the earlier example. The following example implements a guessing game using if statements that could benefit from a switch statement:

      package main
      
      import (
          "fmt"
          "math/rand"
          "time"
      )
      
      func main() {
          rand.Seed(time.Now().UnixNano())
          target := rand.Intn(100)
      
          for {
              var guess int
              fmt.Print("Enter a guess: ")
              _, err := fmt.Scanf("%d", &guess)
              if err != nil {
                  fmt.Println("Invalid guess: err:", err)
                  continue
              }
      
              if guess > target {
                  fmt.Println("Too high!")
                  continue
              }
      
              if guess < target {
                  fmt.Println("Too low!")
                  continue
              }
      
              fmt.Println("You win!")
              break
          }
      }
      

      The output will vary depending on the random number selected and how well you play the game. Here is the output from one example session:

      Output

      Enter a guess: 10 Too low! Enter a guess: 15 Too low! Enter a guess: 18 Too high! Enter a guess: 17 You win!

      Our guessing game needs a random number to compare guesses against, so we use the rand.Intn function from the math/rand package. To make sure we get different values for target each time we play the game, we use rand.Seed to randomize the random number generator based on the current time. The argument 100 to rand.Intn will give us a number in the range 0–100. We then use a for loop to begin collecting guesses from the player.

      The fmt.Scanf function gives us a means to read user input into a variable of our choosing. It takes a format string verb that converts the user’s input into the type we expect. %d here means we expect an int, and we pass the address of the guess variable so that fmt.Scanf is able to set that variable. After handling any parsing errors we then use two if statements to compare the user’s guess to the target value. The string that they return, along with bool, controls the message displayed to the player and whether the game will exit.

      These if statements obscure the fact that the range of values that the variable is being compared against are all related in some way. It can also be difficult, at a glance, to tell if we missed some part of the range. The next example refactors the previous example to use a switch statement instead:

      package main
      
      import (
          "fmt"
          "math/rand"
      )
      
      func main() {
          target := rand.Intn(100)
      
          for {
              var guess int
              fmt.Print("Enter a guess: ")
              _, err := fmt.Scanf("%d", &guess)
              if err != nil {
                  fmt.Println("Invalid guess: err:", err)
                  continue
              }
      
              switch {
              case guess > target:
                  fmt.Println("Too high!")
              case guess < target:
                  fmt.Println("Too low!")
              default:
                  fmt.Println("You win!")
                  return
              }
          }
      }
      

      This will generate output similar to the following:

      Output

      Enter a guess: 25 Too low! Enter a guess: 28 Too high! Enter a guess: 27 You win!

      In this version of the guessing game, we’ve replaced the block of if statements with a switch statement. We omit the expression argument to switch because we are only interested in using switch to collect conditionals together. Each case clause contains a different expression comparing guess against target. Similar to the first time we replaced if statements with switch, we no longer need continue statements since only one case clause will be executed. Finally, the default clause handles the case where guess == target since we have covered all other possible values with the other two case clauses.

      In the examples that we’ve seen so far, exactly one case statement will be executed. Occasionally, you may wish to combine the behaviors of multiple case clauses. switch statements provide another keyword for achieving this behavior.

      Fallthrough

      Sometimes you will want to reuse the code that another case clause contains. In these cases, it’s possible to ask Go to run the body of the next case clause listed using the fallthrough keyword. This next example modifies our earlier ice cream flavor example to more accurately reflect our enthusiasm for strawberry ice cream:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              switch flav {
              case "strawberry":
                  fmt.Println(flav, "is my favorite!")
                  fallthrough
              case "vanilla", "chocolate":
                  fmt.Println(flav, "is great!")
              default:
                  fmt.Println("I've never tried", flav, "before")
              }
          }
      }
      

      We will see this output:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! strawberry is great! I've never tried banana before

      As we’ve seen previously, we define a slice of string to represent flavors and iterate through this using a for loop. The switch statement here is identical to the one we’ve seen before, but with the addition of the fallthrough keyword at the end of the case clause for "strawberry". This will cause Go to run the body of case "strawberry":, first printing out the string strawberry is my favorite!. When it encounters fallthrough it will run the body of the next case clause. This will cause the body of case "vanilla", "chocolate": to run, printing strawberry is great!.

      The fallthrough keyword is not used often by Go developers. Usually, the code reuse realized by using fallthrough can be better obtained by defining a function with the common code. For these reasons, using fallthrough is generally discouraged.

      Conclusion

      switch statements help us convey to other developers reading our code that a set of comparisons are somehow related to each other. They make it much easier to add different behavior when a new case is added in the future and make it possible to ensure that anything we forgot is handled properly as well with default clauses. The next time you find yourself writing multiple if statements that all involve the same variable, try rewriting it with a switch statement—you’ll find it easier to rework when it comes time to consider some other alternative value.

      If you’d like to learn more about the Go programming language, check out the entire How To Code in Go series.



      Source link

      Using Break and Continue Statements When Working with Loops in Go


      Introduction

      Using for loops in Go allow you to automate and repeat tasks in an efficient manner.

      Learning how to control the operation and flow of loops will allow for customized logic in your program. You can control your loops with the break and continue statements.

      Break Statement

      In Go, the break statement terminates execution of the current loop. A break is almost always paired with a conditional if statement.

      Let’s look at an example that uses the break statement in a for loop:

      break.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Breaking out of loop")
                  break // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      This small program creates a for loop that will iterate while i is less than 10.

      Within the for loop, there is an if statement. The if statement tests the condition of i to see if the value is less than 5. If the value of i is not equal to 5, the loop continues and prints out the value of i. If the value of i is equal to 5, the loop will execute the break statement, print that it is Breaking out of loop, and stop executing the loop. At the end of the program we print out Exiting program to signify that we have exited the loop.

      When we run this code, our output will be the following:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Breaking out of loop Exiting program

      This shows that once the integer i is evaluated as equivalent to 5, the loop breaks, as the program is told to do so with the break statement.

      Nested Loops

      It is important to remember that the break statement will only stop the execution of the inner most loop it is called in. If you have a nested set of loops, you will need a break for each loop if desired.

      nested.go

      package main
      
      import "fmt"
      
      func main() {
          for outer := 0; outer < 5; outer++ {
              if outer == 3 {
                  fmt.Println("Breaking out of outer loop")
                  break // break here
              }
              fmt.Println("The value of outer is", outer)
              for inner := 0; inner < 5; inner++ {
                  if inner == 2 {
                      fmt.Println("Breaking out of inner loop")
                      break // break here
                  }
                  fmt.Println("The value of inner is", inner)
              }
          }
          fmt.Println("Exiting program")
      }
      

      In this program, we have two loops. While both loops iterate 5 times, each has a conditional if statement with a break statement. The outer loop will break if the value of outer equals 3. The inner loop will break if the value of inner is 2.

      If we run the program, we can see the output:

      Output

      The value of outer is 0 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 1 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 2 The value of inner is 0 The value of inner is 1 Breaking out of inner loop Breaking out of outer loop Exiting program

      Notice that each time the inner loop breaks, the outer loop does not break. This is because break will only break the inner most loop it is called from.

      We have seen how using break will stop the execution of a loop. Next, let’s look at how we can continue the iteration of a loop.

      Continue Statement

      The continue statement is used when you want to skip the remaining portion of the loop, and return to the top of the loop and continue a new iteration.

      As with the break statement, the continue statement is commonly used with a conditional if statement.

      Using the same for loop program as in the preceding Break Statement section, we’ll use a continue statement rather than a break statement:

      continue.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Continuing loop")
                  continue // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      The difference in using the continue statement rather than a break statement is that our code will continue despite the disruption when the variable i is evaluated as equivalent to 5. Let’s look at our output:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Continuing loop The value of i is 6 The value of i is 7 The value of i is 8 The value of i is 9 Exiting program

      Here we see that the line The value of i is 5 never occurs in the output, but the loop continues after that point to print lines for the numbers 6-10 before leaving the loop.

      You can use the continue statement to avoid deeply nested conditional code, or to optimize a loop by eliminating frequently occurring cases that you would like to reject.

      The continue statement causes a program to skip certain factors that come up within a loop, but then continue through the rest of the loop.

      Conclusion

      The break and continue statements in Go will allow you to use for loops more effectively in your code.



      Source link