{"componentChunkName":"component---src-templates-post-template-js","path":"/posts/javascript-conditional-statements-concepts","result":{"data":{"mdx":{"frontmatter":{"title":"JavaScript Conditional Statements","category":"javascript","date":"June 26th, 2020","readTime":6,"slug":"javascript-conditional-statements-concepts","embeddedImages":null,"image":{"childImageSharp":{"gatsbyImageData":{"layout":"constrained","backgroundColor":"#f8d858","images":{"fallback":{"src":"/static/0f3f8a06cc2369434957a15030e120c7/87706/p1.png","srcSet":"/static/0f3f8a06cc2369434957a15030e120c7/f80f8/p1.png 320w,\n/static/0f3f8a06cc2369434957a15030e120c7/9a63f/p1.png 640w,\n/static/0f3f8a06cc2369434957a15030e120c7/87706/p1.png 1280w","sizes":"(min-width: 1280px) 1280px, 100vw"},"sources":[{"srcSet":"/static/0f3f8a06cc2369434957a15030e120c7/c0bcc/p1.webp 320w,\n/static/0f3f8a06cc2369434957a15030e120c7/17574/p1.webp 640w,\n/static/0f3f8a06cc2369434957a15030e120c7/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 Conditional Statements\",\n  \"slug\": \"javascript-conditional-statements-concepts\",\n  \"image\": \"./images/p1.png\",\n  \"date\": \"2020-06-26T00:00:00.000Z\",\n  \"category\": \"javascript\",\n  \"readTime\": 6\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, \"Very often when we write code, we want to perform different actions for different decisions. We can use conditional statements to accomplish this.\"), mdx(\"h2\", null, \"if... else Statements\"), mdx(\"p\", null, \"if... else statements are the most common type of conditional statement. They're seen in many different coding languages, and follow the following syntax.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"if (condition) {\\n  // code to run if condition is true\\n} else {\\n  // code to run if condition is not true\\n}\\n\")), mdx(\"p\", null, \"It can help to think about a statement as the following pseudo-code: \\\"if the condition \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"returns true\"), \", run code\", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \" A\"), \", else run code \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"B\"), \"\\\"\"), mdx(\"p\", null, \"It's important to note that the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"else\"), \" statement is optional like in the following statement:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"if (condition) {\\n  // code to run if condition is true\\n}\\n// run other code\\n\")), mdx(\"p\", null, \"However, you need to be careful here. In this case, the second block of code is not involved at all with the conditional statement, so it will always run, regardless of whether the condition returns true or false. This is not necessarily a bad thing, but it might not be what you want \\u2014 often you will want to run one block of code or the other, not both.\"), mdx(\"h2\", null, \"else if\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"if... else\"), \" statements provide us with two potential outcomes, but what if we need more? \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"else if\"), \" allows us to have any potential outcomes as we may need. Consider the following example:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"if (userChoice === 'pizza') {\\n  console.log('$1.50')\\n} else if (userChoice === 'hamburger') {\\n  console.log('$2.50')\\n} else if (userChoice === 'taco') {\\n  console.log('$2.00')\\n} else {\\n  console.log('Please select an option')\\n}\\n\")), mdx(\"p\", null, \"It's important to remember that any value that is not \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"false\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"undefined\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"null\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"0\"), \", \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"NaN\"), \", or an empty string \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"('')\"), \" actually returns true when tested as a conditional statement, therefore you can simply use a variable name on its own to test whether it is true, or even that it exists, or not undefined.\"), mdx(\"h2\", null, \"Nesting\"), mdx(\"p\", null, \"It's perfectly ok, and fairly common, to nest \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"if... else\"), \" statements inside one another.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"if (userChoice === 'pizza') {\\n  if (userWallet >= 150) {\\n    console.log('Success!')\\n  } else {\\n    console.log('Doh!')\\n  }\\n}\\n\")), mdx(\"h2\", null, \"Using Logical Operators\"), mdx(\"p\", null, \"Logical operators can be used to test multiple conditions for \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"if... else\"), \" statements and potentially eliminate the need for \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"nesting\"), \" in some cases.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"if (userChoice === 'pizza' && userWallet >= 150) {\\n  console.log('Successfully ordered pizza!')\\n} else if (userChoice === 'hamburger' && userWallet >= 250) {\\n  console.log('Successfully ordered a hamburger!')\\n} else if (userChoice === 'taco' && userWallet >= 200) {\\n  console.log('Successfully ordered a taco!')\\n} else {\\n  console.log('Please select an option you can afford')\\n}\\n\")), mdx(\"p\", null, \"A common mistake when using logical operators is to forget to restate the variable for the binary expression. The following shows the right way and the wrong way to compare userWallet to several values.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"if (userWallet === 150 || 200 || 250) {\\n  // WRONG!\\n  // run my code\\n}\\n\\nif (userWallet === 150 || userWallet === 200 || userWallet === 250) {\\n  // RIGHT!\\n  // run my code\\n}\\n\")), mdx(\"p\", null, \"The first way is a valid conditional statement, but will likely produce undesired results. It will always run the code because both \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"200 and 250\"), \" will be evaluated as true making the statement execute.\"), mdx(\"h2\", null, \"switch Statements\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"if...else\"), \" statements are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"(e.g. multiple logical operators)\"), \". \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"switch statements\"), \", on the other hand, are ideal for when you have a large number of choices. They take a single expression/value as an input, and then look through a number of choices until they find one that matches that value, executing the corresponding code that goes along with it.\"), mdx(\"p\", null, \"The syntax is as follows:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"switch (expression) {\\n  case choice1:\\n    // run this code\\n    break\\n\\n  case choice2:\\n    // run this code instead\\n    break\\n\\n  // include as many cases as you like\\n\\n  default:\\n  // actually, just run this code since none of my choices matched expression\\n}\\n\")), mdx(\"p\", null, \"It's important to note that the default choice is optional and you can safely omit it if there is no chance that the expression could end up equaling an unknown value or if you don't want to run any code in the default case.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"switch (userChoice) {\\n  case 'pizza':\\n    console.log('$1.50')\\n    break\\n  case 'spaghetti':\\n    console.log('$5.50')\\n    break\\n  case 'lasagna':\\n    console.log('$8.50')\\n    break\\n  case 'hamburger':\\n    console.log('$2.50')\\n    break\\n  case 'cheeseburger':\\n    console.log('$3.00')\\n    break\\n  case 'chicken tenders':\\n    console.log('$3.50')\\n    break\\n  case 'taco':\\n    console.log('$2.00')\\n    break\\n  case 'burrito':\\n    console.log('$4.00')\\n    break\\n  default:\\n    console.log('Please select an option')\\n}\\n\")), mdx(\"p\", null, \"The break keyword tells the code to break out of the \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"switch\"), \" statement. If the break \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"if left out\"), \", the code that follows will continue to execute \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"(e.g. - if userChoice is equal to 'pizza' but the break is omitted, both '$1.50' and '$5.50' will be logged to the console)\"), \".\"), mdx(\"h2\", null, \"Ternary Operator\"), mdx(\"p\", null, \"For very simple cases but it's too much important for every framework like \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"reactJs, angular, vue\"), \", a ternary operator can be used for conditional cases. It uses the following syntax:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"condition ? 'run this code' : 'run this code instead'\\n\")), mdx(\"p\", null, \"Where if condition is true it will 'run this code', otherwise it will 'run this code instead'.\"), mdx(\"p\", null, \"An example can be seen below:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"let greeting = isBirthday\\n  ? 'Happy birthday ' + userName\\n  : 'Good morning ' + userName\\n\")), mdx(\"p\", null, \"It's important to note that ternary expression is completely optional. An \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"if... else\"), \" statement can always be used instead and in a lot of times can be far less confusing.\"), mdx(Link, {\n    to: \"/posts\",\n    className: \"btn center-btn\",\n    mdxType: \"Link\"\n  }, \"all posts\"));\n}\n;\nMDXContent.isMDXComponent = true;","id":"2752dadf-7a90-5530-bf8e-f25a65336666"}},"pageContext":{"slug":"javascript-conditional-statements-concepts"}},"staticQueryHashes":["3361116154","3824322444"]}