{"componentChunkName":"component---src-templates-post-template-js","path":"/posts/javascript-loops-concepts","result":{"data":{"mdx":{"frontmatter":{"title":"JavaScript Loops Concepts","category":"javascript","date":"June 27th, 2020","readTime":15,"slug":"javascript-loops-concepts","embeddedImages":null,"image":{"childImageSharp":{"gatsbyImageData":{"layout":"constrained","backgroundColor":"#f8d858","images":{"fallback":{"src":"/static/199e4508e2125de2f6e96286857db773/87706/p1.png","srcSet":"/static/199e4508e2125de2f6e96286857db773/f80f8/p1.png 320w,\n/static/199e4508e2125de2f6e96286857db773/9a63f/p1.png 640w,\n/static/199e4508e2125de2f6e96286857db773/87706/p1.png 1280w","sizes":"(min-width: 1280px) 1280px, 100vw"},"sources":[{"srcSet":"/static/199e4508e2125de2f6e96286857db773/c0bcc/p1.webp 320w,\n/static/199e4508e2125de2f6e96286857db773/17574/p1.webp 640w,\n/static/199e4508e2125de2f6e96286857db773/71d4d/p1.webp 1280w","type":"image/webp","sizes":"(min-width: 1280px) 1280px, 100vw"}]},"width":1280,"height":720}}}},"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"JavaScript Loops Concepts\",\n  \"slug\": \"javascript-loops-concepts\",\n  \"image\": \"./images/p1.png\",\n  \"date\": \"2020-06-27T00:00:00.000Z\",\n  \"category\": \"javascript\",\n  \"readTime\": 15\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"Loops offer a quick and easy way to do the same thing repeatedly. There are many different types of loops, but they all essentially do the same thing... they repeat an action some number of times (and it's actually thought that number could be zero). The different loop algorithms offer different ways to determine the start and endpoints of the loop. There are different situations that are more easily served by one type of loop over the other types.\"), mdx(\"h2\", null, \"while loop\"), mdx(\"p\", null, \"A while loop executes its block of code as long as a specified condition evaluates to true.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"while (condition) {\\n  // execute this code\\n}\\n\")), mdx(\"p\", null, \"If the condition becomes false at any time, the code within the loop stops executing and control passes to the statement following the loop. The test of the condition occurs before the code is executed, so if the initial condition is false, the code inside never executes.\"), mdx(\"p\", null, \"example:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let n = 0\\nlet x = 0\\n\\nwhile (n < 3) {\\n  n++\\n  x += n\\n}\\n\")), mdx(\"p\", null, \"*\", \"It's important to note that while loops can potentially become infinite if your logic does not allow for the loop to ever end\"), mdx(\"p\", null, \"example:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let n = 0\\nlet x = 0\\n\\nwhile (n < x + 1) {\\n  n++\\n  x += n\\n}\\n\")), mdx(\"p\", null, \"The flaw in the logic makes it so that n will never become greater than or equal to \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"x\"), \".\"), mdx(\"h2\", null, \"for...of loop\"), mdx(\"p\", null, \"A for loop can be thought of as a combination of a while loop with an initialization expression (that runs once prior to the loop condition ever being evaluated) as well as an increment expression (that runs every time after the loop body runs). The loop uses the following syntax:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"for ([initializationExpression]; [condition]; [incrementExpression]) {\\n  // execute this code\\n}\\n\")), mdx(\"p\", null, \"An example for loop can be found below:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let total = 10\\n\\nfor (let i = 0; i < total; ++i) {\\n  // execute code \\\"total\\\" times\\n}\\n\")), mdx(\"p\", null, \"You can think of the statement as the following. We initialize i as 0 once. Then while i is less than total we want to execute the code in braces. After the code executes, we want to run the increment expression and increment i by 1. Essentially, for loops are a simpler syntax for writing while loops. For instance, you could rewrite the above loop with a while loop and achieve the exact same thing, there would just be slightly more code involved.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let i = 0\\nlet total = 10\\n\\nwhile (i < total) {\\n  // execute code \\\"total\\\" times\\n  ++i\\n}\\n\")), mdx(\"h2\", null, \"do...while loop\"), mdx(\"p\", null, \"A \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"do...while\"), \" loop is similar to a while loop in that it executes a block of code while a specified condition is true; however, it swaps the order of evaluation and runs the code first and checks the condition after. It uses the following syntax:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"do {\\n  // execute this code\\n} while (condition)\\n\")), mdx(\"p\", null, \"An example of a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"do...while\"), \" loop can be seen below:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let i = 0\\nlet amount = 10\\nlet sleep = ''\\n\\ndo {\\n  sleep += 'Z'\\n} while (i++ < amount)\\n\")), mdx(\"p\", null, \"The major difference in this case between a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"while loop\"), \" and a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"do...while\"), \" loop is that if amount had been 0 for instance, a while loop would have never executed and sleep would have been an \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"empty string ''\"), \". However, using a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"do...while loop\"), \" ensures that the code will at least be executed once, and sleep will have the value \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"'Z'\"), \" even if amount is 0.\"), mdx(\"h2\", null, \"for...in loop\"), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"for...in\"), \" statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements. It uses the following syntax:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"for (variable in object) {\\n  // execute this code\\n}\\n\")), mdx(\"p\", null, \"An example for...in loop could be the following:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let car = {\\n  make: 'Acura',\\n  model: 'TL',\\n}\\n\\nfor (let i in car) {\\n  console.log(i) // would print 'make' in 1st loop and 'model' in 2nd\\n  console.log(car[i]) // would print 'Acura' in 1st loop and 'TL' in 2nd\\n}\\n\")), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"for...in\"), \" loops can technically be used to interate through Arrays; however, traditional for loops are recommended since a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"for...in\"), \" loop will iterate over user-defined properties in addition to the array indexes.\"), mdx(\"h2\", null, \"for...of loop\"), mdx(\"p\", null, \"The for...of statement initiates a loop Iterating over iterable objects (including Array, Map, Set, the argument object, and so on), executing a custom iteration hook with statements to be executed for the value of each individual property. It uses the subsequent syntax:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"for (variable of object) {\\n  // execute this code\\n}\\n\")), mdx(\"p\", null, \"It's similar to the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"for...in\"), \" loop, except where the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"for...in\"), \" loop iterates \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"over property names\"), \", the for...of loop iterates over iterable property values. The following illustrates the difference between the two loops.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let arr = [10, 11, 12]\\n\\narr.foo = 'bar'\\n\\nfor (let i in arr) {\\n  console.log(i) // logs '0', '1', '2', 'foo'\\n}\\n\\nfor (let i of arr) {\\n  console.log(i) // logs 10, 11, 12\\n}\\n\")), mdx(\"h2\", null, \"break statement\"), mdx(\"p\", null, \"Use the break statement to terminate a loop, switch, or in conjunction with a labeled statement. The syntax is as follows:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"break\\n// or\\nbreak labelName // if used with a labeled statement\\n\")), mdx(\"p\", null, \"The following is an example of using the break statement:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let names = ['Teddy', 'John', 'Mike', 'George'] // we can imagine this was initialized elsewhere\\n\\nfor (let i = 0; i < names.length; ++i) {\\n  if (names[i] === 'John') {\\n    console.log('We found John!') // and we DONT want to continue searching through the array\\n    break\\n  }\\n}\\n\")), mdx(\"h2\", null, \"continue statement\"), mdx(\"p\", null, \"The continue statement can be used to restart a \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"while\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"do...while\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"for\"), \", or \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"labeled statement\"), \". The syntax is as follows:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"continue\\n// or\\ncontinue labelName // if used with a labeled statement\\n\")), mdx(\"p\", null, \"The following is an example of using the continue statement:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let names = ['Teddy', 'devsrc', 'Mike', 'George'] // we can imagine this was initialized elsewhere\\n\\nfor (let i = 0; i < names.length; ++i) {\\n  if (names[i] === 'devsrc') {\\n    console.log('We found devsrc!') // and we DO want to continue searching through the array\\n    continue\\n  }\\n}\\n\")), mdx(\"h2\", null, \"labeled statement\"), mdx(\"p\", null, \"A label provides a statement with an identifier that lets you refer to it elsewhere in your program. You can create a label with the following syntax:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"labelName:\\n    // code to execute\\n\")), mdx(\"p\", null, \"The value of label may be any JavaScript identifier that is not a reserved word.\"), mdx(\"p\", null, \"The following is an example of labeling a while loop:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"markedWhile: while (someCondition === true) {\\n  // execute some code\\n}\\n\")), mdx(\"p\", null, \"It's fairly uncommon as it's not generally necessary to label blocks of code. There are limited use cases where it can be useful though (especially when nesting loops in other loops). For example, the following is an example where it could be useful:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let i\\nlet j\\n\\nloop1: for (i = 0; i < 3; i++) {\\n  //The first for statement is labeled \\\"loop1\\\"\\n  loop2: for (j = 0; j < 3; j++) {\\n    //The second for statement is labeled \\\"loop2\\\"\\n    if (i === 1 && j === 1) {\\n      continue loop1\\n    }\\n\\n    console.log('i = ' + i + ', j = ' + j)\\n  }\\n}\\n\\n// Output is:\\n//   \\\"i = 0, j = 0\\\"\\n//   \\\"i = 0, j = 1\\\"\\n//   \\\"i = 0, j = 2\\\"\\n//   \\\"i = 1, j = 0\\\"\\n//   \\\"i = 2, j = 0\\\"\\n//   \\\"i = 2, j = 1\\\"\\n//   \\\"i = 2, j = 2\\\"\\n// Notice how it skips both \\\"i = 1, j = 1\\\" and \\\"i = 1, j = 2\\\"\\n\")), mdx(\"p\", null, \"or using a break statement:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let i\\nlet j\\n\\nloop1: for (i = 0; i < 3; i++) {\\n  //The first for statement is labeled \\\"loop1\\\"\\n  loop2: for (j = 0; j < 3; j++) {\\n    //The second for statement is labeled \\\"loop2\\\"\\n    if (i === 1 && j === 1) {\\n      break loop1\\n    }\\n\\n    console.log('i = ' + i + ', j = ' + j)\\n  }\\n}\\n\\n// Output is:\\n//   \\\"i = 0, j = 0\\\"\\n//   \\\"i = 0, j = 1\\\"\\n//   \\\"i = 0, j = 2\\\"\\n//   \\\"i = 1, j = 0\\\"\\n// Notice the difference with the previous continue example\\n\")), mdx(Link, {\n    to: \"/posts\",\n    className: \"btn center-btn\",\n    mdxType: \"Link\"\n  }, \"all posts\"));\n}\n;\nMDXContent.isMDXComponent = true;","id":"249f76b3-eb0e-576c-ad01-5cd761fd2608"}},"pageContext":{"slug":"javascript-loops-concepts"}},"staticQueryHashes":["3361116154","3824322444"]}