<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alisa Bajramovic on Medium]]></title>
        <description><![CDATA[Stories by Alisa Bajramovic on Medium]]></description>
        <link>https://medium.com/@alisabajramovic?source=rss-83fb45c2f6ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IACMH1A5aEpWXOXX</url>
            <title>Stories by Alisa Bajramovic on Medium</title>
            <link>https://medium.com/@alisabajramovic?source=rss-83fb45c2f6ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:34:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alisabajramovic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The 6 Most Common Operators in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/the-6-most-common-operators-in-javascript-599cbd914484?source=rss-83fb45c2f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/599cbd914484</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alisa Bajramovic]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 04:53:04 GMT</pubDate>
            <atom:updated>2021-01-30T04:53:04.995Z</atom:updated>
            <content:encoded><![CDATA[<h4>You see them every day, but do you know what they are?</h4><p>In JavaScript, an operator is a way to compare or assign values, or perform operations. There are many different types of operators.</p><p>There are <em>binary</em> operators, <em>unary</em> operators, and a <em>ternary</em> operator in JavaScript. “Binary” means that there are <strong>two</strong> values, or <em>operands</em>, involved, with one coming before the operator, and one coming after the operator. An example of a binary operator is 1 + 2. In this example, 1 and 2 are the operands, and + is the operator.</p><p>A “unary” operator means that there is only <strong>one</strong> operand. The operand is either before the operator, or after the operator. An example of a unary operator is x++ (don&#39;t worry if you&#39;re unfamiliar with this syntax, we&#39;ll talk about below).</p><p>The “ternary” operator in JavaScript involves <strong>three</strong> operands. It’s used as a shortened version of an if...else statement, and is therefore also known as a &quot;conditional&quot; operator. An example of a ternary operator is num &gt;= 0 ? &quot;Positive&quot; : &quot;Negative&quot;. In this example, the three operands are num &gt;= 0, &quot;Positive&quot;, and &quot;Negative&quot;, and the operators that separate them are ? and :.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lHYKqGrLHMjK0lx4" /><figcaption>Photo by <a href="https://unsplash.com/@miracleday?utm_source=medium&amp;utm_medium=referral">Elena Mozhvilo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Assignment operators</h3><p>An <strong>assignment</strong> operator is a binary operator. It assigns a value to the left operand based on the value of the right operand.</p><p>The most common assignment operator is =, as in a = b. In this example, a is the left operand, and it&#39;s assigned the value of b, which is the right operand.</p><p>There are also <em>compound assignment operators</em>. Compound assignment operators typically combine assignment and arithmetic operators in a shortened version. For example, a += b is a shortened version of a = a + b.</p><p>Below is a table of some of the most common assignment operators:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/849298598a6b57b100c5111169fecd6d/href">https://medium.com/media/849298598a6b57b100c5111169fecd6d/href</a></iframe><p>Let’s see some examples of the above operators:</p><pre>let x = 10;<br>console.log((x += 3)); // x = 10 + 3 -&gt; x = 13</pre><pre>let y = 8;<br>console.log((y -= 3)); // y = 8 - 3 -&gt; y = 5</pre><pre>let z = 3;<br>console.log((z *= 3)); // z = 3 * 3 -&gt; z = 9</pre><pre>let m = 6;<br>console.log((m /= 3)); // m = 6 / 3 -&gt; m = 2</pre><pre>let n = 7;<br>console.log((n %= 3)); // n = 7 % 3 -&gt; n = 1</pre><h3>2. Comparison operators</h3><p>A <strong>comparison</strong> operator is a binary operator. It compares the two operands, and returns true or false depending on the comparison.</p><p>One comparison operator is less than, or &lt;. For example, 1 &lt; 2 would return true, because 1 is less than 2.</p><p>When comparing two values of different types, JavaScript does something called <strong>type conversion</strong>. This means that if you’re comparing a string with an integer, for example, JavaScript will try to convert the string into a number so that the values can actually be compared. There are two comparison operators that <strong>don’t</strong> do type conversion: strict equal, ===, and strict not equal, !==. Strict equal and strict not equal do not convert values of different types before performing the operation.</p><p>Below is a table of comparison operators in JavaScript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b7e1b6e26e4683ac51b48862252ae5d/href">https://medium.com/media/1b7e1b6e26e4683ac51b48862252ae5d/href</a></iframe><p>Let’s see some examples of the above operators:</p><pre>let x = 5;<br>let y = 2;<br>let z = 7;<br>let m = &quot;5&quot;;<br>let n = &quot;6&quot;;</pre><pre>x == m; // 5 == &quot;5&quot; -&gt; true<br>x != y; // 5 != 2 -&gt; true<br>x === z; // 5 === 7 -&gt; false<br>x !== m; // 5 !== &quot;5&quot; -&gt; true<br>x &gt; y; // 5 &gt; 2 -&gt; true<br>x &gt;= z; // 5 &gt;= 7 -&gt; false<br>x &lt; n; // 5 &lt; &quot;6&quot; -&gt; true<br>x &lt;= m; // 5 &lt;= &quot;5&quot; -&gt; true</pre><h3>3. Arithmetic operators</h3><p>An <strong>arithmetic</strong> operator can be a binary or unary operator. As a binary operator, it takes two numerical values as the operands, performs an arithmetic operation, and returns a numerical value. As a unary operator, it takes one numerical value, performs an operation, and returns a numerical value.</p><p>One arithmetic operator is the plus sign, +, which is used to add two numbers. For example, 4 + 6 would return 10. Below is a table of some of the arithmetic operators in JavaScript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d4fd32733cf909442adebd67bf6ffdf/href">https://medium.com/media/1d4fd32733cf909442adebd67bf6ffdf/href</a></iframe><p>Let’s see some examples of the above operators:</p><pre>let x = 3;<br>let y = 5;<br>let z = 6;<br>let a = 2;<br>let b = 7;</pre><pre>console.log(x + y); // 3 + 5 -&gt; 8<br>console.log(y - x); // 5 - 3 -&gt; 2<br>console.log(x * z); // 3 * 6 -&gt; 18<br>console.log(z / x); // 6 / 3 -&gt; 2<br>console.log(y % x); // 5 % 3 -&gt; 2<br>console.log(a++); // 2<br>console.log(--b); // 6<br>console.log(y ** x); // 5 * 5 * 5 -&gt; 125</pre><h3>4. Logical operators</h3><p>A <strong>logical</strong> operator can be a binary operator or a unary operator. As a binary operator, it typically takes two Boolean values, evaluates them, and returns a Boolean value.</p><p>The unary logical operator in JavaScript is the logical NOT. It takes one operand and evaluates if it can be converted to the Boolean value true.</p><p>Below is a table of logical operators in JavaScript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/587f659ad6b56b5644d39ece22d5d73d/href">https://medium.com/media/587f659ad6b56b5644d39ece22d5d73d/href</a></iframe><p>Let’s see some examples of the above operators:</p><pre>true &amp;&amp; true; // true<br>true &amp;&amp; false; // false<br>false &amp;&amp; false; // false</pre><pre>true || true; // true<br>true || false; // true<br>false || false; // false</pre><pre>!true; // false<br>!false; // true</pre><h3>5. String operators</h3><p>A <strong>string</strong> operator is a binary operator. It takes two strings and combines them into a single string using +, which in this case is called the <em>concatenation operator</em>. String <em>concatenation</em> means combining two string values together.</p><p>An example of a string operator is console.log(&quot;Happy &quot; + &quot;birthday&quot;), which console logs the string &quot;Happy birthday&quot;.</p><p>There is also a shortened version of the string operator, which is +=. For example:</p><pre>let string1 = &quot;birth&quot;;<br>let string2 = &quot;day&quot;;<br>console.log(string1 += string2) // &quot;birthday&quot;</pre><h3>6. Ternary (conditional) operator</h3><p>A <strong>conditional</strong> operator, or ternary operator, is used with three operands. It’s used to evaluate if a condition is true, and then returns one of two values depending on that.</p><p>The ternary operator is structured like the following:</p><pre>condition ? expressionIfTrue : expressionIfFalse</pre><p>Ternary operators are discussed at length <a href="https://medium.com/javascript-in-plain-english/the-2-types-of-conditional-statements-in-javascript-ffd14dc96b8b">in this post</a>.</p><p>This post just went over some of the more common operators you’ll use and come across in JavaScript. There are many more operators, including bitwise operators and relational operators, and I encourage you to learn more about them in the MDN documentation <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=599cbd914484" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-6-most-common-operators-in-javascript-599cbd914484">The 6 Most Common Operators in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intermediate JavaScript Concepts]]></title>
            <link>https://javascript.plainenglish.io/intermediate-javascript-concepts-aaba0406dfde?source=rss-83fb45c2f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaba0406dfde</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Alisa Bajramovic]]></dc:creator>
            <pubDate>Sat, 23 Jan 2021 18:14:14 GMT</pubDate>
            <atom:updated>2021-01-23T18:14:14.358Z</atom:updated>
            <content:encoded><![CDATA[<h4>Functions, Hoisting, Scope, and Closures</h4><h4>You see them every day, but do you know what they are?</h4><h3>1. Functions</h3><p>A function in JavaScript is a set of statements that take some input, do a certain task, and return some output.</p><p>When working with functions, you first have to <strong>define</strong> the function, which involves naming it and saying what actions it does. Then, it actually get those actions to happen, you have to <strong>call</strong> the function.</p><p>There are two main ways to define a function: <strong>function declarations</strong> and <strong>function expressions</strong>. (Note: there also is something called the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function">function constructor</a>, though it’s less commonly used.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hwXuh0Mf2XG3EKlM" /><figcaption>Photo by <a href="https://unsplash.com/@neal_johnson?utm_source=medium&amp;utm_medium=referral">Neal E. Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Function declarations</h4><p>A function declaration, also known as a function definition or a function statement, is one way to define a function. It’s structured like the following:</p><pre>function name(input) {<br>  statements;<br>}</pre><p>The name of the function is name. The input is the <em>parameters</em> for the function, and it&#39;s enclosed in parentheses. Inside of the curly brackets is statements, which do a certain task. statements often return a value, or an <em>output</em>. A function does not have to take in any parameters, so input is optional. The statements themselves are also optional (though that would just mean you&#39;d have an empty function that didn&#39;t do anything).</p><p>For example, let’s say we wanted to define a function using a function declaration that took in a number, and returned the given number times two:</p><pre>function double(number) {<br>  return number * 2;<br>}</pre><p>In this example, number is passed to the function by <strong>value</strong> alone; in other words, this function does not change number in the larger, global context. To illustrate what that means, let&#39;s insert a few console logs before and after the above function:</p><pre>// declaring a variable called `count` and setting it equal to 3<br>let count = 3;<br>console.log(count); // 3</pre><pre>// declaring a function called `double` which returns an inputted number times 2<br>function double(number) {<br>  return number * 2;<br>}</pre><pre>// declaring a variable called `result` is set equal to calling the function `double` and passing the number `count` as the input<br>let result = double(count);<br>console.log(result); // 6</pre><pre>console.log(count); // 3</pre><p>When we called the function double() and passed in count, we didn&#39;t change the value of count itself -- it still equaled 3.</p><p>However, this is only true of <em>primitive parameters</em> in JavaScript. If you pass a <em>non-primitive parameter</em> to a function (such as an array or object), and the function alters the object in some way, then the object is changed outside of the function as well. For example:</p><pre>let fruits = [&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;];</pre><pre>function removeLastElement(array) {<br>  array.pop();<br>  return array;<br>}</pre><pre>removeLastElement(fruits);</pre><pre>console.log(fruits); // [&quot;apple&quot;, &quot;banana&quot;]</pre><p>The above example uses the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">.pop() method</a>, which removes the last element of an array. By passing in the fruits object as a parameter in removeLastElement(), the last element of fruits was removed, and the updated array was returned. When working with non-primitive values, it&#39;s important to keep in mind that passing them into functions may end up changing their value.</p><h4>Function expressions &amp; arrow functions</h4><p>Another way to define functions is with a function expression. The main difference between a function expression and function declaration is that with function expressions, the function name is optional. If you don’t include a function name, you have an <strong>anonymous function</strong>. A function expression is structured like the following:</p><pre>function name(input) {<br>    statements;<br>}</pre><p>Note that this is the exact same structure as function declaration. The following is an example of an anonymous function, meaning that it does not have a name. The function is set equal to a variable called triple:</p><pre>const triple = function (number) {<br>  return number * 3;<br>};</pre><p>Function expressions are often written as <strong>arrow functions</strong>. Arrow functions are considered to be compact versions of function expressions, and are often used to “clean up” code. Let’s turn the above function into an arrow function:</p><pre>// Standard function expression<br>function (number) {<br>  return number * 3;<br>};</pre><pre>// Arrow function<br>number =&gt; number * 3;</pre><p>What changed with the arrow function? The words function and return were removed, there are no parentheses around the parameter number, the curly brackets were replaced by an arrow =&gt;, and everything is on one line.</p><p>However, these rules vary depending on the arrow function. If the function has only <strong>one</strong> parameter, then you don’t surround it in parentheses. If it has <strong>zero or 2+</strong> parameters, then you do surround it in parentheses. If the function has only <strong>one statement</strong>, then you don’t have the curly brackets or the word return. If the function has <strong>more than one statement</strong>, then you have <strong>both</strong> the brackets and the word return. Let&#39;s see an example of each of these:</p><pre>// One parameter, one statement<br>number =&gt; number * 3; // AB</pre><pre>// Zero parameters, one statement (these are often used in callback functions)<br>() =&gt; x * 2;</pre><pre>// Two parameters, one statement<br>(a, b) =&gt; a - b;</pre><pre>// Two parameters, multiple statements:<br>(a, b) =&gt; {<br>  let tax = 0.05;<br>  return (a + b) * tax;<br>};</pre><p>Arrow functions have a lot of changing syntax, depending on the function. However, it’s less important to memorize exactly when to use parentheses around an input, than it is to recognize what an arrow function generally looks like, and where to find more resources about it. Over time and with practice, you’ll end up not needing to refer back to the documentation. This is true of a lot of aspects of programming: rather than trying to memorize every little detail of how something is written and the specific ways to use it, it’s much better to recognize something and know where to go for more information. Every programmer uses Google and refers to documentation, no matter how long they’ve been doing it.</p><h4>Calling functions</h4><p>Just because you defined a function, that doesn’t mean the function has been executed. When you define a function, you say what it’s called and what it’s supposed to do. When you call a function, it actually gets performed.</p><p>To call a function, you refer to the function’s name, and pass in arguments that correspond to the parameters. To call the function triple(), which we defined above, we need to refer to its name, and pass in one number as an argument:</p><pre>triple(5);</pre><h3>2. Hoisting</h3><p><strong>Hoisting</strong> in JavaScript means that variable declarations and function declarations are brought to the top of the code.</p><p>This is tricky concept to grasp at first, so it can help to look at an example. Let’s create a function using a function declaration, and call it numberSquared. numberSquared() will take an inputted number, and then console log that value squared. Then, after the function, we can call it, and we&#39;ll pass in the number 5.</p><pre>function numberSquared(num) {<br>  console.log(num * num);<br>}</pre><pre>numberSquared(5);</pre><p>The result of the above code is 25.</p><p>Now, what would happen if we called the function <em>before</em> we declared the function?</p><pre>numberSquared(5);</pre><pre>function numberSquared(num) {<br>  console.log(num * num);<br>}</pre><p>Again, the result of the above code is 25. This is because the function declaration was brought to the top when your code was compiled.</p><p>Keep in mind that only function declarations, not function expressions, are hoisted.</p><h3>3. Scope and closures</h3><p>A <strong>scope</strong> in JavaScript is what is currently “visible” or “accessible”. According to <a href="https://developer.mozilla.org/en-US/docs/Glossary/Scope">MDN documentation</a>, “If a variable or other expression is not ‘in the current scope,’ then it is unavailable for use.”</p><p>In terms of functions, the variables that are declared in the function are only accessible within the function. This is called a <strong>closure</strong>.</p><p>To see examples of different scopes, let’s look at the following:</p><pre>const weather = &quot;rainy&quot;;</pre><pre>function myNameAndTheWeather() {<br>  const name = &quot;Alisa&quot;;</pre><pre>  console.log(name);<br>  console.log(weather);<br>}</pre><pre>myNameAndTheWeather();</pre><pre>console.log(weather);<br>console.log(name);</pre><p>What would happen if we ran this program? The output would be the following:</p><pre>Alisa<br>rainy<br>rainy<br>[ReferenceError: name is not defined]</pre><p>To understand why these are the results, let’s go over what the code says, and what happens when we run it. First, the variable weather is initialized and set equal to &quot;rainy&quot;. Then, using a function declaration, the function myNameAndTheWeather() is defined. Inside of myNameAndTheWeather(), the variable name is initialized and set equal to &quot;Alisa&quot;, name is console logged, and weather is console logged. Then, outside of the function, myNameAndTheWeather() is called. Then, weather is console logged. Finally, name is console logged.</p><p>When we run this program, the first thing that happens is that the function myNameAndTheWeather() is called. name is defined in the function, in the <strong>local scope</strong>, so the function is able to console log it. weather is defined outside of the function, in the <strong>global scope</strong>, so the function also has access to it. In other words, the function has access to variables declared in its own local scope (a closure) and in the global scope. Therefore, Alisa and rainy are logged to the console.</p><p>After myNameAndTheWeather() is executed, the program goes to the next line, which says to log weather to the console. weather is an accessible variable, so the program console logs its value. Finally, the program tries to console log the variable name. However, name is defined <em>within</em> the function myNameAndTheWeather(). It has a local scope, which means we don&#39;t have access to it from outside of the function. Therefore, a reference error is returned.</p><p>Let me know in the comments if you have any questions or other ways of thinking about functions, scope, and hoisting in JavaScript.</p><h4>Resources</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions</a></li><li><a href="https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function">https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">https://developer.mozilla.org/en-US/docs/Glossary/Hoisting</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Scope">https://developer.mozilla.org/en-US/docs/Glossary/Scope</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaba0406dfde" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/intermediate-javascript-concepts-aaba0406dfde">Intermediate JavaScript Concepts</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 2 Types of Conditional Statements in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/the-2-types-of-conditional-statements-in-javascript-ffd14dc96b8b?source=rss-83fb45c2f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffd14dc96b8b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Alisa Bajramovic]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 16:17:28 GMT</pubDate>
            <atom:updated>2021-01-20T16:17:28.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>What they are and when to use them</h4><p>Conditional statements tell your program to do a certain set of commands if a certain condition is true. In JavaScript, there are if...else statements and switch statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*irZKgDnXMZL3mO1g.jpg" /></figure><p>Conditional statements are used all the time in the non-programming world. Let’s say your friend asks you to pick them up some ice cream from the grocery store. They tell you, “If the store has mint chocolate chip ice cream, please get it. If the store doesn’t have that, please get cookies and cream. If the store doesn’t have that either, just get me chocolate ice cream.” Written another way, your friend is saying:</p><ul><li>If the store has mint chocolate chip ice cream: buy that.</li><li>Otherwise, if it has cookies and cream ice cream: buy that.</li><li>Otherwise: buy chocolate ice cream.</li></ul><p>Each one of these statements has a condition (“the store has mint chocolate chip ice cream”) and a statement to execute if that condition is true (“buy that”). It’s also important to note that the <strong>order</strong> matters in these statements. Your friend doesn’t want you to buy chocolate ice cream if cookies and cream is an option.</p><p>When working with conditional statements, it’s important to keep in mind what you’re checking and what order those things should be checked in.</p><h4>1. If…else statements</h4><p>An <strong>if…else statement</strong> is structured like the following:</p><pre>if (condition) {<br>    statement_1;<br>} else {<br>    statement_2;<br>}</pre><p>If condition is true, then statement_1 will execute. Otherwise, if the condition is false, then statement_2 will execute.</p><p>It’s important to note that the else clause is optional. Also, you can test multiple conditions in sequential order using else if:</p><pre>if (condition_1) {<br>    statement_1;<br>} else if (condition_2) {<br>    statement_2;<br>} else if (condition_3) {<br>    statement_3;<br>} else {<br>    statement_last;<br>}</pre><p>When multiple conditions are being tested, only the <strong>first</strong> condition that evaluates to true is executed.</p><p>To execute multiple statements, group them in a block statement, like the following:</p><pre>if (condition) {<br>    statement_1;<br>    statement_2;<br>} else {<br>    statement_3;<br>    statement_4;<br>}</pre><p>For example, let&#39;s say we have an array that keeps track of the temperature on each day of the week. If it&#39;s the end of the week (as in, the array has 7 temperatures in it), we want to report back that it&#39;s been a whole week. Otherwise, we want to log that it&#39;s not the end of the week yet:</p><pre>let arr = [55, 60, 58, 57, 54];<br>if (arr.length === 7) {<br>  console.log(&quot;It&#39;s been a whole week!&quot;);<br>} else {<br>  console.log(&quot;It&#39;s not the end of the week yet.&quot;);<br>}</pre><p>Let&#39;s take that example a step further, and incorporate some of the loops discussed in <a href="https://medium.com/javascript-in-plain-english/the-5-types-of-loop-in-javascript-8bdb8f8fc1e9">The 5 Types of Loops in JavaScript</a>. Rather than just logging if it&#39;s the end of the week, we should return what the average temperate was that week.</p><p>There are multiple ways to find the average (or <em>mean</em>) of an array of numbers. One involves using a for loop to find the sum of every value of the array, and then dividing it by the length of the array (average is total sum divided by count). We&#39;ll start by initializing a variable which will equal the sum of every value in the array. Because we only want to find the average temperature of a full week, we will do this in the statement following the if condition.</p><pre>let arr = [55, 60, 58, 57, 54, 52, 60];<br>if (arr.length === 7) {<br>  //initialize sum at 0 because we need to add values to it<br>  let sum = 0;<br>  //...<br>} else {<br>  console.log(&quot;It&#39;s not the end of the week yet.&quot;);<br>}</pre><p>Then, we can use a for loop to go over each value of the array, and add it to sum. The for loop will start a counter at 0, because <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#accessing_array_elements">arrays are zero-indexed in JavaScript</a>. It will go until the length of the array, or arr.length. And we want to check each element of the array, one at a time, so we will increment by 1 each time. Inside of the for loop, we want to add the current value of the array to sum. We can access the value of the array with arr[i].</p><pre>let arr = [55, 60, 58, 57, 54, 52, 60];<br>if (arr.length === 7) {<br>  let sum = 0;<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    sum = sum + arr[i]; // this could also be written as sum += arr[i]<br>  }<br>  //...<br>} else {<br>  console.log(&quot;It&#39;s not the end of the week yet.&quot;);<br>}</pre><p>Once the for loop is done executing, sum contains the total sum of every temperate that week. Since we want to return the average temperature, we can divide sum by 7 (the number of days in the week), and console log that value.</p><pre>let arr = [55, 60, 58, 57, 54, 52, 60];<br>if (arr.length === 7) {<br>  let sum = 0;<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    sum = sum + arr[i]; // this could also be written as sum += arr[i]<br>  }<br>  console.log(<br>    &quot;It&#39;s been a whole week! This week&#39;s average temperature was &quot; +<br>      sum / 7 +<br>      &quot;degrees.&quot;<br>  );<br>} else {<br>  console.log(&quot;It&#39;s not the end of the week yet.&quot;);<br>}</pre><h4>2. Switch statements</h4><p>The other kind of conditional statement supported in JavaScript is the <strong>switch statement</strong>. A switch statement evaluates an expression, and depending on that evaluation, tries to match it to a specified case. If a case matches, then that case&#39;s statement executes. A switch statement looks like the following:</p><pre>switch (expression) {<br>    case label_1:<br>        statement_1;<br>        break;<br>    case label_2:<br>        statement_2;<br>        break;<br>    default:<br>        statement_default;<br>        break;<br>}</pre><p>First, expression is evaluated. Then, your program will look for a case whose label matches the value of the expression, and then the associated statement is executed. If no matching label can be found, your program will look for the default clause (which is optional), and executes the associated statement. If there is no default clause, your program will simply exit the switch statement.</p><p>The break statements tell your program to break out of the switch once that case&#39;s statement is executed. break statements are optional. If you don&#39;t include them, your program will stay in the switch statement, and will execute the next statement in the switch statement.</p><p>For example, let’s say you’re trying to decide what jacket to wear, and it depends on the weather. If it’s hot, warm, or cold out, different jackets are appropriate:</p><pre>switch (weather) {<br>  case &quot;Hot&quot;:<br>    console.log(&quot;No jacket needed.&quot;);<br>    break;<br>  case &quot;Warm&quot;:<br>    console.log(&quot;Bring a light jacket.&quot;);<br>    break;<br>  case &quot;Cold&quot;:<br>    console.log(&quot;Bring your heavy jacket.&quot;);<br>    break;<br>  default:<br>    console.log(&quot;You probably should bring a jacket anyway, just in case!&quot;);<br>    break;<br>}</pre><p>You may be wondering, what exactly do the break statements do? Using the same example, let&#39;s say you didn&#39;t include any of the break statements, and that weather = &quot;Hot&quot;:</p><pre>let weather = &quot;Hot&quot;;<br>switch (weather) {<br>  case &quot;Hot&quot;:<br>    console.log(&quot;No jacket needed.&quot;);<br>  case &quot;Warm&quot;:<br>    console.log(&quot;Bring a light jacket.&quot;);<br>  case &quot;Cold&quot;:<br>    console.log(&quot;Bring your heavy jacket.&quot;);<br>  default:<br>    console.log(&quot;You probably should bring a jacket anyway, just in case!&quot;);<br>}</pre><p>The output would be:<br>No jacket needed. Bring a light jacket. Bring your heavy jacket. You probably should bring a jacket anyway, just in case!</p><p>This is because the label for the first case, &quot;Hot&quot;, matches weather, so that statement executes. Then, each subsequent statement executes, since there are no breaks telling your program to stop.</p><h4>The ternary operator</h4><p>The <strong>ternary operator</strong> is not a type of conditional statement. Instead, it’s an operator that checks a condition. It’s a single line of code, and because it’s so condensed, it’s often used as a shortened version of a simple if...else statement.</p><p>The ternary operator is structured like the following:</p><pre>condition ? expressionIfTrue : expressionIfFalse</pre><p>The condition is an expression that&#39;s evaluated. If condition is <a href="https://developer.mozilla.org/en-US/docs/Glossary/truthy"><em>truthy</em></a> (meaning that it is true, or its value can be converted to true), expressionIfTrue is executed. If condition is <a href="https://developer.mozilla.org/en-US/docs/Glossary/falsy"><em>falsy</em></a> (meaning that it is false, or its value can be converted to false, which includes null, NaN, 0, &quot;&quot;, undefined), expressionIfFalse is executed.</p><p>For example, let’s say the original if...else statement checks if a number is positive:</p><pre>const num = 4;<br>if (num &gt;= 0) {<br>  console.log(&quot;Positive&quot;);<br>} else {<br>  console.log(&quot;Negative&quot;);<br>}</pre><p>The condition is num &gt;=0, which means that&#39;s what we&#39;re checking. Using a ternary operator, that will go on the left side of the question mark ?. If it&#39;s truthy, we&#39;ll want to console log &quot;Positive&quot;, so that&#39;s the first expression after the ?. If it&#39;s falsy, we&#39;ll want to console log &quot;Negative&quot;, so that&#39;s the second expression, and it comes after the colon :.</p><p>We can store the result of the ternary operator into a variable called positiveCheck. Then, we can console log the value of that variable.</p><pre>const num = 4;<br>const positiveCheck = num &gt;= 0 ? &quot;Positive&quot; : &quot;Negative&quot;;<br>console.log(positiveCheck);</pre><p>Some people like ternary operators because they save space when working with simple conditional statements, but not everyone likes them or uses them. Whether or not you use ternary operators, it’s important to know what they look like and how to read them in case you encounter them.</p><h4>Conclusion</h4><p>Please let me know in the comments if you have any questions or other ways of thinking about conditional statements in JavaScript.</p><p><strong>Resources:</strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals">https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffd14dc96b8b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-2-types-of-conditional-statements-in-javascript-ffd14dc96b8b">The 2 Types of Conditional Statements in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 5 Types of Loop in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/the-5-types-of-loop-in-javascript-8bdb8f8fc1e9?source=rss-83fb45c2f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdb8f8fc1e9</guid>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Alisa Bajramovic]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 18:13:11 GMT</pubDate>
            <atom:updated>2023-06-13T14:46:21.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>The 5 Types of Loops in JavaScript</h3><h4>What they are and when to use them</h4><p>A <a href="https://www.youtube.com/watch?v=EZYzmpPGy3E">loop</a> tells your program to repeatedly do a certain action. The number of times your program should do that action depends on the conditions that you set.</p><p>In non-programming terms, let’s say you’re giving your friend directions to your house. They call you and say that they’re on your street, but they don’t know which house is yours. You tell them, “keep walking north until you reach the yellow house on the corner”. In this statement, “until you reach the yellow house on the corner” is the condition you’ve set for your friend. They will continue to walk north <em>until</em> they get to that house, at which point they’ll <em>stop</em> walking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iq9WzIuPpF9rGYyUTDx4bw.png" /><figcaption>Your friend walks north toward your house until they reach your house</figcaption></figure><p>What would happen if you didn’t give your friend the condition? In other words, what would happen if you just said to your friend, “keep walking north”? Your friend would never know when to stop. They would keep walking north way past your house. You can’t blame your friend for not finding your house, since you never told them when to stop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aSpcK-7eso1h56sQe6R-w.png" /><figcaption>Your friend has walked past your house, and they are still going north</figcaption></figure><p>This non-programming example illustrates one of the most common issues people encounter when working with loops: the <strong>infinite loop</strong>. If you don’t tell your loop when to stop, the loop will keep going forever. Importantly, if you tell your loop when to stop, but that stopping point could never actually be reached, that also is an infinite loop. Using the same example, let’s say you told your friend “keep walking north until you reach the pink house on the corner”. Your friend keeps walking north, but no matter how far they walk, they never find a pink house on the corner. Even though you gave your friend an ending point, they never could reach that ending point, so they would (theoretically) keep walking forever.</p><p>When working with loops, it’s very important that you say when the loop should stop running, and that that ending point can actually be reached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1O6kvitXbRLJIA1Y" /><figcaption>Photo by <a href="https://unsplash.com/@etiennegirardet?utm_source=medium&amp;utm_medium=referral">Etienne Girardet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>1. While loops</h4><p>One of the most popular loops is a <strong>while loop</strong>. A while loop is structured like the following:</p><pre>while (condition) {<br>  statement<br>}</pre><p>Before the statement is executed, condition is tested. If it evaluates to true, then the statement is executed. As long as condition is true, the statement continues to execute. When condition becomes false, the statement stops executing.</p><p>For example, let’s say you have a variable called e, which starts out by equaling 0. You want e to keep <em>incrementing </em>(or increasing by 1) as long as e is less than 4.</p><pre>let e = 0;<br>while (e &lt; 4) {<br> e++;<br>}</pre><p>Here is a table breaking down what’s going on in the above loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c13c52a833422a2ba7a38aa4c2e490a/href">https://medium.com/media/8c13c52a833422a2ba7a38aa4c2e490a/href</a></iframe><p>As long as e &lt; 4 is true, the loop executes. When it becomes false, it does not execute.</p><p>It’s very easy to accidentally write an infinite loop when working with `while` loops. For example, if the condition from the above example was e &gt;= 0, then the loop will infinitely execute. e starts at 0, which means the condition is true, and keeps getting bigger, which means the condition will always evaluate to true:</p><pre>//Infinite loop<br>let e = 0;<br>while (e &gt;= 0) {<br> e++;<br>}</pre><h4>2. For loops</h4><p>Another loop that’s widely used is the <strong>for loop</strong>. A for loop is structured like the following:</p><pre>for (initialExpression; conditionExpression; incrementExpression) {<br> statement<br>}</pre><p>The initialExpression is the first thing that runs. Any variable created in this expression is <em>scoped</em> to the loop (meaning that you cannot refer to this variable from outside of the loop). The initialExpression is usually where a counter is initialized.</p><p>The conditionExpression is then evaluated for being either true or false. If it’s true, then the statement executes. If it’s false, the statement does not execute, and the for loop terminates. If no conditionExpression is listed, then the condition is automatically true.</p><p>The incrementExpression runs <em>after</em> the statement executes. Just as the initialExpression usually initializes a counter in a for loop, the incrementExpression usually increments that counter. However, the expression also can <em>decrement</em> the counter (or decrease by 1). At this point, the conditionExpression is evaluated again, and if it’s still true, then the for loop continues to execute.</p><p>For example, let’s create a for loop that logs the phrase “I can count to X” to the console, where X is a number starting at 1, and going to 5. We start by initializing a variable in the initialExpression with let i = 1. Then, we set the conditionExpression to i &lt;= 5. This means that the statement will continue to run as long as i is less than or equal to 5. Finally, we want to increase i by 1 each time the loop executes, so incrementExpression is i++. <strong>Note:</strong> it’s important that each of the expressions is separated by a semicolon, ;.</p><pre>for (let i = 1; i &lt;= 5; i++) {<br> console.log(“I can count to “ + i)<br>}</pre><p>Here is a table breaking down what’s going on in the above loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/321dcd456d1ddd13e32a8a52e74161ea/href">https://medium.com/media/321dcd456d1ddd13e32a8a52e74161ea/href</a></iframe><p>Infinite loops also happen with for loops. One example of an infinite loop would be using the same example above, but changing the third expression to be i — -. i — - means that i keeps decreasing, so i will start at 1, then become 0, then -1, and so on. All the while, i &lt;=5 will continue to evaluate to true, because i will always be less than or equal to 5.</p><pre>//Infinite loop<br>for (let i = 1; i &lt;= 5; i — ) {<br> console.log(“I can count to “ + i)<br>}</pre><h4>3. Do…while loops</h4><p>The <strong>do…while loop</strong> is very similar to the while loop. A do...while loop is structured like the following:</p><pre>do {<br>  statement<br>} while (condition);</pre><p>The first thing that happens in this loop is the statement is executed. Once that happens, condition is checked. If condition evaluates to true, the statement executes again. The statement keeps executing until condition evaluates to false. The major difference between the do...while loop and the while loop is that the statement will always be executed <strong>at least once</strong>.</p><p>For example, let’s initialize a variable called booksRead to equal 10. We want to log “I read X books this year” to the console, where X is the value of booksRead. We’ll then set the condition to be booksRead &lt; 14. <strong>Note:</strong> in the below example, I use <em>string interpolation</em> when console logging the number of books read this year. String interpolation is done by using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literals</a> in JavaScript.</p><pre>let booksRead = 10;<br>do {<br> console.log(`I read ${booksRead} books this year`);<br> booksRead++;<br>} while (booksRead &lt; 14);</pre><p>Here is a table breaking down what’s going on in the above loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/249d7a38704e2c571e1fce76c9bc26ec/href">https://medium.com/media/249d7a38704e2c571e1fce76c9bc26ec/href</a></iframe><p>One way you can create an infinite loop when working with do…while loops is if you don’t increment the variable that you’re checking in the condition. Using the same example as above, if you never increment booksRead, then booksRead stays at 10 forever, which means the condition, booksRead &lt; 14, will always be true.</p><pre>//Infinite loop<br>let booksRead = 10;<br>do {<br> console.log(`I read ${booksRead} books this year`);<br>} while (booksRead &lt; 14);</pre><h4>4. For…in loops</h4><p>A <strong>for…in loop</strong> is used with an object in JavaScript. It’s structured like the following:</p><pre>for (variable in object) {<br> statement<br>}</pre><p>A for…in loop iterates a variable over each property (or key) of an object. For each property, the statement is executed. The loop enables you to access each property of an object without knowing the name of the property. `for…in` loops iterate over the object’s properties in an arbitrary order. Therefore, according to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">MDN documentation</a>, “it is best <strong>not to add, modify, or remove properties</strong> from the object during iteration, other than the property currently being visited”. You also should <strong>not use for…in loops with arrays</strong>.</p><p>For example, let’s say you had an object that listed each meal you had that day, and you wanted to console log everything you ate. The object is called foodIAte. Using a for…in loop, you can list the name of each meal, as well as what you ate for that meal.</p><pre>const foodIAte = {<br> breakfast: ‘eggs’,<br> lunch: ‘salad’,<br> dinner: ‘pizza’<br>};</pre><pre>for(const meal in foodIAte) {<br> console.log(`For ${meal}, I ate ${foodIAte[meal]}.`);<br>};</pre><p>Here is a table breaking down what’s going on in the above loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61a3e431a0a076206bdb6477d91b1a4a/href">https://medium.com/media/61a3e431a0a076206bdb6477d91b1a4a/href</a></iframe><h4>5. For…of loops</h4><p>The last loop is the <strong>for…of loop</strong>. The for…of loop can be used with <em>iterable objects</em>, which includes arrays, maps, sets, strings, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">and more</a>. It’s structured like the following:</p><pre>for (variable of iterableObject) {<br> statement<br>}</pre><p>The for…of loop iterates over iterableObject, and a statement is executed for the value of each property in iterableObject. While for…in loops iterate over the property <em>name</em>, for…of loops iterate over the property <em>value</em>.</p><p>For example, let’s say you have an array, and want to console log each value of the array:</p><pre>const array = [5, 10, 15];<br>for (const value of array) {<br> console.log(value);<br>}</pre><p>The above loop would console log 5, 10, 15.</p><p>Let’s say you have a string, and want to console log each value of the string:</p><pre>const string = “cat”;<br>for (const value of string) {<br> console.log(value);<br>}</pre><p>The above loop would console log c, a, t.</p><p>Here is a video by <a href="http://twitter.com/sunilsandhu">Sunil Sandhu</a> that also covers each of these 5 loops with examples:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEZYzmpPGy3E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEZYzmpPGy3E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEZYzmpPGy3E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/688298806f42b4baa897584eb97e9928/href">https://medium.com/media/688298806f42b4baa897584eb97e9928/href</a></iframe><p>Please let me know in the comments if you have any questions or other ways of thinking about loops in JavaScript.</p><p><strong>Resources<br></strong>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols</a><br>- <a href="https://www.w3schools.com/js/js_loop_for.asp">https://www.w3schools.com/js/js_loop_for.asp</a><br>- <a href="https://www.freecodecamp.org/news/javascript-loops-explained-for-loop-for/">https://www.freecodecamp.org/news/javascript-loops-explained-for-loop-for/</a><br>- <a href="https://www.javascripttutorial.net/javascript-for-in/">https://www.javascripttutorial.net/javascript-for-in/</a></p><p><strong>Learn more:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEZYzmpPGy3E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEZYzmpPGy3E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEZYzmpPGy3E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/688298806f42b4baa897584eb97e9928/href">https://medium.com/media/688298806f42b4baa897584eb97e9928/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdb8f8fc1e9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-5-types-of-loop-in-javascript-8bdb8f8fc1e9">The 5 Types of Loop in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways to Rotate an Array]]></title>
            <link>https://medium.com/better-programming/3-ways-to-rotate-an-array-2a45b39f7bec?source=rss-83fb45c2f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a45b39f7bec</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alisa Bajramovic]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 13:26:17 GMT</pubDate>
            <atom:updated>2020-07-14T13:26:17.333Z</atom:updated>
            <content:encoded><![CDATA[<h4>There’s nothing easy about this algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lj4kmi0QAWGfIROpG3olWg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@publicpowerorg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">American Public Power Association</a> on <a href="https://unsplash.com/s/photos/arrays?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>One of the most commonly found algorithms is the <a href="https://leetcode.com/problems/rotate-array/">Rotate Array problem</a>:</p><blockquote>Given an array, rotate the array to the right by k steps, where k is non-negative. Try to come up as many solutions as you can — there are at least three different ways to solve this problem. Could you do it in place with O(1) extra space?</blockquote><p>For example, if you were given the array [1, 2, 3, 4, 5] , and told to rotate it 2 steps to the right, the output should be [4, 5, 1, 2, 3]. After one rotation right, the array would be [5, 1, 2, 3, 4], so that after two rotations right, the array becomes [4, 5, 1, 2, 3].</p><p>On Leetcode, this problem is labeled “easy” — how they determine the difficulty level, I’m not sure. However, I think this problem is by no means easy. There are many ways to solve this problem, which is partly why I like it, and I think each solution is complicated in its own way.</p><p>In this article, I’ll walk through three different ways to approach and solve this problem:</p><ol><li>Popping and unshifting the elements in the array.</li><li>Creating a new array where the elements start out shifted.</li><li>Reversing different sections of the array.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ieB9Zj-EKlGxn49W" /><figcaption>Photo by <a href="https://unsplash.com/@paan_azam13?utm_source=medium&amp;utm_medium=referral">Farhan Azam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Approach #1: Popping and Unshifting</h3><p>When working with arrays, a few methods come up all the time. One these is .pop(), which “removes the last element from an array and returns that element” (read more about .pop() <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">here</a>). For example:</p><pre>const arr = [1, 2, 3]<br>arr.pop() // would return 3<br>console.log(arr) // would print [1, 2]</pre><p>Another common method used on arrays is .unshift(). This method “adds one or more elements to the beginning of an array and returns the new length of the array” (`read more about .unshift() <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift">here</a>). For example:</p><pre>const arr = [2, 3]<br>arr.unshift(1) // would return 3, the new length of the array<br>console.log(arr) // would print [1, 2, 3]</pre><p>Rotating an array right can also be thought of as moving the elements from the back of the array to the front of the array. In this problem, we want to move elements from the back of the array to the front, doing so k times. In a for loop, which will run k times, we can pop the last number off the back of the array, and unshift that number to the front of the array.</p><p>For example, let’s say we were given the array nums = [1, 2, 3, 4, 5] and k = 2, so we should rotate the array twice. Using pop and unshift, we’d start by popping off the last element, 5, which would make nums = [1, 2, 3, 4]. Then, we unshift 5, putting it at the front of the array, so that nums = [5, 1, 2, 3, 4].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*u23vSKxlx46U6OKIxYqErQ.png" /><figcaption>nums = [1, 2, 3, 4, 5]; nums.pop() = 5; nums = [1, 2, 3, 4]; nums.unshift(5) = [5, 1, 2, 3, 4]</figcaption></figure><p>We repeat this cycle once more, popping off the 4, making nums = [5, 1, 2, 3], and then unshifting 4, giving us the final answer of nums = [4, 5, 1, 2, 3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*e0mEFWGjQTytWzW2NtI28A.png" /><figcaption>nums.pop() = 4; nums = [5, 1, 2, 3]; nums.unshift(4) = [4, 5, 1, 2, 3]</figcaption></figure><h4><strong>Coding the first approach</strong></h4><p>Before we start coding this solution, there’s one more thing to note about this problem. Let’s say that the given array was [1, 2], and we were told to rotate it to the right seven times. The array is less than seven elements long, so rotating it seven times would be a lot of unnecessary work. So, before we do anything, both in this solution and in the other approaches, we should modify k using modulo (%).</p><p>The modulo operator returns the remainder after dividing one number by another. For example, 10%3 would return 1, because 10/3 has a remainder of 1. Similarly, in this problem, we want to set k equal to k % nums.length. Using the same example, if k = 7, and nums = [1, 2], then k = k % nums.length is the same as k = 7%2, or k = 1. So, the first line of this solution will be this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a746de438d72413d7c5d5feadd1a6a37/href">https://medium.com/media/a746de438d72413d7c5d5feadd1a6a37/href</a></iframe><p>We want to do .pop()and .unshift() as many times as k equals, so we make a for loop that repeats k times. Inside the for loop, we store the result of nums.pop() to a variable called back. Then, we unshift back, putting it at the start of the nums array.</p><p>Once the for loop stops executing, we return nums.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be90e0509f5ed070d85aaec4882a90c0/href">https://medium.com/media/be90e0509f5ed070d85aaec4882a90c0/href</a></iframe><p>This first approach is done in linear time (O(n)) and constant space (O(1)).</p><h3>Approach #2: Creating a New Array</h3><p>In the second approach, we’re creating a new array, where the elements have moved over k spaces. The idea here is that we can just iterate through the nums array, and move each element k spaces to the right of where it was.</p><p>What happens if the element is supposed to move to an index that’s longer than the length of the nums array? In that case, you use the modulo operator, calculating the result of moving to the new distance % the length of the nums array. I think this is a particularly tricky part of this approach, so I’ll use an example.</p><p>Let’s say you’re starting out with the array nums = [1, 2, 3] and a blank array arr. We’re told k = 2, so the array will move over 2 spots to the right. We start out by moving the first element of the nums array, 1. 1 is at index 0 (i = 0), and we want to move it two spots over. In other words, we want its position in the arr array to be determined by i + k which is index 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*rH6Piijkj0ioUvxJUK5euA.png" /><figcaption>nums = [1, 2, 3]; arr = [ ]; i = 0; i + k = 2; arr = [&lt;empty&gt;, &lt;empty&gt;, 1]</figcaption></figure><p>Now, we’re on index one of the nums array, 2. We want to move it k steps to the right, but i + k is 3, and that would be longer than the length of the nums array. So, to find the new spot for 2, we should do (i + k) % nums.length, or 3%3, which is 0. So, we should move the element 2 to the index 0 in arr.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*wCt9iEmfRzlbSuMTqS2qfw.png" /><figcaption>i = 1; i + k = 3; nums.length = 3; 3 % 3 = 0; arr = [2, &lt;empty&gt;, 1]</figcaption></figure><p>Finally, we’re on the index two of the nums array, which is 3. We want to move it k steps to the right, and i + k is 4, which is longer than the length of the nums array. So, to find the new spot for 3, we should do (i + k) % nums.length, or 4%3, which is 1. So, we should move the element 3 to the index 1 in arr, giving us the final result of this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*ideSuBTVuDJwxs4fNr8OKA.png" /><figcaption>i = 2; i + k = 4; nums.length = 3; 4% 3 = 1; arr = [2, 3, 1]</figcaption></figure><h4><strong>Coding the second approach</strong></h4><p>To start out this solution, we do the same modifications to k that we did in the first approach. We then initialize a new, empty array called arr.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0767d1bec34b120ffe2d36de81f216dd/href">https://medium.com/media/0767d1bec34b120ffe2d36de81f216dd/href</a></iframe><p>Now, we use a for loop to go through every element in nums. At each index, we place that element in the new spot in arr. We can find that new spot by doing (i + k) % nums.length. So, we set arr[(i + k) % nums.length] equal to nums[i].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e65b874cd01b6af3ecf15d2370e7a9e/href">https://medium.com/media/3e65b874cd01b6af3ecf15d2370e7a9e/href</a></iframe><p>Now, arr will be the rotated array that we want. However, in this problem, we should be modifying the nums array, so we have to set each index in nums equal to the value at that index in arr. To do this, we set up another for loop. At each index, we’ll set nums[i] equal to arr[i]. When the for loop ends, we can return nums.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ee80b6313b8f52d67bb7df82f61472d/href">https://medium.com/media/0ee80b6313b8f52d67bb7df82f61472d/href</a></iframe><p>This second approach is done in linear time (O(n)) and linear space (O(n)).</p><h3><strong>Approach #3: Reversing the Sections</strong></h3><p>In this third approach, we’re going to be reversing parts of the nums. The first time, we reverse the entire array. The second time, we reverse the first k elements of the array. The third time, we reverse the final elements of the array, from k to the end.</p><p>The idea behind this approach is best be seen with an example. We start with the array [1, 2, 3, 4, 5], and we want to rotate it two steps. We start by rotating the entire array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*2-vSfYUCPbMhiYyELJXazg.png" /><figcaption>[1, 2, 3, 4, 5] -&gt; [5, 4, 3, 2, 1]</figcaption></figure><p>Now, we’ll want to rotate the first k elements. Since k is 2, we’ll rotate the elements at 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*zKyx6Z30xFbdfzQH6gas7g.png" /><figcaption>[5, 4, 3, 2, 1] -&gt; [4, 5, 3, 2, 1]</figcaption></figure><p>Finally, we’ll rotate the last elements, from index k to the end. This gives us the final array that we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*qvRPpHHoJyXOnYYUwHE16Q.png" /><figcaption>[4, 5, 3, 2, 1] -&gt; [4, 5, 1, 2, 3]</figcaption></figure><p><strong>Coding the third approach<br></strong>To code this solution, we’ll write a function called reverse within the rotate function, and we’ll call it three times. To start, however, we’ll do the same modification to k that we did in the previous two approaches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb424170da90ef7b512c12a75417a825/href">https://medium.com/media/bb424170da90ef7b512c12a75417a825/href</a></iframe><p>Then, we’ll call the function reverse (which we’ll write in a minute), and we’ll call it three times. reverse() will take in the array, the index to start reversing, and the index to end reversing. So, the first call to reverse() will pass in nums, 0 (as the start index), and nums.length — 1 (as the end index). The second call to reverse() will pass in nums, 0 (as the start index), and k — 1 (as the end index). The third call to reverse() will pass in nums, k (as the start index), and nums.length — 1 (as the end index).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/211c4f882fb8ed017bbd253e7f125f38/href">https://medium.com/media/211c4f882fb8ed017bbd253e7f125f38/href</a></iframe><p>Now, we can write the function reverse, whose parameters will be nums, start, and end. In this function, we switch the values at the start and end index, and move start and end toward the center. We keep doing this as long as start is less than end.</p><p>So, we write a while loop, that will keep going as long as start is less than end. Inside the loop, we keep a temporary variable that stores the value of the nums array at the start index. Then, we set the value at the start index equal to the value at the end index and the value at the end index equal to the temporary variable. We move start toward the middle by incrementing it and we move the end toward the middle by decrementing it. Finally, when the while loop has executed, well return nums to the rotate function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d885cb6706427a779f1767bf08a9301d/href">https://medium.com/media/d885cb6706427a779f1767bf08a9301d/href</a></iframe><p>Once each reverse() function has executed, the final thing is to return nums:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bdc4790411930ae86b6d66976a34f16/href">https://medium.com/media/4bdc4790411930ae86b6d66976a34f16/href</a></iframe><p>This solution is done in linear time (O(n)) and constant space (O(1)).</p><p>Let me know in the comments if you have any questions or ideas for other ways to solve this!</p><h3><strong>Resources</strong></h3><ul><li><a href="https://leetcode.com/problems/rotate-array/">https://leetcode.com/problems/rotate-array/</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a45b39f7bec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/3-ways-to-rotate-an-array-2a45b39f7bec">3 Ways to Rotate an Array</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Climbing Staircase Problem]]></title>
            <link>https://javascript.plainenglish.io/solving-the-climbing-staircase-problem-e412cf761636?source=rss-83fb45c2f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/e412cf761636</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technical-interview]]></category>
            <dc:creator><![CDATA[Alisa Bajramovic]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 17:38:05 GMT</pubDate>
            <atom:updated>2020-07-13T17:38:05.978Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Fibonacci numbers to approach this common algorithm</h4><p>A common algorithm found in technical interviews is the <a href="https://leetcode.com/problems/climbing-stairs/">Climbing Staircase Problem</a>:</p><blockquote>You are climbing a stair case. It takes <em>n</em> steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?</blockquote><p>For example, if the input were 2 (there’s 2 stairs in the staircase), then there are 2 distinct ways to climb to the top. You can either climb one step at a time, or climb both steps at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*EWh8YdfyKAopYat9FdMDXQ.png" /><figcaption>Two 2-step staircases. The first staircase is one step at a time, the second staircase is two steps at once.</figcaption></figure><p>This is one of those problems where there’s a lot of ways to solve it — including recursion and memoization, and dynamic programming — but the solution I like the most involves the Fibonacci number. In this post, I’ll explain what the Fibonacci numbers are, their relevance to this problem, and how to solve the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e4sp0LW1y9VHj5y0" /><figcaption>Photo by <a href="https://unsplash.com/@reidzura?utm_source=medium&amp;utm_medium=referral">Reid Zura</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Fibonnaci Numbers</h3><p>The Fibonacci numbers (also known as the Fibonacci sequence) are a series of numbers defined by a recursive equation:</p><blockquote>Fn = Fn-1 + Fn-2</blockquote><p>The sequence starts with F0 = 0, and F1 = 1. That means that F2 = 1, because F2 = F1 + F0 = 1 + 0. Then, F3 = 2, because F3 = F2 + F1 = 1 + 1. The sequence continues on infinitely: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34… You can read more about Fibonacci numbers <a href="https://mathworld.wolfram.com/FibonacciNumber.html">here</a>.</p><p>Let’s look at a few examples of the expected output of the staircase problem. We can start with n = 0. That means the staircase has 0 steps. There’s 0 ways to climb this staircase, so when n = 0, the output = 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*W2es2UYRPflEDmOeqUKRKg.png" /><figcaption>n = 0; 0 ways to climb the staircase; output = 0</figcaption></figure><p>When n = 1, the staircase has 1 step. There’s 1 way to climb this staircase, so when n = 1, the output = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*izFcfj7gLaZ_1_DEbU9ZaA.png" /><figcaption>n = 1; one way to climb the staircase; output = 1</figcaption></figure><p>When n = 2, the staircase has 2 steps. Since we can either climb 1 or 2 stairs at a time, there’s 2 ways to climb this staircase. So, when n = 2, the output = 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*K3dSwdAvJvMTr1QYCvrE_g.png" /><figcaption>n = 2; two different ways to climb the staircase; output = 2</figcaption></figure><p>When n = 3, the staircase has 3 steps. There are 3 ways we can climb this staircase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*iv2SwjnWynKYoBcM-PP0xw.png" /><figcaption>n = 3; three different ways to climb the staircase; output = 3</figcaption></figure><p>We can keep doing this for when n = 4 (output = 5)…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6pr-yYaTCwZ687hIJdGeA.png" /><figcaption>n = 4; five different ways to climb the staircase; output = 5</figcaption></figure><p>… and n = 5 (output = 8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQeaI0SG7NuufIDqiNI48A.png" /><figcaption>n = 4; eight different ways to climb the staircase; output = 8</figcaption></figure><p>Notice any pattern in the output?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*1qPQaUlp4Xk3Ppieyy9Qww.png" /><figcaption>When n = 0, output = 0; n = 1, output = 1; n = 2, output = 2; n = 3, output = 3; n = 4, output = 5; n = 5, output = 8</figcaption></figure><p>We can see the Fibonacci sequence in our outputs! Each time we increment n, the number of ways to climb the staircase is the sum of the previous two ways. That means that we can solve the staircase problem by solving for the Fibonacci number at each stair, until we get to n.</p><h3>Solving the algorithm</h3><p>Now that we’ve recognized the pattern in the output, we can go ahead and solve the algorithm. To start, we need to write out a few base cases. When n is 0, 1, and 2, the number of ways to climb the stairs 0, 1, and 2 (in that order) — so if n is one of those numbers, we can just return n.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48273158010f5e4e9d41fd1b27a4d63e/href">https://medium.com/media/48273158010f5e4e9d41fd1b27a4d63e/href</a></iframe><p>We need to initialize two constants, one called first and one called second. We&#39;ll start by setting first equal to 1, and second equal to 2. We&#39;ll be using these numbers to add up to the current number we&#39;re on, and will continue to change them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82700b7d74f7d031e287d5924a3b6415/href">https://medium.com/media/82700b7d74f7d031e287d5924a3b6415/href</a></iframe><p>Now, starting at the number 2, and going until we reach n, we can have a for loop incrementing one number at a time. Inside the for loop, we’ll initiate a new variable called current which will store the sum of first and second. Then, we can move first over to equal second, and second to equal current.</p><p>Once the for loop ends, we’ll want to return whatever the second number is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29f72d0c362ad6b5b3815618114f340d/href">https://medium.com/media/29f72d0c362ad6b5b3815618114f340d/href</a></iframe><p>Let me know in the comments if you have any questions or ideas for other ways to solve this!</p><p><strong>Resources</strong>:</p><ul><li><a href="https://leetcode.com/problems/climbing-stairs/">https://leetcode.com/problems/climbing-stairs/</a></li><li><a href="https://mathworld.wolfram.com/FibonacciNumber.html">https://mathworld.wolfram.com/FibonacciNumber.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e412cf761636" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/solving-the-climbing-staircase-problem-e412cf761636">Solving the Climbing Staircase Problem</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Happy Number Algorithm]]></title>
            <link>https://medium.com/@alisabajramovic/solving-the-happy-number-algorithm-334afa34599?source=rss-83fb45c2f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/334afa34599</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alisa Bajramovic]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 15:44:28 GMT</pubDate>
            <atom:updated>2020-07-09T15:44:28.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using recursion to separate, square, and sum the digits of a number</h4><p>One of the most optimistic-sounding Leetcode algorithms is the Happy Number <a href="https://leetcode.com/problems/happy-number/">problem</a>:</p><blockquote>Write an algorithm to determine if a number n is &quot;happy&quot;.</blockquote><blockquote>A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1. Those numbers for which this process <strong>ends in 1</strong> are happy numbers.</blockquote><blockquote>Return True if n is a happy number, and False if not.</blockquote><p>For example, let’s say your input was 19. The expected output would be true. 19, when broken down into its digits, is 1 and 9. Those numbers squared are 1 and 81. 1 + 81 is 82. 82 broken into its digits is 8 and 2. Those numbers squared are 64 and 4, and 64 + 4 = 68. 68 broken down into its digits is 6 and 8. Those numbers squared is 36 and 64. 36 + 64 = 100. 100 broken down into its digits is 1, 0, and 0. Those numbers squared and summed is 1, which makes it a happy number.</p><p>There are a number of ways to approach this problem, and in this piece I’ll be walking through how to use recursion to solve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l8qYZdHR9wTaFsnE" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Halacious</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The first thing we’ll do is initialize a variable called sum. The digits of a number will be broken up, set to the power of two, and then added, so it’s important to keep track of what the sum is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06814953262ec0f21bed12fba279c694/href">https://medium.com/media/06814953262ec0f21bed12fba279c694/href</a></iframe><p>Then, we’ll want to break up the number using modulo. When asked to manipulate a number, it’s best to do so without changing it to a string or integer. Modulo enables you do to this easily. If you’re given n = 25, then n % 10 would give you the result of 5, because the remainder of doing 25 / 10 is 5. We can then set n equal to n / 10 (and then round down), which gives us that n = 20. We’ll then want to repeat the process of performing modulo on n and dividing n by 10, and to do this as long as n is greater than 0. Every time we break down the digits, we’ll want to take the result of the modulo, square that number, and add it to the sum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/328a8620f2baf67417456647f77d6caa/href">https://medium.com/media/328a8620f2baf67417456647f77d6caa/href</a></iframe><p>Now, we need to check what sum is. If sum is equal to 1, then it’s a happy number, and we can return true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9419498db6e9d94cefa2c562cd689940/href">https://medium.com/media/9419498db6e9d94cefa2c562cd689940/href</a></iframe><p>If the sum is greater than 1 but less than or equal to 4, then we know the sum will get stuck in an infinite loop and will never equal 1, so it’s definitely not a happy number.</p><p>You can test this out yourself: if the number is 2, then 2² is 4. 4² is 16. 1² + 6² = 37. 3² + 7² = 58. 5² + 8² = 89. 8² + 9² = 145. 1² + 4² + 5² = 42. 4² + 2² = 20. 2² + 0² = 4 — and we’re stuck in the same loop. (You can also try this out for 3). Therefore, if sum is greater than 1 and less than or equal to 4, then we can return false.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5b29c7b10f900bdbee0dba5e8445070/href">https://medium.com/media/e5b29c7b10f900bdbee0dba5e8445070/href</a></iframe><p>The final thing to do is make a recursive call to the function. If the sum does not fulfill one of the base cases — it’s not equal to 1, 2, 3, or 4 — then its digits need to be split, squared, and summed, therefore calling the function again. Therefore, we need to call the function, this time with sum as the argument. It’s also important to write return before the function call, or else you’ll end up with a result of undefined, since nothing was returned back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09bc76dd91b9e9600a4c6253f61167f8/href">https://medium.com/media/09bc76dd91b9e9600a4c6253f61167f8/href</a></iframe><p>Let me know in the comments if you have any questions or alternate solutions for how to approach this problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=334afa34599" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>