<?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 Kimberly Love on Medium]]></title>
        <description><![CDATA[Stories by Kimberly Love on Medium]]></description>
        <link>https://medium.com/@kimberlymlove15?source=rss-70915dd6fdf6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zgrc1l7SYfCozUBE</url>
            <title>Stories by Kimberly Love on Medium</title>
            <link>https://medium.com/@kimberlymlove15?source=rss-70915dd6fdf6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:23:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kimberlymlove15/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[SQLAlchemy Relationship Status: It’s Complicated — Backref vs. Back_populates]]></title>
            <link>https://medium.com/@kimberlymlove15/sqlalchemy-relationship-status-its-complicated-backref-vs-back-populates-9eaf07335a13?source=rss-70915dd6fdf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eaf07335a13</guid>
            <category><![CDATA[object-relationships]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[object-relational-mapping]]></category>
            <category><![CDATA[flask-sqlalchemy]]></category>
            <category><![CDATA[relational-databases]]></category>
            <dc:creator><![CDATA[Kimberly Love]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 22:17:36 GMT</pubDate>
            <atom:updated>2023-10-13T22:17:36.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQLAlchemy Relationship Status: It’s Complicated — Backref vs. Back_populates</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*JGmWuZQn8JctfqOf.png" /><figcaption>[3] Python, ORM, Database Diagram</figcaption></figure><p>As a new programmer, the use of libraries can be intimidating, and when it comes to managing databases in your Python projects, the SQLAlchemy library might initially seem like a formidable beast to tame. SQLAlchemy, however, is here to simplify the process with its Object-Relational Mapping (ORM) capabilities. It allows us to seamlessly connect our Python classes to relational databases without the need to write SQL statements manually. Instead, we can harness the power of Python to create and execute these queries.</p><p>But that’s just the tip of the iceberg when it comes to what SQLAlchemy can do for us. Among its many features, one particularly essential aspect is the ability to establish relationships between different models. Models can be linked in various ways, including One-to-One, Many-to-Many, and the focus of this blog post: One-to-Many relationships.</p><p>In this blog post we’ll dive deeper into the intricacies of One-to-Many relationships, shedding light on how they function within the SQLAlchemy framework. The examples in this blog will be written using Flask-SQLAlchemy, a combination that simplifies web development and database management in Python.</p><h3>Relationship Class</h3><p>The SQLAlchemy method relationship() method creates an instance of Relationship that can be used to access the related items. Lets take a look at the One-to-Many example below, given the relationship a Parent has many children and a Child belongs to a Parent:</p><pre>from flask_sqlalchemy import SQLAlchemy<br>db = SQLAlchemy()<br><br>class Parent(db.Model):<br>  __tablename__ = &quot;parents&quot;<br><br>  id = db.Column(db.Integer, primary_key=True)<br>  name = db.Column(db.String)<br><br>  children = db.relationship(&quot;Child&quot;)<br><br>class Child(db.Model):<br>  __tablename__ = &quot;children&quot;<br>  <br>  id = db.Column(db.Integer, primary_key=True)<br>  name = db.Column(db.String)<br>  parent_id = db.Column(db.Integer, db.ForeignKey(&quot;parents.id&quot;))<br>  <br>  parent = db.relationship(&quot;Parent&quot;)</pre><p>The relationship method takes multiple paramenters, the first being the class you want to establish a relationship with written as a string. The relationship method can take many other optional paramenters (i.e. cascade, lazy, overlaps..), but the main one we’ll be focusing on is backref and back_populates. Looking at what they do, why we need them, and figuring out which one we should use now.</p><h3>Do we really need backref or back_populates?</h3><p>That’s a great question! If we look at the example above, we don’t use either, so we just establish the relationship with the related class and that’s it. So what happens if we just do this:</p><pre>nicole = Parent(name = &quot;Nicole&quot;)<br>elijah = Child(name = &quot;Elijah&quot;)<br><br>print(nicole.children)<br># LOG: []<br>print(elijah.parent)<br># LOG: None<br><br>elijah.parent = nicole<br>print(elijah.parent)<br># LOG: &lt;Parent: Nicole&gt;<br><br>print(nicole.children)<br># LOG: []</pre><p>So we still can create the relationship using just the class name, but if you create a child object, elijah, and assign it a parent object, nicole, the parent object doesn’t recognize the child object as it’s child. So how do we fix that?</p><h3>What does backref and back_populates do?</h3><p>So this is where the backref and back_populates attributes shine. Using these creates a bidirectional relationship that will automatically allow SQLAlchemy to recognize that there is a connection between two instances. Lets take a closer look at how backref and back_populates work.</p><blockquote><strong>backref</strong></blockquote><p>With backref you only need to declare the relationship in one class, usually the parent class but you can put the relationship in either class. In the child class you only need to have a foreign key:</p><pre>from flask_sqlalchemy import SQLAlchemy<br>db = SQLAlchemy()<br><br>class Parent(db.Model):<br>  __tablename__ = &quot;parents&quot;<br><br>  id = db.Column(db.Integer, primary_key=True)<br>  name = db.Column(db.String)<br><br>  # Relationship with backref<br>  children = db.relationship(&quot;Child&quot;, backref=&quot;parent&quot;) <br><br>class Child(db.Model):<br>  __tablename__ = &quot;children&quot;<br>  <br>  id = db.Column(db.Integer, primary_key=True)<br>  name = db.Column(db.String)<br><br>  # Foreign Key<br>  parent_id = db.Column(db.Integer, db.ForeignKey(&quot;parents.id&quot;))<br>  <br><br>nicole = Parent(name = &quot;Nicole&quot;)<br>elijah = Child(name = &quot;Elijah&quot;)<br><br>print(nicole.children)<br># LOG: []<br>print(elijah.parent)<br># LOG: None<br><br>elijah.parent = nicole<br>print(elijah.parent)<br># LOG: &lt;Parent: Nicole&gt;<br><br>print(nicole.children)<br># LOG: [&lt;Parent: Elijah&gt;]</pre><p>backref automatically creates a .parent relationship on the child class.</p><blockquote><strong>back_populates</strong></blockquote><p>When using back_populates you must explicitly create the relationship in both the parent and child classes:</p><pre>from flask_sqlalchemy import SQLAlchemy<br>db = SQLAlchemy()<br><br>class Parent(db.Model):<br>  __tablename__ = &quot;parents&quot;<br><br>  id = db.Column(db.Integer, primary_key=True)<br>  name = db.Column(db.String)<br><br>  # Relationship with back_populates<br>  children = db.relationship(&quot;Child&quot;, back_populates=&quot;parent&quot;) <br><br>class Child(db.Model):<br>  __tablename__ = &quot;children&quot;<br>  <br>  id = db.Column(db.Integer, primary_key=True)<br>  name = db.Column(db.String)<br>  parent_id = db.Column(db.Integer, db.ForeignKey(&quot;parents.id&quot;))<br><br>  # Relationship with back_populates<br>  parent = db.relationship(&quot;Child&quot;, back_populates=&quot;children&quot;)<br><br>nicole = Parent(name = &quot;Nicole&quot;)<br>elijah = Child(name = &quot;Elijah&quot;)<br><br>print(nicole.children)<br># LOG: []<br>print(elijah.parent)<br># LOG: None<br><br>nicole.children.append(elijah)<br><br>print(nicole.children)<br># LOG: [&lt;Parent: Elijah&gt;]<br><br>print(elijah.parent)<br># LOG: &lt;Parent: Nicole&gt;<br></pre><p>So, with either backref or back_populates, if you assign some children to a parent, the children will be able to recognize the parent. And if you assign a parent to a child, the parent will be able to recognize the child.</p><h3>Which one should we use?</h3><p>If both backref and back_populates perform the same essential task without any significant execution advantage of one over the other, the question arises: which one should we use? The answer to this lies in the current best practices and the quest for clarity and transparency in our code.</p><p>In current SQLAlchemy usage, it is recommended to favor back_populates. The reason behind this recommendation is because back_populates offers a more explicit approach to defining and visualizing the relationships between classes. By explicitly specifying the relationship within the classes, it becomes very clear and easy to recognize these connections.</p><p>On the other hand, with backref, you may find yourself looking through other classes that rely on backref to establish their connections. This can make comprehending the entirety of relationships a more complex process, as there isn’t a dedicated relationship method within each class for quick reference.</p><h3>References</h3><p>[1] A. Zhou, “Concept FAQs,” Concept FAQs — Intro to Backend Development, <a href="https://backend-course.cornellappdev.com/cheat-sheets/concept-faqs">https://backend-course.cornellappdev.com/cheat-sheets/concept-faqs</a> (accessed Oct. 13, 2023).</p><p>[2] BoopityBoppityBoopityBoppity 95922 gold badges99 silver badges1111 bronze badges, eRunnereRunner 1, and u2gillesu2gilles 6, “Concepts of backref and back_populate in sqlalchemy?,” Stack Overflow, <a href="https://stackoverflow.com/questions/51335298/concepts-of-backref-and-back-populate-in-sqlalchemy">https://stackoverflow.com/questions/51335298/concepts-of-backref-and-back-populate-in-sqlalchemy</a> (accessed Oct. 13, 2023).</p><p>[3] “Optimizing Database Interactions in python: Sqlalchemy best practices,” Soshace, <a href="https://soshace.com/optimizing-database-interactions-in-python-sqlalchemy-best-practices/">https://soshace.com/optimizing-database-interactions-in-python-sqlalchemy-best-practices/</a> (accessed Oct. 13, 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eaf07335a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda Me This…]]></title>
            <link>https://medium.com/@kimberlymlove15/lambda-me-this-270807e841f8?source=rss-70915dd6fdf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/270807e841f8</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[python-functions]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kimberly Love]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 21:51:41 GMT</pubDate>
            <atom:updated>2023-09-25T14:08:14.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*58IXFkGTS2WZK_XIjeR7pg.png" /></figure><p>If you’re new to programming like me you’ll probably find that as you continue to dive deeper into any language and look at Stack Overflow and other resources to try to help you solve problems, you discover new code that you’ve never seen before. During my journey to learn python I stumbled across something called lambda. Your first thought when you see the world lambda may take you down a rabbit hole of Greek mythology, or pull you over into the physics world. But when it comes to python, lambda is actually a shorthand tool we can use to write functions. Let’s big a little deeper into understanding how lambda works in the python world.</p><h3>What is a lambda function?</h3><p>In python we traditionally define a function by first using the <em>def</em> keyword, followed by the name of the function, then the paramenter for the function in parenthesis, a colon, and finally the body of the function indented in on the next lines down:</p><pre>def sum(a, b):<br>  return a + b<br><br>print(sum(3,5))<br>#LOG: 8</pre><p>However, for very simple functions, like the one above, this can be a lot of extra code. Thankfully python gives us an alternative way to write functions using lambda. <strong>Lambda functions </strong>are anonymous functions that provide a shorthand syntax for creating functions in python.</p><h3>Lets Write Lambda Functions</h3><p>The syntax for a lambda function is the <em>lambda </em>keyword, followed by the the arguments, a colon, and finally an expression:</p><pre># Syntax: lambda arguments : expression<br><br>lambda x : x * 2</pre><p>There&#39;s a few things to note about lambda functions:</p><ol><li>These functions can take any number of arguments</li><li>They can only have <strong>ONE </strong>expression, which is evaluated and returned</li></ol><h3>Invoking Anonymous Functions</h3><p>As we mentioned earlier, lambda functions are anonymous functions, which means they don’t have a name associated with them. And without a name, we can’t invoke a function. So what do we do? One thing you can do is assign a lambda funciton to a variable.</p><blockquote>Assigning Lambda Functions to Variables</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Yu74Qc4mxXMh9ZN3Yic0gA.png" /><figcaption>[2] Image by the Author Dorfer.</figcaption></figure><p>Lets take a look a assigning a lambda to an variable, reusing our lambda syntax and sum function examples from earlier:</p><pre>multiply = lambda x : x * 2<br>sum = lambda a, b : a + b<br><br>print(multiply(5))<br>#LOG: 10<br><br>print(sum(3,5))<br>#LOG: 8<br></pre><p>If we take a look at the multiply funciton, we are able to invoke the lambda function using the tradition method of invoke a function (parenthesis ()) and passing a single argument to the variable name it was assigned to. If we look at the sum function, we are able to pass multiple paramenters to a lambda function. This same function that took us two lines using the traditional python function declaration method only took us one line using a lambda function.</p><h3>Other Uses for Lambda Functions</h3><blockquote>Lambda and Callback Functions</blockquote><p>Callbacks functions are functions that are passed as arguments to other functions or invoked within another function. And a lot of the time callback functions are anonymous functions. You can pass a lambda function as a callback to another function. The lambda function can be defined inline as well. Lets take a look at these examples below:</p><h4>Map() and Filter()</h4><p>The map and filter functions in python take two arguments, a function an iterable. The function passed to map and filter is run on every element in the iterable and is passed the current element as an argument. In other words, the map and filter functions call the passed in function on each element and passes the element as an argument, making the passed in function a callback function. They both return a filter or array object that you can iterate over. The objects will contain the modified elements based on the conditions in the callback function. That callback function used in map and filter can be a lambda function.</p><pre># map(func, iterable)<br># filter(func, interable)<br><br>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br><br>double_nums = map(lambda num: num*2, numbers)<br>print(list(double_nums))<br># LOG: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]<br><br>is_even = filter(lambda num: num % 2 == 0, numbers)<br>print(list(is_even))<br># LOG: [2, 4, 6, 8, 10]</pre><p>Here we pass an anonymous, inline lambda function as the first parameter to the map and filter functions. The second paramenter is the iterable which is the list numbers. Map and filter pass each element of the iterable to the callback as an argument. The map function uses the lambda callback function to double each element in the list. The filter function uses the lambda callback function to check to see if a number is even or not.</p><h4>Sorted()</h4><p>The sorted function by default sorts an iterable alphabetically.</p><pre>cars = [&quot;Ford&quot;, &quot;Honda&quot;, &quot;BMW&quot;, &quot;Mercedes&quot;, &quot;VW&quot;]<br><br>x = sorted(cars)<br><br>print(x)<br>#LOG: [&#39;BMW&#39;, &#39;Ford&#39;, &#39;Honda&#39;, &#39;Mercedes&#39;, &#39;VW&#39;]</pre><p>However, sorted takes an optional second argument, <em>key</em>, which is set equal to a function to execute to decide what to sort by. This key argument can be set equal to a lambda function:</p><pre>cars = [&quot;Ford&quot;, &quot;Honda&quot;, &quot;BMW&quot;, &quot;Mercedes&quot;, &quot;VW&quot;]<br><br>x = sorted(cars, key = lambda x : len(x))<br><br>print(x)<br>#LOG: [&#39;VW&#39;, &#39;BMW&#39;, &#39;Ford&#39;, &#39;Honda&#39;, &#39;Mercedes&#39;]</pre><p>Here we set key equal to an anonymous inline lambda function to gets the length of each element in the list. The sort function uses the lambda callback function to sort the list by length.</p><blockquote>Lambda and if-else</blockquote><p>We can use lambda functions with ternary expressions to create simple if-else functions:</p><pre>max_num = lambda a, b : a if a &gt; b else b<br><br>print(max_num(3,5))<br>#LOG: 5</pre><p>We can use a ternary expression to compare the arguments passed to the lambda function and return whichever number is bigger.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*xXv8T2poXxMmNzbTqaQDIw.png" /><figcaption>Figure 1: Python Lambda Functions [1]</figcaption></figure><p>Lambda functions are a great tool in python when you need to write a simple, single line functions usually involving short operations. They can be easily passed as callback functions and defined inline so that you don’t have to clog the global scope with a function that only needs to be used once. However if you need to write a multi-line function or need to explain parts of you function, you should probably us the standard python function definition.</p><blockquote>Aside: Do lambda functions remind you of anything? If you’ve dabbled at all in JavaScript, you may be familiar with arrow functions. Arrow functions are by definition anonymous functions and can be assigned to a variable as well. They are also often passed as callbacks and used in other similar situations as lambda functions. And if you look at the syntax of a python lambda function vs a JavaScript arrow function, you might see some similarities there are well!</blockquote><h3>Reference List</h3><p>[1] “Python lambda functions,” GeeksforGeeks, <a href="https://www.geeksforgeeks.org/python-lambda-anonymous-functions-filter-map-reduce/">https://www.geeksforgeeks.org/python-lambda-anonymous-functions-filter-map-reduce/</a> (accessed Sep. 21, 2023).</p><p>[2] T. A. Dorfer, “How to effectively use lambda functions in python as a data scientist,” Medium, <a href="https://towardsdatascience.com/how-to-effectively-use-lambda-functions-in-python-as-a-data-scientist-fd6171554053">https://towardsdatascience.com/how-to-effectively-use-lambda-functions-in-python-as-a-data-scientist-fd6171554053</a> (accessed Sep. 21, 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270807e841f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Destructuring Destructured]]></title>
            <link>https://medium.com/@kimberlymlove15/destructuring-destructured-bc724e9a7c6?source=rss-70915dd6fdf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc724e9a7c6</guid>
            <category><![CDATA[array-destructuring]]></category>
            <category><![CDATA[object-destructuring]]></category>
            <category><![CDATA[destructuring]]></category>
            <category><![CDATA[usestate-in-react]]></category>
            <category><![CDATA[props-in-react]]></category>
            <dc:creator><![CDATA[Kimberly Love]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 03:58:05 GMT</pubDate>
            <atom:updated>2023-09-06T03:58:05.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*NVF8x6T_t9939oZUI4oswQ.jpeg" /><figcaption>Figure 1: Patrick Destructuring Meme [2]</figcaption></figure><p>When you see a word like destructuring it can be very intimidating, especially when you’re first starting out in the coding world. However, once you get the hang of this JavaScript shorthand it can save you many lines of code. In this blog we will break down object destructuring and array destructuring to turn this seemingly scary method into a very useful one.</p><h3>What Is Destructuring?</h3><p>That’s a great question! According to MDN [1]:</p><blockquote>“The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.”</blockquote><p>So what exactly does all that mean? JavaScript gives us a shorthand to either assign the values of a key/value pair in an object to a variable or extract the elements out of an array and assign them to variables. Okay this still sounds confusing so lets see object and array destructuring in action and break this down a little further with some examples.</p><h3>Object Destructuring</h3><p>Lets take a look a the following object:</p><pre>const cat = {<br>  name: &quot;Oliver&quot;,<br>  age: 6,<br>  color: &quot;Orange&quot;,<br> }</pre><p>If we wanted to access the values at each key in this object and assign the value to a variable, I would have to use dot notation and type either <em>cat.name</em>, <em>cat.age</em> or <em>cat.color</em> to get the it.</p><pre>// Vanilla JS imperative variable assignment<br>const name = cat.name<br>const age= cat.age<br>const color= cat.color</pre><p>With a small object like this that may not seem too bad, but imagine if your object had 15 or 20 keys? That’s a lot of times to write <em>cat.</em> and we want to keep our code as dry as possible.</p><p>So JavaScript gives us a way to extract those values out of the object using object destructuring. The syntax for object destructuring is first using a variable declaration (let or const), followed by curly braces {}. Inside those curly braces are the key/variable names. Then you set the curly braces equal to an object that contains those key name.</p><pre>//Object Destructuring shorthand<br><br>variable declaration<br> vv<br>const { name, age, color } = cat<br>             ^^^             ^^<br>      variable/key names    object name<br><br><br>console.log(name) // Log: &quot;Oliver&quot;<br>console.log(age) // Log: 6<br>console.log(color) // Log: &quot;Orange&quot;</pre><p>With this syntax, the variables named inside the curly braces are expected to be the names of keys inside the object it is set equal to. If that key exists inside the object, then the value at that key is assigned to the corresponding variable. This way we don’t have to write <em>cat. </em>over and over again. We can extract all the values out of the object with one line of code, instead of three lines like we had to use in the vanilla JS imperative example.</p><h3>Array Destructuring</h3><p>Now that we have a better understanding object destructuring, lets talk about array destructuring. This is a very similar concept with a similar syntax, expect we’re working with arrays. While objects will match up with their keys, arrays will match up with their indexes. Lets take a look at the following array:</p><pre>const cat = [&quot;Oliver&quot;, 6, &quot;Orange&quot;]</pre><p>We can extract the elements out of the cat array using array destructuring and assign them to variables. The syntax for array destructuring is first using a variable declaration (let or const), followed by square brackets []. Inside those square brackets are the variable names you want to assign to each element of the array. Then you set the square brackets equal to an array of the same length. The variable name at index [0] will be assigned the value of the element at index [0] in the cat array. The variable name at index [1] will be assigned the value of the element at index [1] in the cat array and so on.</p><pre>const [name, age, color] = cat<br><br>console.log(name) // Log: &quot;Oliver&quot;<br>console.log(age) // Log: 6<br>console.log(color) // Log: &quot;Orange&quot;</pre><h3>Uses In The Real World — React</h3><p>Now that we understand how object and array destructuring works, when do we actually use it? If you’ve ever used React, a front-end JavaScript library, then you are already probably familiar with these two concepts.</p><blockquote>Prop Destructuring</blockquote><p>In React we pass props down to child components from parent components.</p><pre>function ParentComponent(){<br>  return &lt;ChildComponent name=&quot;Oliver&quot; age={9} color=&quot;Orange&quot;/&gt;<br>}</pre><p>Props are key/value pairs that are bundled up into an object that is passed as an argument to the child functional component.</p><pre>function ChildComponent(props){<br>  console.log(props) // LOG: {name: &quot;Oliver&quot;, age: 9, color: &quot;Orange&quot;}<br>  <br>  return &lt;h1&gt;Child Component&lt;/h1&gt;<br>}</pre><p>As we can see in the example above, the props argument is an object, which means we can do object destructuring to extract out all the values in the object. That way we don’t have to write <em>props.something</em> over and over again:</p><pre>function ChildComponent(props){<br>  const {name, age, color} = props<br><br>  console.log(name) // Log: &quot;Oliver&quot;<br>  console.log(age) // Log: 6<br>  console.log(color) // Log: &quot;Orange&quot;<br><br>  return &lt;h1&gt;Child Component&lt;/h1&gt;<br>}</pre><p>This works because the props object has keys of name, age and color. React also allows us to take this one step further and deconstruct the props object right in the parenthesis of the argument:</p><pre>function ChildComponent({name, age, color}){<br><br>  console.log(name) // Log: &quot;Oliver&quot;<br>  console.log(age) // Log: 6<br>  console.log(color) // Log: &quot;Orange&quot;<br><br>  return &lt;h1&gt;Child Component&lt;/h1&gt;<br>}</pre><blockquote>useState Hook</blockquote><p>React has many hooks. Hooks are a special type of function in React that allows us to “hook” into Reacts internal state. One hook that is used quite often is the useState hook to control and update dynamic data.</p><p>The useState hook takes an initial value as an argument and returns an array of two elements: (1) the first element being a state variable set to the initial value and (2) the second element being a setter function:</p><pre>// useState(initialValue) =&gt; [state, setterFunction]<br><br>useState(1) // =&gt; [1, f()]</pre><p>We can go the log route of assigning the return of useState to variables:</p><pre>const start = useState(true)  <br>const isOn = start[0]<br>const setIsOn = start[1]<br>  <br>console.log(start) // LOG: [true, f()]<br>console.log(isON) // LOG: true<br>console.log(setIsOn) // LOG: f()</pre><p>But since useState returns an array, we can save ourselves all those extra lines of code and use array destructuring to set the state and anonymous setter function to variables:</p><pre>const [isOn, setIsOn] = useState(true)<br><br>console.log(isOn) // LOG: true<br>console.log(setIsOn) // LOG: f()</pre><h3>Conclusion</h3><p>Destructuring, even though it has a scary name it is not very scary once you get the hang of it. It’s actually very helpful! Array and object destructuring can save you from writing a lot of unnecessary code, keeping our code dry and saving use time overall!</p><h3>Reference List</h3><p>[1] MDN Contributors, “Destructuring assignment — JavaScript | MDN,” <em>developer.mozilla.org</em>. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment</a> (accessed Sept. 5, 2023).</p><p>[2] <em>Velog.io</em>, 2023. <a href="https://images.velog.io/images/jangws/post/12a41869-6471-4463-be8f-c060029a12e5/5xvvb0.jpg">https://images.velog.io/images/jangws/post/12a41869-6471-4463-be8f-c060029a12e5/5xvvb0.jpg</a> (accessed Sep. 06, 2023).</p><p>‌</p><p>‌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc724e9a7c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Definitions and When to Use Then]]></title>
            <link>https://medium.com/@kimberlymlove15/function-definitions-3a06993f4ae7?source=rss-70915dd6fdf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a06993f4ae7</guid>
            <category><![CDATA[anonymous-function]]></category>
            <category><![CDATA[function-declaration]]></category>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[function-definition]]></category>
            <dc:creator><![CDATA[Kimberly Love]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 21:44:37 GMT</pubDate>
            <atom:updated>2023-08-10T21:53:43.255Z</atom:updated>
            <content:encoded><![CDATA[<p>As a beginning developer, you might struggle with when to use a function declaration versus an anonymous function versus an arrow function versus a function expression. They all seem to do the same thing right? Being a beginner developer myself, this is a concept I’ve been struggling to grasp. In this blog, we will explore the similarities and differences between these types of functions and see if there really is a better time to use one over the other.</p><h3><strong>What is a Function?</strong></h3><p>Let’s start with a simple question, what is a function? According to MDN [1]:</p><p><em>“Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure — a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.”</em></p><p>The technical definition can be a little intimidating, so I like to think of a function as a reusable block of code. This block of code is saved and can be “called” or “invoked” at a later point in time (sometimes….).</p><h3><strong>The Different Ways to Define a Function</strong></h3><p>Okay let’s talk about these different types of functions:</p><blockquote>Function declaration:</blockquote><p>A function declaration requires the use of the <strong>function </strong>keyword. Afterwards, you write the name of the function, followed by a parenthesis () where you can include parameters if needed, and lastly, the curly braces {} where you put the code you want to execute when the function is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mx_0RhKgrWxMM_DZS7Dz2Q.png" /><figcaption><strong>Figure 1: <em>Function Declaration Breakdown [2]</em></strong></figcaption></figure><pre>function sayHi(name) {<br>  console.log(&quot;Hi &quot; + name);<br>}<br>sayHi(&quot;Kim&quot;);<br> <br>LOG: &quot;Hi Kim&quot;</pre><blockquote>Anonymous function:</blockquote><p>Anonymous functions are very similar to function declarations expect they do not have a name, hence anonymous. However, without a name, you cannot invoke an anonymous function.</p><pre>function () {<br> console.log(&quot;Hi world!&quot;);<br>}</pre><blockquote>Function Expression:</blockquote><p>A function expression is an anonymous function that is assigned to a variable name. Creating a function expression is one method that allows us to have access to and invoke an anonymous function.</p><pre>const sum = function(a, b) {return a + b}<br>sum(2,4); =&gt; 6</pre><blockquote>Arrow Function:</blockquote><p>Arrow functions allow for a kind of shorthand to create functions involving, you guessed it, an arrow =&gt;.</p><pre>const difference = (a, b) =&gt; a - b;<br>difference(7, 3); =&gt; 4<br> <br>const squared = a =&gt; a**2;<br>squared(4); =&gt; 16</pre><h3><strong>Let’s Compare</strong></h3><p>Alright now let’s compare these definitions! There’s one very big advantage to using function declarations as compared to the others and that is that function declarations are <strong>hoisted</strong>, while the others are not. This means that you can invoke a function that has been defined using function declaration earlier in your code before the function is actually defined.</p><pre>helloWorld();<br><br>// Random lines of code<br>// Random lines of code<br><br>function helloWorld() {<br>  console.log(&quot;Hello World!&quot;);<br>}<br> <br> LOG: &quot;Hello World!&quot;</pre><p>You can see in the sample of code above that helloWorld() will still console log out, even though it is in front of the actual function definition in the code.</p><p>Now, function declarations seem to have the upper hand right now with hoisting, so when might we use the others? Especially anonymous functions since they must be assigned to a variable to use them. Well, actually that’s not the only way they can be invoked, you may see an anonymous function used as a callback function. Anonymous functions are useful when you don’t want to crowd the global scope and only want to invoke a function once for a certain task.</p><p><strong><em>Note</em></strong><em>: If you don’t assign an arrow function to a variable, it is also technically an anonymous function because it has no name. Anonymous arrow functions are often passed as callbacks in other functions as well.</em></p><p>Let’s compare function declarations and arrow functions. Arrow functions create a shorthand and eliminate the function keyword all together. You also do not need to include parenthesis around the parameter if there is only one parameter. Lastly, arrow functions allow you to do both implicit and explicit returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*H7EyIVvUFLikBPK2jjL4Tw.png" /><figcaption>Created By: Kim Love</figcaption></figure><h3>Conclusion</h3><p>After all this, which function is the best one to use? What we have learned is that there are several ways to declare functions and pros and cons to each way. So, there is no one best function definition to use, it depends on the situation and how you want that function to be used. If you need to reuse a block of code quite a bit throughout your program, and want to take advantage of hoisting, using a function declaration in the global scope might be best. If you want to write a shorthand function and use implicit return, then an arrow function would work great. Or if you only want to call a function one time throughout your program, using an anonymous function (or anonymous arrow function) would get the job done and not pollute the global scope.</p><p>In the end just think about how you want your function to be used throughout your program and that’ll help you decide which function definition to use!</p><h3><strong>Reference List</strong></h3><p>[1] MDN Contributors, “Functions — javascript: MDN,” JavaScript | MDN, <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> (accessed Aug. 10, 2023).</p><p>[2] Functions, <a href="https://fireship.io/courses/javascript/beginner-js-functions/">https://fireship.io/courses/javascript/beginner-js-functions/</a> (accessed Aug. 10, 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a06993f4ae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>