<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ programming languages - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ programming languages - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 05 Jun 2026 20:27:24 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/programming-languages/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Choose the Best Programming Languages, Libraries, and Patterns ]]>
                </title>
                <description>
                    <![CDATA[ In my first few years learning software development and building applications, I was quite interested in finding the best programming language, platform, libraries, frameworks, patterns, and architectures available. I thought that by finding the best... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-choose-the-best-programming-languages-libraries-and-patterns/</link>
                <guid isPermaLink="false">6898d3414c52a26ffefb1693</guid>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ryan Michael Kay ]]>
                </dc:creator>
                <pubDate>Sun, 10 Aug 2025 17:13:37 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754846007203/c9db729e-ebed-4726-8e3e-5414c8e2714d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In my first few years learning software development and building applications, I was quite interested in finding the best programming language, platform, libraries, frameworks, patterns, and architectures available. I thought that by finding the <em>best</em> things and focusing on those topics to the exclusion of others, I could avoid wasting precious time.</p>
<p>While I figured out early on that narrowing my focus by using a project-based learning approach (as opposed to the topic-by-topic laundry list approach) was important, finding the best tools for the job was a different matter. </p>
<p>If you happen to be searching for some of those things, then this article is for you. After over a decade of programming products, building client applications, answering thousands of questions from junior and intermediate developers, and wrestling with these questions myself, I will do my best to explain how to find the best <em>things</em>.</p>
<p>This article is intended for junior to intermediate level developers looking to get some practical answers to difficult problems. You will not need extensive programming experience to get through it and you may skip over any technical discussions specifics. Those are meant to be helpful pieces of information, but the core of this article is about how to make these decisions in general using what I call: The Law of Suitability.</p>
<p>The topics I will cover are:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-find-the-best-anything">How to Find the Best Anything</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-find-the-best-water-bottle">How to Find the Best Water Bottle</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-find-the-best-programming-language">How to Find the Best Programming Language</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-navigating-public-and-expert-opinions">Navigating Public and Expert Opinions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-low-level-vs-high-level">Low Level vs High Level</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tightly-structured-static-vs-loosely-structured-dynamic">Tightly Structured (Static) vs Loosely Structured (Dynamic)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popularity-is-only-one-factor">Popularity Is Only One Factor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popularity-is-not-a-guarantee-of-employment">Popularity Is Not A Guarantee Of Employment</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-hardware-amp-working-with-what-you-have">Hardware &amp; Working With What You Have</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-if-i-want-the-ai-to-code-for-me">What if I Want the AI to Code For Me?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-avoid-the-sunk-cost-fallacy">Avoid the Sunk-Cost Fallacy</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-find-the-best-libraries-and-frameworks">How to Find the Best Libraries and Frameworks</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-libraries-and-frameworks">What Are Libraries and Frameworks?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-libraries-and-frameworks">How to Choose Libraries and Frameworks</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-find-the-best-programming-principles-and-practices">How to Find the Best Programming Principles and Practices</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-dry-dont-repeat-yourself">D.R.Y – Don’t Repeat Yourself</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-about-other-programming-principles">What About Other Programming Principles?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-a-note-about-patterns-and-architectures">A Note About Patterns and Architectures</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-find-the-best-software-architecture">How to Find the Best Software Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-design-pattern-trap">The Design Pattern Trap</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
<h2 id="heading-how-to-find-the-best-anything">How to Find the Best Anything</h2>
<p>I invite you to follow along with some basic non-technical examples which lay the groundwork for the rest of this article. The examples may sound silly to some, but I have layered in some conceptual patterns which you can apply to programming languages, tools, and concepts – as well as just about anything where terms like good, bad, best, or worst can apply.</p>
<h3 id="heading-how-to-find-the-best-water-bottle">How to Find the Best Water Bottle</h3>
<p>Suppose that you are looking to solve the problem of staying hydrated and wish to purchase a water bottle. </p>
<p>You consider that figuring out the best water bottle might involve looking into:</p>
<ul>
<li><p>Public opinions and reviews</p>
</li>
<li><p>Expert opinions and reviews</p>
</li>
<li><p>The manufacturer’s descriptions and reputation</p>
</li>
<li><p>Buying and testing water bottles (though preferably not all of them, as that costs too much time and money, generally)</p>
</li>
</ul>
<p>All of those things are fair for consideration. Something which is not well-tested in public presents uncertainty. Expert reviews can help inform your decision, but you have to consider the biases and motivations of such experts. You also should consider if the manufacturer has a history of quality, design, and customer support, or whether they’re simply maximizing profit.</p>
<p>After doing some research, you come up with these options:</p>
<ul>
<li><p>A plastic bottle of water from a vending machine</p>
</li>
<li><p>A high-tech metal bottle which you can even boil stuff in!</p>
</li>
<li><p>A simple but ethically sourced, refillable, BPA-free plastic water bottle</p>
</li>
</ul>
<p>However, you noticed that nobody seemed to universally agree about which option was the best. There were usually some common opinions, but it was never the case that every expert had the same evaluation or recommendation.</p>
<p>After reflecting on this, it became obvious that you need to consider how, when, and where you will be using this water bottle. In other words, you need to <strong>consider the context or situation</strong> of its usage.</p>
<p>Suppose three different contexts within which you have to make this decision:</p>
<ul>
<li><p>You are standing in a rest stop in Death Valley California (often thought to be the hottest place on Earth in summer) and there is a vending machine full of micro-plastic filled, old, generic, and cheap plastic bottles of water in front of you. But you have no other options and are very thirsty</p>
</li>
<li><p>You are in a camping store preparing for a camping trip to New Zealand with lots of hiking and not too much access to filtered water</p>
</li>
<li><p>You are looking on your favorite shopping website for something you can bring to work each day to avoid those dehydration headaches from not drinking enough water</p>
</li>
</ul>
<p>In summary, you shouldn’t ignore second-hand knowledge, expert opinions, popularity, ratings, reviews, testimonials, and even first-hand experience. But you will never find the best water bottle for every situation you find yourself in. The best “anything” depends on the problem you are trying to solve and the context (words like requirements or situation also apply here) of that problem. </p>
<p>In other words, none of these things have an absolute or fixed value – their value is always relative. I call that the <strong>Law of Suitability</strong>.</p>
<p>Let’s now discuss some examples which are directly related to software design and development. </p>
<h2 id="heading-how-to-find-the-best-programming-language">How to Find the Best Programming Language</h2>
<p>The Law of Suitability applies just as much to programming languages as it does to water bottles – even though the details and contexts are different. There is no such thing as the best programming language for every person, team, problem, or feature. </p>
<p>But I do have some specific details and contexts to offer which may help you answer that question for yourself. This section will cover concrete details and some general ideas on how to choose a programming language. These patterns also apply to frameworks, libraries, and most other aspects of programming.</p>
<p>If you are not interested in the topic of finding a programming language, feel free to skip to the next sections on topics like libraries, principles, and patterns.</p>
<h3 id="heading-navigating-public-and-expert-opinions">Navigating Public and Expert Opinions</h3>
<p>Firstly, you need to be skeptical of popularity and the opinions of experts and “influencers” here. </p>
<p>My general tip here is to be extremely cautious about anyone who makes one of these claims:</p>
<ul>
<li><p>“X” language is the best (though saying “X” language is my favourite is perfectly acceptable)</p>
</li>
<li><p>“X” language is the worst, is terrible, is dead, is garbage, is useless, and so on.</p>
</li>
</ul>
<p>There are three groups of people who generally make these sorts of statements:</p>
<ul>
<li><p>Actual experts who are voicing their personal preferences but presenting them as immutable facts (how I wish this was not so common in this industry)</p>
</li>
<li><p>Non-experts parroting opinions of the above group or who have not yet understood the Law of Suitability</p>
</li>
<li><p>Engagement farmers</p>
</li>
</ul>
<p>It’s also worth noting that people can be experts in a subset of problems but that doesn’t guarantee their opinions about all problems are expert level. </p>
<p>This doesn’t mean you should reflexively dismiss expert opinions in general. Consider both the track records of the person and the degree to which they pay attention to the context of their statement. </p>
<p>Let us look at two examples:</p>
<ul>
<li><p><em>Expert A</em> says: “Python has the best tooling, support, and ecosystem for ML development”</p>
</li>
<li><p><em>Expert B</em> says: “Python is the best programming language”</p>
</li>
</ul>
<p>While <em>Expert B</em> is obviously displaying a lack of precision (either deliberately or not) if you have followed me so far, <em>Expert A</em> is a different case. Whether or not the statements made by <em>Expert A</em> are true (for the record, I have written a bit of Python but no ML code), you can tell that they are considering details and context. Look for people like <em>Expert A</em>!</p>
<h3 id="heading-low-level-vs-high-level">Low Level vs High Level</h3>
<p>In simple terms, low level programming languages are difficult for humans to read and write. Also, they tend to be faster and have a lower memory footprint than high level languages. Conversely, high level languages are closer to human language which generally makes them easier for humans to work with.</p>
<p>I must confess, though, that I have seen plenty of examples of people writing unintelligible code in high level languages – please don’t do that.</p>
<p>Someone working on an embedded system might want to do so in a language like C or C++ to optimize performance or work around the limitations of memory and processing power.</p>
<p>But in enterprise systems, which need to run on a variety of platforms and which closely intermingle with business requirements, rules, and real world objects (thing products, users, and so on), lower level languages are not so popular. After all, upper and middle management generally tends to care about low level optimizations only to the extent it affects the user experience. </p>
<p>I love optimization in general, but never forget that everything is fast with small datasets (that is, when <em>n</em> is small) or high processing power. In simpler terms, sometimes human concerns like legibility are significantly more important than insignificant optimizations on efficiency.</p>
<h3 id="heading-tightly-structured-static-vs-loosely-structured-dynamic">Tightly Structured (Static) vs Loosely Structured (Dynamic)</h3>
<p>Ironically, the main downsides and benefits of a language like Java (which is very structured and verbose) versus a language like JavaScript (quite the opposite, depending on how you use it) are the same depending on the context. </p>
<p>Speaking of enterprise systems, using structures, types, interfaces, classes, threading, concurrency primitives, and similar programming constructs can have a variety of benefits. It can insulate you from safety while providing some flexibility via type hierarchies, interfaces, protocols, abstractions and so on.</p>
<p>Further, studying design patterns can teach you repeatable solutions to problems which have been encountered since the dawn of the general purpose computer – or shortly thereafter. </p>
<p>But the Law of Suitability still applies here. Maybe you just need to write a quick script to migrate some data from one SQL database to another. Maybe you know how to approach problems using a more functional approach that doesn’t require or discourages the use of objects, classes, or structs. Maybe you realize one day that trying to apply design patterns, architectures, hierarchies and similar constructs in every situation has actually created as many problems as they were solving. More on that later.</p>
<p>It’s also worth mentioning that most modern language designers and maintainers have understood that we developers like flexibility. Many of us want to avoid premature optimization and unnecessary structure but also don’t want our code to blow up because we accidentally told the program to add together 1.23356 + “Rhinoceros”. </p>
<p>The main point is that structure or a lack of structure is both a blessing and a curse, depending on where it is used.</p>
<h3 id="heading-popularity-is-only-one-factor">Popularity Is Only One Factor</h3>
<p>I’m not going to say that popularity is irrelevant and that you should start with the least popular hipster programming language you can find. No shade intended to hipster programming languages, but unpopularity is not generally a good thing in isolation, either.</p>
<p>The key point is that many people weighing in on programming languages (probably most) don’t have abundant experience working on a variety of platforms, languages, and settings. If someone has only ever written Python and enjoys doing so, they will naturally tend to regard it above others.</p>
<p>We humans have a tendency to find the first thing that works for us and then die on a hill defending it. But to take a more anecdotal approach here, I know a couple dozen intermediate to senior level developers who have extensive experience in Java and other programming languages. Despite Java still being ranked as one of the most popular languages globally, only one of those developers I know actually prefers to write in Java if they have the choice. </p>
<p>Don’t make the mistake of assuming that the first thing that works for many people will be the last thing you need to try out. I have from time to time experimented with languages such as Haskell, which taught me many valuable lessons about the benefits of making my code more functional (and functionally pure) in nature. </p>
<p>But I have zero intention of using Haskell as my go to solution for building GUI applications. </p>
<h3 id="heading-popularity-is-not-a-guarantee-of-employment">Popularity Is Not A Guarantee Of Employment</h3>
<p>One of the most common things you ought to consider is whether or not the language you pick will help you get a job – assuming that’s a concern. Influencers absolutely love to tell people to choose one particular language because it has the most public commits on GitHub, or another because it has the largest number of programmers using it (which is in practice something that’s impossible to say for sure). </p>
<p>Let me flip that on its head: suppose that the most common programming language and platform combination is JavaScript and web. Let’s further suppose that we have pretty concrete data on the number of job postings on the web which confirms that the largest volume of jobs available is for that combination. Let’s finally suppose that for whatever reason, you strongly dislike JavaScript and enjoyed building a website using PHP. </p>
<p>You will find voices who will tell you that PHP is a dead language and a dead end for job searching. </p>
<p>But if you go looking, you may notice that there is a good supply of job postings out there looking for PHP developers who can expand and maintain existing codebases. You might also have a much better chance of getting an interview because <em>the ratio of job postings to applications is significantly better for PHP developers</em> than JavaScript developers. In fact, my team recently hired a PHP developer!</p>
<h3 id="heading-hardware-amp-working-with-what-you-have">Hardware &amp; Working With What You Have</h3>
<p>This section is largely irrelevant to web developers, but may be extremely important for those looking to target specific hardware or operating systems. Simply put, if you don’t have a computer with Mac OS and XCode, you will have a very hard time developing an iOS app, for example. In my case, back in 2014, I chose Android development partly because I had studied a bit of Java – though a big consideration was that I had an Android phone. </p>
<p>There are some ways around this by paying to use a remote device (such as a remote Mac via an online service), but my experience with such services years ago is that they weren’t great.</p>
<p>Think about what resources you have and how that fits into what you want to build or whom you want to work for. If you have not much other than a cheap computer with a web browser, and you still want to build GUI applications, web development can be a great choice.</p>
<h3 id="heading-what-if-i-want-the-ai-to-code-for-me">What if I Want the AI to Code For Me?</h3>
<p>While this topic is worthy of a separate article, I don’t believe this is an unreasonable question to ask. A year ago, I would have told you that at best, the AI can write some basic code and help you learn some things which may or may not be wrong. </p>
<p>How things have changed! Though I would be bad at my job if I copy pasted code I didn’t understand or didn’t test, AI has absolutely become a force multiplier for me as a developer. </p>
<p>Back to the topic in question, how does this relate to choosing a programming language? Well, after telling you that popularity is not always a big deal, by the nature of how LLMs work, popularity is a factor. In terms of general use, languages like Python, JavaScript, and Java are likely to have the largest amount of training data. My experience has been that the languages I typically use, such as Kotlin, TypeScript, and Swift also do fine.</p>
<p>But there is a curious side effect of developing Android or iOS applications that I don’t experience so much in web development. The nature of these constantly changing platforms and SDKs, with tens of thousands of third party libraries, dozens of architectures, and endless opinions about best practices and anti-patterns, means that LLMs can have serious troubles with complexity or specificity. </p>
<p>I expect this issue to be fixed as LLM services improve correctness checking or other methods to reduce hallucinations.</p>
<h3 id="heading-avoid-the-sunk-cost-fallacy">Avoid the Sunk-Cost Fallacy</h3>
<p>Perhaps the most important point I can make in choosing a programming language is to avoid the sunk-cost fallacy. For the first several years of my part-time studies, I didn’t imagine learning a second language based on how difficult it was for me to learn Java.</p>
<p>Roughly 12 years later, I have written non-trivial code in Java, Kotlin, Swift, C++, TypeScript, and SQL. Further, I have dabbled with code in C, Python, JavaScript, Racket, Haskell, Objective C, Visual Basic, and C#. </p>
<p>It was not the case that I sought out to learn all of these things artificially – I don’t tend to learn things outside of the problems in front of me. It’s that these learning opportunities naturally unfolded along with my personal and professional interests. </p>
<p>Learning the fundamentals or approaching mastery of any general purpose programming language will have carry over to others. It’s true that someone learning Python or JavaScript without CS fundamentals is not going to have much of a clue how things work at the OS level or lower. </p>
<p>It’s also true that I have met several people who could probably code circles around me in C/C++/Assembly but never made it past building toy programs in University or College. </p>
<p>Just keep learning and try to find a balance between personal interest and professional goals.</p>
<h2 id="heading-how-to-find-the-best-libraries-and-frameworks">How to Find the Best Libraries and Frameworks</h2>
<p>The next few topics revolve around a question which we’ll revisit a couple of times before the end of this article: “<em>Does it solve more problems than it creates?</em>”</p>
<h3 id="heading-what-are-libraries-and-frameworks">What Are Libraries and Frameworks?</h3>
<p>Before we proceed, here’s a useful but not definitive definition about the relationship between libraries and frameworks. You’ll find other definitions, but there’s remarkably little consensus on topics like this in this industry.</p>
<p>For me, a library is code which you can take from somewhere and use it to build things. It could be anything from a single line to a large and complex sub-system – usually something in between. I could give you a long and pedantic definition, but that’s not appropriate for this context (suitability!). </p>
<p>One example could be Java’s Math (java.lang.Math) library, which provides you with the following: “<em>The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.</em>”</p>
<p>Some people use the term framework interchangeably with library, and I don’t have any problems with that. When I think of a framework, I’m thinking about something which you build stuff around and is not necessarily to do with solving a specific problem domain (such as mathematics). </p>
<p>An example of this would be RxJava, which is a rather complex framework you can use to bind together and manage data flows across an entire application. I’ve used this framework in almost a dozen applications which did very different things in principle.</p>
<p>I do consider a framework to be a library, fundamentally – they just have a different set of goals and often a larger footprint.</p>
<h3 id="heading-how-to-choose-libraries-and-frameworks">How to Choose Libraries and Frameworks</h3>
<p>When I think about choosing libraries and frameworks, I ask myself these questions:</p>
<ul>
<li><p>Does it solve more problems than it creates compared to writing my own solution?</p>
</li>
<li><p>Is it well-maintained (regularly worked on, responsive authors, backed by tech companies)?</p>
</li>
<li><p>Does it have good documentation (less of a problem now that we can leverage AI for this purpose)?</p>
</li>
<li><p>What kind of footprint does it have?</p>
</li>
</ul>
<p>Let’s take two examples. I won’t refer to the specific platform or name of these libraries to avoid offending anyone. But they were/are both used in mobile development (though they are solving common GUI problems on any platform).</p>
<p>Firstly, one of my favorite libraries had one job: It loads images into the UI. </p>
<p>Although devices are more powerful than they used to be, it can still be a problem to load large images on smart phones for display. Mobile operating systems can be aggressive about killing programs (that is, processes) which use up too much of the system’s resources.</p>
<p>This library handles all aspects of loading images that I’m concerned about:</p>
<ul>
<li><p>Loading the image into a particular widget</p>
</li>
<li><p>Displaying an appropriate loading indicator </p>
</li>
<li><p>Displaying an optional error or fallback state that tells the user something went wrong</p>
</li>
<li><p>Handling the complexities of asynchronously loading in (via URL/URI), processing, and compressing potentially large streams of bits (that is, image data)</p>
</li>
<li><p>Doesn’t inflate the packaged application’s size unnecessarily</p>
</li>
<li><p>Doesn’t change its public API frequently (think changing function names which cause people’s implementations to break when updating versions)</p>
</li>
<li><p>It solves problems that I’m not interested in solving</p>
</li>
</ul>
<p>Secondly, one of my least favorite libraries also had one job: Pagination. Pagination, or paging, in this case refers to loading data in <em>chunks</em> into an application. This is an extremely common pattern in shopping cart or social media applications. </p>
<p>The library I am thinking of approaches that problem like so:</p>
<ul>
<li><p>Tightly couples every layer of your client application (from front end to back end) to its dependencies</p>
</li>
<li><p>This tight coupling makes testing difficult without jumping through some hoops</p>
</li>
<li><p>Handles the core problem of pagination well unless you need customization or specialized cases</p>
</li>
<li><p>Frequently changed its public facing API</p>
</li>
<li><p>Solved (in general) a problem which I am quite happy to write my own solution for</p>
</li>
<li><p>Did not play well with other frameworks due to a restrictive set of types and lack of flexibility</p>
</li>
<li><p>Was constantly updated for a couple of years then ditched and marked deprecated</p>
</li>
<li><p>Did not inflate the packaged applications size too much but certainly more than my own solution would</p>
</li>
</ul>
<p>As you can see, even something which solves a core problem reasonably well, can still fail this simple test of: Does it solve more problems than it creates? Having written pagination code by myself on a couple of occasions now, I would have to be pretty strongly convinced not to. </p>
<h2 id="heading-how-to-find-the-best-programming-principles-and-practices">How to Find the Best Programming Principles and Practices</h2>
<p>There are more best practices and principles than I care to describe in detail. What I will do is explain why I treat programming principles as being distinct from immutable/unbreakable laws. Similarly to my goal of finding the best programming language, I wanted to find the best principles in order to write the best code. </p>
<p>The problem is that any programming principle I’ve come across has also been subject to the Law of Suitability. I’ll discuss one example from personal experience and point out that the question we asked above, “does it solve more problems than creates,” also applies here.</p>
<h3 id="heading-dry-dont-repeat-yourself">D.R.Y – Don’t Repeat Yourself</h3>
<p>This principle can be summarized with the idea that if you find duplicated code, you should pull it into a separate module (file, function, class, library, and so on). Without getting into the weeds, the act of pulling the duplicated code into a separate module can be thought of as a process of abstraction. </p>
<p>To be fair to the creators and proponents of this idea, it’s more nuanced than that. But many developers never bother to dig that deep into nuances – nor should they have to. I ran into the nuances simply by applying this idea more than I should have.</p>
<p>There a couple of cases where code duplication is sometimes preferable:</p>
<ul>
<li><p>You have a set of similar modules (say similar widgets or business rules) but they get used in different places for different reasons</p>
</li>
<li><p>You have a set of similar modules which might change for different reasons (for example, rapidly changing demands from product teams and clients with different priorities) </p>
</li>
<li><p>You’re deliberately grouping certain modules that work together in distinct packages, files, or directories to insulate modules/groupings from affecting each other</p>
</li>
<li><p>You find that you need to add details about one particular implementation into your abstraction, but those details don’t apply to other implementations (that is, it’s a bad abstraction)</p>
</li>
</ul>
<p>All of the things I listed above are summaries of things I have run into in the past. The key take away is that I broadly agree with avoiding code duplication. I also know of some cases where I prefer it. Suitability!</p>
<h3 id="heading-what-about-other-programming-principles">What About Other Programming Principles?</h3>
<p>In general, you can think of all programming principles like YAGNI, DRY, SRP (and other aspects of SOLID), and even software development methodologies like AGILE and Waterfall in the same way. Contextually, you can use them as guidelines to help avoid some common problems. But a person of sufficient creativity and experience can come up with a situation where following any of these principles creates more problems than it solves.</p>
<p>In many cases, you need to apply these things too much in order to understand what too much means in practical terms. Just be careful not to swing too far in the other direction when one of these principles really breaks down in front of you. I’ve also made that mistake and had to re-adjust.</p>
<p>To date, I haven’t come across a programming principle which is universally true. There are some which come close to that, but I can always imagine a situation where they’re not the best approach. Take a good one like: Always write the simplest code you can write. In other words, don’t add extra complexity without a reason. </p>
<p>Well, suppose you have a not great value system or incentive structure which encourages inflating your work artificially. Need I say more?</p>
<h2 id="heading-a-note-about-patterns-and-architectures">A Note About Patterns and Architectures</h2>
<p>I’ll now discuss the topic of patterns and architectures in software systems with respect to the Law of Suitability. Software architecture is the only thing I consider myself an expert in, and I have read multiple books on design patterns. I always try to provide some useful info on these topics when I get the chance.</p>
<h3 id="heading-how-to-find-the-best-software-architecture">How to Find the Best Software Architecture</h3>
<p>To summarize entire articles, courses, and public talks I have given on this topic: The best software architecture depends on project and personal requirements. </p>
<p>One way to grasp the main idea is to ask yourself whether the best architecture for a hospital is also a good fit for a 2-bedroom apartment. The obvious answer is that we might expect a few commonalities (doors, windows, bathrooms of some kind, and so on) among these different sets of requirements. But the ideal, or even just a good architecture for a 2 bedroom apartment cannot possibly be the same for a hospital. </p>
<p>In short, you will never find an architecture which works well for all projects and requirements.</p>
<p>Here is a list of architectures I have some familiarity with:</p>
<ul>
<li><p>Model-View-Controller</p>
</li>
<li><p>Model-View-Presenter</p>
</li>
<li><p>Model-View-ViewModel</p>
</li>
<li><p>VIPER</p>
</li>
<li><p>Clean Architecture (Robert C. Martin style)</p>
</li>
<li><p>Model-View-Intent</p>
</li>
</ul>
<p>To make matters more confusing, there are multiple different ways to implement these architectures – almost as many ways as developers implementing them! M-V-VM is one of the more common architectures in mobile development, and I can think of at least five different variations on how to achieve what some people think of as a single architecture.</p>
<p>Here are my general suggestions for working with these architectures:</p>
<ul>
<li><p>Be wary of adding unnecessary complexity with the more complex architectures (particularly Clean Architecture, as many people get this horribly wrong)</p>
</li>
<li><p>Don’t try to make the project requirements fit the architecture – work the other way around (the best indicator for this is noticing that something you’re trying to implement is made unnecessarily difficult because of the architecture you’re using)</p>
</li>
<li><p>Don’t be afraid of applying different approaches in different features of the same application instead of blindly applying the same pattern just for consistency’s sake</p>
</li>
</ul>
<h3 id="heading-the-design-pattern-trap">The Design Pattern Trap</h3>
<p>One of the most common engagement farming tactics I see on social media is to post lists of design patterns “that you must know” in order to get a job or to scare junior programmers into buying your low-quality, copy-pasted content of each pattern.</p>
<p>Don’t get me wrong, I loved studying design patterns and I use a couple key patterns in most GUI applications I build. The Observer (a.k.a. Publisher-Subscriber or Pub-Sub) Pattern really shines when you need to glue together a bunch of asynchronous data sources. I love seeing library developers give me a nice Builder Pattern to work with their APIs. I think understanding the basics of patterns like the Bridge or Facade can teach you how to hide details behind abstractions, which is actually simpler than the big scary words describing these things make it sound.</p>
<p>But I spend very little time in my day to day work thinking about or in design patterns. Instead, I’m always thinking about the kinds of attitudes and principles that give rise to these patterns: </p>
<ul>
<li><p>Promoting loosely coupled code (separating the creation and usage of dependencies and parameters, reasonable usage of abstraction)</p>
</li>
<li><p>Writing classes, interfaces, protocols, and functions which do one thing (though this “one thing” might be a macroscopic goal instead of a microscopic operation)</p>
</li>
<li><p>Avoiding complexity wherever possible (a common source of this complexity is over-use of abstractions)</p>
</li>
<li><p>Not pretending that every complex problem has a simple solution (that is, as simple as it can be but no simpler)</p>
</li>
<li><p>Avoiding pre-mature optimization</p>
</li>
</ul>
<p>Again, I will only apply these principles and attitudes to the extent that I find they solve more problems than they create. Design patterns, when applied too rigorously, can break many of those principles – particularly when it comes to avoiding complexity and pre-mature optimization. </p>
<p>Don’t try to make your project requirements fit your patterns. Instead, think about which patterns might suit your project requirements and deviate as necessary.</p>
<h2 id="heading-summary">Summary</h2>
<p>My goal with this piece was to provide three things:</p>
<ul>
<li><p>A practical overview of choosing a programming language and avoiding the traps the people can fall into when navigating these sorts of topics</p>
</li>
<li><p>A philosophical but pragmatic framework which you can use to evaluate the suitability of anything – with emphasis on learning and developing software</p>
</li>
<li><p>A breakdown of how I approach other topics like tools, architectures, and patterns</p>
</li>
</ul>
<p>While it can be important to consider things like job opportunities and your current hardware, don’t discount personal interest as a driving factor. From what little I remember about studying cognition (learning how to learn), interest is tightly coupled to motivation and memory. We can’t always exclusively do what interests us, but I suggest you look for intersections between personal and practical concerns as often as you can. </p>
<p>In closing, I encourage you to think about other areas where you might be able to explore the principles of suitability and the problems of tribalistic thinking. Change is constant and value is relative.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Embedded Swift: A Modern Approach to Low-Level Programming ]]>
                </title>
                <description>
                    <![CDATA[ Embedded programming has long been dominated by C and C++, powering everything from microcontrollers to real-time systems. While these languages offer unmatched low-level control, they also introduce persistent challenges, manual memory management, u... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/embedded-swift-a-modern-approach-to-low-level-programming/</link>
                <guid isPermaLink="false">688d5fc7d30be1cecdacf767</guid>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firmware Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ memory-management ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham Banerjee ]]>
                </dc:creator>
                <pubDate>Sat, 02 Aug 2025 00:45:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754090186842/80a42dca-f2c4-49de-b704-2e90134c6397.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Embedded programming has long been dominated by C and C++, powering everything from microcontrollers to real-time systems. While these languages offer unmatched low-level control, they also introduce persistent challenges, manual memory management, unsafe pointer operations, and subtle logic bugs stemming from weak type systems and undefined behavior.</p>
<p>With the release of Swift 6 and its new Embedded Swift compilation mode, developers now have access to a modern, memory-safe, and performant alternative that’s tailored specifically for resource-constrained systems.</p>
<p>While languages like Rust have also emerged to address these issues, Embedded Swift brings the clarity and safety of Swift to microcontroller environments, without giving up on determinism, binary size, or hardware access.</p>
<p>This article introduces Embedded Swift and explores how it compares to traditional C/C++ development. We’ll cover its key features, programming and memory models, how to set up the toolchain for STM32 microcontrollers, and how to link Swift with existing C drivers.</p>
<p>Along the way, we’ll examine performance trade-offs, growing ecosystem support, and the broader industry movement toward memory-safe languages. As I hope you’ll see, Swift is a serious contender in the future of embedded development.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To get the most out of this article, you should have a basic understanding of programming in Swift and C. Familiarity with embedded hardware platforms and firmware development concepts will also be helpful.</p>
<p>If you're new to embedded systems, consider reviewing this <a target="_blank" href="https://www.freecodecamp.org/news/learn-embedded-systems-firmware-basics-handbook-for-devs/">introductory guide to embedded firmware</a> to build foundational knowledge before diving into Embedded Swift.</p>
<h2 id="heading-scope">Scope</h2>
<p>This article is intended as a practical introduction to Embedded Swift. It covers:</p>
<ul>
<li><p>An overview of Embedded Swift and its key language features</p>
</li>
<li><p>Swift’s programming and memory model in an embedded context</p>
</li>
<li><p>Setting up the Embedded Swift toolchain on macOS for STM32 microcontrollers</p>
</li>
<li><p>Interoperability with C code and linking to existing low-level drivers</p>
</li>
<li><p>A look at memory and instruction-level performance</p>
</li>
<li><p>Future directions and use cases for Embedded Swift</p>
</li>
</ul>
<p>Note that this article does not provide a full tutorial on the Swift language itself. While the primary focus is on STM32, similar principles apply to other supported platforms such as ESP32, Raspberry Pi Pico, and nRF52.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-swift-what-is-embedded-swift">What is Swift? What is Embedded Swift?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-swift-programming-model">Swift Programming Model</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-swift-memory-management">Swift Memory Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-memory-and-instruction-cycle-comparison">Memory and Instruction Cycle Comparison</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-setup-embedded-swift">How to Setup Embedded Swift</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-c-swift-linkages">C-Swift Linkages:</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-future-work">Future Work</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-swift-what-is-embedded-swift">What is Swift? What is Embedded Swift?</h2>
<p>Swift is a modern programming language developed by Apple that combines the performance of compiled languages with the expressiveness and safety of modern language design. While Swift was originally created for iOS and macOS development, it has evolved into a powerful general-purpose language used in server-side development, systems programming, and increasingly, embedded systems.</p>
<p>Embedded Swift is a special compilation mode introduced in Swift 6 that brings the benefits of Swift to resource-constrained platforms like microcontrollers. It lets developers use a safe, high-level language while still producing compact, deterministic, and performant binaries suitable for embedded applications.</p>
<h3 id="heading-key-features-of-swift">Key Features of Swift</h3>
<p>Embedded Swift retains many of the powerful language features that make Swift an attractive alternative to C/C++ in embedded development:</p>
<p><strong>Type Safety</strong>: Swift uses a strong static type system, which prevents many programming errors at compile time. Unlike C, where type mismatches can result in undefined behavior, Swift ensures all types are used correctly before code even runs.</p>
<p><strong>Strict Type Checking</strong>: Swift doesn't allow implicit type conversions that could lose data or cause unexpected behavior. For example:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// This won't compile in Swift</span>
<span class="hljs-keyword">let</span> integer: <span class="hljs-type">Int</span> = <span class="hljs-number">42</span>
<span class="hljs-keyword">let</span> decimal: <span class="hljs-type">Double</span> = <span class="hljs-number">3.14</span>
<span class="hljs-keyword">let</span> result = integer + decimal  <span class="hljs-comment">// Error: Cannot convert value of type 'Int' to expected argument type 'Double'</span>

<span class="hljs-comment">// You must be explicit about conversions</span>
<span class="hljs-keyword">let</span> result = <span class="hljs-type">Double</span>(integer) + decimal  <span class="hljs-comment">// Correct</span>
</code></pre>
<p><strong>Non-nullable Types by Default</strong>: In C, pointers can be null by default, which introduces risk. In Swift, variables cannot be nil unless explicitly marked as optionals:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span> = <span class="hljs-string">"John"</span>
name = <span class="hljs-literal">nil</span>  <span class="hljs-comment">// Compile error - String cannot be nil</span>

<span class="hljs-keyword">var</span> optionalName: <span class="hljs-type">String?</span> = <span class="hljs-string">"John"</span>
optionalName = <span class="hljs-literal">nil</span>  <span class="hljs-comment">// This is allowed</span>
</code></pre>
<h4 id="heading-memory-safety-via-arc-covered-in-detail-later">Memory Safety via ARC (Covered in detail later):</h4>
<p>Swift manages memory automatically using Automatic Reference Counting (ARC). Unlike manual memory management in C/C++, ARC handles object lifecycles efficiently without unpredictable garbage collection pauses. We'll cover ARC and its impact in embedded contexts in a dedicated section later.</p>
<p><strong>Modern Syntax</strong>:<br>Swift's syntax is clean, consistent, and designed for readability. It supports modern paradigms including:</p>
<ul>
<li><p>Functional programming (map, filter, reduce)</p>
</li>
<li><p>Generics (type-safe abstractions)</p>
</li>
<li><p>Protocol-Oriented Programming (discussed in the next section)</p>
</li>
</ul>
<p>These features allow you to write more expressive and maintainable code compared to procedural C or inheritance-heavy C++.</p>
<p><strong>Performance</strong>:<br>Swift is designed to perform on par with C++ in many scenarios. Optimizations such as inlining, dead code elimination, and static dispatch help ensure that high-level abstractions don’t compromise performance. In embedded mode, Swift disables features like runtime reflection and dynamic dispatch to further reduce overhead.</p>
<p>To fully leverage Swift for embedded development, it's important to understand its programming model. Unlike C’s procedural approach or C++’s class-heavy design, Swift promotes protocol-oriented programming and composition, which offers both flexibility and safety in embedded system design.</p>
<h2 id="heading-swift-programming-model">Swift Programming Model</h2>
<p>Swift embraces a multi-paradigm programming model that blends object-oriented, functional, and protocol-oriented programming, all underpinned by strong type safety and memory safety.</p>
<p>For embedded developers coming from C or C++, this model may feel different at first. But it provides a more modular and testable way to build complex systems, something especially valuable in embedded applications where hardware abstraction and strict reliability are critical.</p>
<h3 id="heading-protocol-oriented-programming-pop">Protocol-Oriented Programming (POP)</h3>
<p>Swift emphasizes protocols over inheritance, encouraging developers to define behaviors through protocols and implement them using value types like <code>struct</code> and <code>enum</code>, rather than relying heavily on classes.</p>
<p>This philosophy favors composition over inheritance, allowing you to build complex functionality by combining smaller, well-defined components.</p>
<p>Key Concepts<strong>:</strong></p>
<ul>
<li><p><code>protocol</code> defines required behavior.</p>
</li>
<li><p>Protocol extensions provide default behavior.</p>
</li>
<li><p>Prefer value semantics using <code>struct</code>.</p>
</li>
</ul>
<p>Example<strong>:</strong></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>
}

<span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Default sound"</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Woof!"</span>)
    }
}
</code></pre>
<p>Embedded Swift uses protocols with static dispatch. With static dispatch, the compiler knows the exact memory address of the function to call and can generate a direct jump instruction. There's no runtime lookup, no indirection, and no uncertainty.</p>
<h4 id="heading-why-pop-matters-for-embedded-systems">Why POP Matters for Embedded Systems</h4>
<p>First, you get flexible hardware extraction. Protocols make it easy to define interfaces for hardware components, allowing for mock implementations during testing or platform-specific variations.</p>
<p>Second, you have nice low overhead. Embedded Swift uses static dispatch for protocols, meaning there’s no runtime lookup, and calls are resolved at compile time for maximum performance.</p>
<p>Also, <code>struct</code> and <code>enum</code> types avoid heap allocations, making code more efficient and predictable in low-memory environments.</p>
<p>Now that we’ve explored how Swift’s programming model enables safer and more modular embedded code, let’s turn to another critical piece of the puzzle: memory management. Swift’s use of Automatic Reference Counting (ARC) replaces manual memory handling and offers important benefits, and tradeoffs, for embedded systems.</p>
<h2 id="heading-swift-memory-management">Swift Memory Management</h2>
<p>One of Swift’s most impactful features, especially in the context of embedded systems, is its use of Automatic Reference Counting (ARC) for memory management. Unlike C/C++, where memory must be manually allocated and freed using <code>malloc</code> and <code>free</code>, Swift automates this process while maintaining deterministic performance.</p>
<p>This automation significantly reduces the risk of common memory-related bugs like leaks, dangling pointers, or use-after-free errors, all of which are notorious in low-level C code.</p>
<h3 id="heading-how-arc-works">How ARC works</h3>
<p>Swift supports ARC not only for the Cocoa Touch API's but for all APIs, providing a streamlined approach to memory management. Unlike garbage collection systems that can cause unpredictable pauses, ARC works deterministically at compile time and runtime to manage memory.</p>
<p>ARC automatically tracks and manages the lifetime of objects in memory based on how many references point to them.</p>
<ul>
<li><p>Reference Counting: Every object has a counter that tracks how many strong references point to it.</p>
</li>
<li><p>Retain / Release: The compiler inserts <code>retain</code> and <code>release</code> calls automatically during assignment and deinitialization.</p>
</li>
<li><p>Immediate Deallocation: When the reference count reaches zero, the object is deallocated immediately.</p>
</li>
<li><p>Deterministic: Unlike garbage collectors, ARC doesn’t introduce unpredictable pauses or runtime scanning.</p>
</li>
</ul>
<p>Swift offers multiple reference types to give you precise control over memory behavior and prevent cycles:</p>
<p><strong>Strong References</strong> (default)</p>
<ul>
<li><p>Keeps the referenced object alive.</p>
</li>
<li><p>Used in most cases.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">var</span> sensor: <span class="hljs-type">SensorData?</span>  <span class="hljs-comment">// Strong reference</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateReading</span><span class="hljs-params">(newData: SensorData)</span></span> {
        <span class="hljs-keyword">self</span>.sensor = newData  <span class="hljs-comment">// Previous sensor data automatically deallocated</span>
    }
}
</code></pre>
<p><strong>Weak References</strong></p>
<ul>
<li><p>Used to break reference cycles (especially in two-way object relationships).</p>
</li>
<li><p>Automatically becomes <code>nil</code> when the referenced object is deallocated.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Device</span> </span>{
    <span class="hljs-keyword">var</span> controller: <span class="hljs-type">MotorController?</span>

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Device deallocated"</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">weak</span> <span class="hljs-keyword">var</span> device: <span class="hljs-type">Device?</span>  <span class="hljs-comment">// ← Weak reference breaks the cycle</span>

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"MotorController deallocated"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">breakCycle</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> device = <span class="hljs-type">Device</span>()
    <span class="hljs-keyword">let</span> controller = <span class="hljs-type">MotorController</span>()

    device.controller = controller
    controller.device = device  <span class="hljs-comment">// ← This is now a weak reference</span>

    <span class="hljs-comment">// When this function ends, both objects are properly deallocated</span>
}

breakCycle()
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Device deallocated</span>
<span class="hljs-comment">// MotorController deallocated</span>
</code></pre>
<p><strong>Unowned References</strong></p>
<ul>
<li><p>Non-optional version of <code>weak</code>.</p>
</li>
<li><p>Assumes the object will never be deallocated while still in use.</p>
</li>
<li><p>More lightweight than <code>weak</code>, but unsafe if misused.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SensorSystem</span> </span>{
    <span class="hljs-keyword">unowned</span> <span class="hljs-keyword">let</span> controller: <span class="hljs-type">MotorController</span>  <span class="hljs-comment">// unowned reference</span>

    <span class="hljs-keyword">init</span>(controller: <span class="hljs-type">MotorController</span>) {
        <span class="hljs-keyword">self</span>.controller = controller
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">var</span> sensorSystem: <span class="hljs-type">SensorSystem?</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setupSensors</span><span class="hljs-params">()</span></span> {
        sensorSystem = <span class="hljs-type">SensorSystem</span>(controller: <span class="hljs-keyword">self</span>)
    }

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"MotorController deallocated"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">testUnowned</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> controller = <span class="hljs-type">MotorController</span>()
    controller.setupSensors()
    <span class="hljs-comment">// sensorSystem deallocates before controller ends</span>
}

testUnowned()
<span class="hljs-comment">// Output: MotorController deallocated</span>
</code></pre>
<h3 id="heading-arc-overhead-in-embedded-systems">ARC Overhead in Embedded Systems</h3>
<p>While ARC provides safety benefits, it does introduce some overhead compared to manual memory management:</p>
<h4 id="heading-memory-overhead">Memory Overhead:</h4>
<p>ARC-managed class instances in Swift typically include an additional 4 or 8 bytes to store reference count metadata, depending on the system architecture, 4 bytes on 32-bit systems and 8 bytes on 64-bit systems. This metadata allows the runtime to track how many active references exist to a given object and deallocate it when no references remain. When developers use weak or unowned references, the memory footprint increases further. These references require additional data structures, such as side tables or tracking mechanisms, to manage object liveness and cleanup. In the case of weak references specifically, Swift maintains zeroing weak reference tables that automatically null out pointers once the referenced object is deallocated, ensuring memory safety.</p>
<h4 id="heading-cpu-overhead">CPU Overhead:</h4>
<p>ARC introduces some runtime overhead due to retain and release operations, which are inserted automatically during reference assignments. These operations involve incrementing or decrementing the reference count and are especially common in code that passes objects between functions or stores them in collections. To ensure thread safety, these updates are typically implemented using atomic operations, which add further instruction cycles. In complex object graphs, ARC may also engage in cycle detection and cleanup through the use of weak references to prevent memory leaks caused by strong reference cycles. While Swift's ARC provides deterministic and efficient memory management, it does so with both memory and CPU costs that developers should consider carefully, especially in performance-critical embedded systems.</p>
<h3 id="heading-type-safety-and-error-prevention">Type Safety and Error Prevention</h3>
<p>Swift's type system prevents many common errors that plague C/C++ programs:</p>
<ul>
<li><p><strong>Buffer Overflows</strong>: Swift arrays are bounds-checked, preventing buffer overflow vulnerabilities that are common in C.</p>
</li>
<li><p><strong>Null Pointer Dereferences</strong>: Swift's optional types make null pointer dereferences impossible at compile time.</p>
</li>
<li><p><strong>Use After Free</strong>: Swift's ownership model prevents use-after-free errors that can cause crashes or security vulnerabilities.</p>
</li>
</ul>
<p>Now that we’ve covered Swift's memory model and ARC behavior, let’s explore how it compares to C in terms of memory usage and instruction cycles, a crucial aspect when evaluating Embedded Swift for real-world deployment.</p>
<h2 id="heading-memory-and-instruction-cycle-comparison">Memory and Instruction Cycle Comparison</h2>
<p>Understanding the performance characteristics of Swift versus C is essential for embedded systems, where every instruction cycle and byte of memory matters. While Swift brings advantages like safety and expressiveness, these benefits come with certain trade-offs in terms of memory usage and runtime behavior that embedded developers must evaluate carefully.</p>
<h3 id="heading-memory-management">Memory Management:</h3>
<p>Swift uses Automatic Reference Counting (ARC) to manage memory. ARC tracks the number of references to each object and deallocates it when no references remain. This eliminates the need for explicit <code>free()</code> calls but introduces overhead.</p>
<p>C, in contrast, uses manual memory management. Developers allocate memory using <code>malloc</code> and release it using <code>free</code>, or rely on the stack for most short-lived data.</p>
<p>The table below provides the memory management comparison between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Feature</strong></td><td><strong>Swift (ARC)</strong></td><td><strong>C (Manual)</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Memory strategy</td><td>Automatic reference counting</td><td>Manual with <code>malloc</code>/<code>free</code></td></tr>
<tr>
<td>Overhead per object</td><td>4–8 bytes (for ref count)</td><td>None for stack; variable for heap</td></tr>
<tr>
<td>Deallocation</td><td>Deterministic, triggered by ARC</td><td>Developer-controlled</td></tr>
<tr>
<td>Weak reference support</td><td>Requires additional metadata</td><td>Not built-in</td></tr>
<tr>
<td>Thread safety</td><td>Atomic operations in ARC</td><td>Not guaranteed</td></tr>
<tr>
<td>Layout control</td><td>Limited, compiler-managed</td><td>Full control (via structs/pointers)</td></tr>
</tbody>
</table>
</div><p>Swift ensures safety through deterministic cleanup and predictable memory usage. But this comes at the cost of added memory and CPU overhead.</p>
<p>C’s approach offers complete control over memory layout and minimal runtime cost, but increases the risk of memory leaks and fragmentation without disciplined practices.</p>
<h3 id="heading-instruction-cycle-analysis">Instruction Cycle Analysis</h3>
<p>The safety features in Swift, such as bounds checking, optional unwrapping, and ARC updates, translate into additional CPU instructions. While this can impact performance, the Swift compiler is aggressive about optimization in release builds. For example, inlining and ARC elision can remove much of the overhead in performance-critical paths.</p>
<p>C has no built-in safety checks, allowing it to generate highly efficient, predictable code. Developers can even use inline assembly for tight control over performance.</p>
<p>The table below provides the instruction cycle comparison between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Instruction-Level Feature</strong></td><td><strong>Swift</strong></td><td><strong>C</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Reference count updates</td><td>2–4 instructions per assignment</td><td>N/A</td></tr>
<tr>
<td>Bounds checking</td><td>1–3 instructions per array access</td><td>None</td></tr>
<tr>
<td>Optional unwrapping</td><td>1–2 instructions per check</td><td>N/A</td></tr>
<tr>
<td>Method dispatch</td><td>Protocols introduce indirection</td><td>Direct calls or function pointers</td></tr>
<tr>
<td>Optimization potential</td><td>ARC elision, inlining, dead code removal</td><td>Full manual control, inline assembly</td></tr>
<tr>
<td>Predictability</td><td>High in optimized builds, with some abstraction overhead</td><td>Very high, minimal abstraction</td></tr>
</tbody>
</table>
</div><p>Although Swift inserts extra instructions for safety, much of this cost can be mitigated through compiler optimization.</p>
<p>C has no such features by default, making it ideal for applications where performance must be tightly controlled and the developer is willing to take full responsibility for safety.</p>
<h3 id="heading-instruction-count-comparison-swift-vs-c-loop-performance">Instruction Count Comparison: Swift vs C Loop Performance</h3>
<p>When evaluating Swift and C for embedded use, it's helpful to analyze instruction-level performance on basic operations, such as a loop that processes an array of floating-point numbers. This gives us a concrete sense of the computational cost of each language's safety and abstraction features.</p>
<p>Let’s consider a simple example: summing an array of <code>Float</code> values and returning the average. In Swift, the code uses a high-level <code>for-in</code> loop over an array:</p>
<p>Simple loop performance:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Swift loop with safety checks</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processData</span><span class="hljs-params">(<span class="hljs-number">_</span> data: [Float])</span></span> -&gt; <span class="hljs-type">Float</span> {
    <span class="hljs-keyword">var</span> sum: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>
    <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> data {  <span class="hljs-comment">// Iterator with bounds checking</span>
        sum += value     <span class="hljs-comment">// Safe arithmetic</span>
    }
    <span class="hljs-keyword">return</span> sum / <span class="hljs-type">Float</span>(data.<span class="hljs-built_in">count</span>)  <span class="hljs-comment">// Safe division</span>
}
<span class="hljs-comment">// Estimated: ~8-10 instructions per iteration</span>
</code></pre>
<p>Although elegant and safe, this loop includes several safety mechanisms:</p>
<ol>
<li><p>Bounds checking on every array access</p>
</li>
<li><p>Reference counting if <code>data</code> is passed as a reference type</p>
</li>
<li><p>Overflow protection in debug mode</p>
</li>
<li><p>Optional handling or runtime checks if <code>data</code> might be empty</p>
</li>
</ol>
<p>These checks introduce runtime overhead, resulting in an estimated 8–10 instructions per iteration on most platforms (depending on optimization level and target architecture). In release builds, Swift aggressively inlines and strips redundant checks, but some level of abstraction cost remains, especially compared to raw memory access in C.</p>
<p>Now, compare that to its equivalent in C:</p>
<pre><code class="lang-c"><span class="hljs-comment">// C loop without safety checks</span>
<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">process_data</span><span class="hljs-params">(<span class="hljs-keyword">float</span>* data, <span class="hljs-keyword">int</span> count)</span> </span>{
    <span class="hljs-keyword">float</span> sum = <span class="hljs-number">0.0f</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; count; i++) {  <span class="hljs-comment">// Direct pointer arithmetic</span>
        sum += data[i];                <span class="hljs-comment">// Direct memory access</span>
    }
    <span class="hljs-keyword">return</span> sum / count;  <span class="hljs-comment">// Direct division (no safety check)</span>
}
<span class="hljs-comment">// Estimated: ~4-5 instructions per iteration</span>
</code></pre>
<p>This version performs direct memory access with pointer arithmetic, no bounds checks, and no type safety. The C code is lower-level, with fewer runtime checks, and compiles down to just 4–5 instructions per iteration, depending on the target CPU and compiler flags. It is lean and fast, ideal for cycles-per-instruction-critical scenarios.</p>
<p>The table below shows the comparison of single loop performance between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Swift</td><td>C</td></tr>
</thead>
<tbody>
<tr>
<td>Array access</td><td>Bounds-checked</td><td>Direct pointer access</td></tr>
<tr>
<td>Loop iteration</td><td>High-level iterator abstraction</td><td>Raw loop with pointer increment</td></tr>
<tr>
<td>Instruction count (per loop)</td><td>~8–10 (in debug), ~6–8 (in release)</td><td>~4–5</td></tr>
<tr>
<td>Division</td><td>Safe (avoids divide-by-zero in dev)</td><td>Direct</td></tr>
<tr>
<td>Overflow behavior</td><td>Checked in debug, unchecked in release</td><td>Unchecked</td></tr>
<tr>
<td>Readability and safety</td><td>High</td><td>Low</td></tr>
<tr>
<td>Performance</td><td>Lower (but optimizable)</td><td>Higher (manual)</td></tr>
</tbody>
</table>
</div><p>Now that we’ve compared Swift and C in terms of memory and cycle costs, let’s move into the practical side: how to set up Embedded Swift on an STM32 platform and get started with real-world development.</p>
<h2 id="heading-how-to-setup-embedded-swift">How to Setup Embedded Swift</h2>
<p>In this section, we'll walk through how to configure and use Embedded Swift for development on STM32 microcontrollers. STM32 is a popular family of ARM Cortex-M–based microcontrollers, commonly used in industrial, consumer, and IoT applications.</p>
<h3 id="heading-prerequisites-1">Prerequisites</h3>
<p><strong>Required Software:</strong></p>
<ul>
<li><p>Swift Development Snapshot (includes the Embedded Swift toolchain)</p>
</li>
<li><p>Swiftly - Easiest way to manage and install swift toolchains</p>
</li>
<li><p>Swiftc - Swift Compiler command-line tool</p>
</li>
<li><p>Python3 - Required to run scripts to convert Mach-O to binary files</p>
</li>
<li><p>Git (to clone sample repositories) like <a target="_blank" href="https://github.com/swiftlang/swift-embedded-examples">https://github.com/swiftlang/swift-embedded-examples</a></p>
</li>
<li><p>A Unix-like development environment (macOS is currently best supported)</p>
</li>
</ul>
<p><strong>Target Hardware:</strong> This guide focuses on STM32 microcontrollers, which are widely used in embedded applications and have excellent community support.</p>
<p>This guide walks you through the full setup process, from installing the required Swift toolchain to flashing the final binary onto your board. We’ll begin by installing the Swift Development Snapshot using Swiftly, a simple command-line utility for managing Swift toolchains. From there, we’ll configure the build system, set up the correct board variant, customize the build script, and compile the Swift and C source code into a binary. Finally, we’ll flash the firmware onto the STM32 using standard tools</p>
<h3 id="heading-install-swift-development-snapshot">Install Swift Development Snapshot</h3>
<p>The easiest way to install and manage Embedded Swift toolchains is by using the swiftly tool, which simplifies downloading and using Swift snapshots.</p>
<h4 id="heading-macos-installation">macOS Installation:</h4>
<p>The below steps will help install the Swift embedded toolchain:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Using Swiftly (Recommended)</span>
curl -O https://download.swift.org/swiftly/darwin/swiftly.pkg
installer -pkg swiftly.pkg -target CurrentUserHomeDirectory
~/.swiftly/bin/swiftly init --quiet-shell-followup
<span class="hljs-built_in">source</span> <span class="hljs-string">"<span class="hljs-variable">${SWIFTLY_HOME_DIR:-<span class="hljs-variable">$HOME</span>/.swiftly}</span>/env.sh"</span>

<span class="hljs-comment"># Install and use development snapshot</span>
swiftly install main-snapshot
swiftly use main-snapshot

<span class="hljs-comment"># Verify installation</span>
swift --version
</code></pre>
<p>You can clone this Github example repository:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/swiftlang/swift-embedded-examples.git 
<span class="hljs-built_in">cd</span> swift-embedded-examples/projects/stm32-blink
</code></pre>
<p>The stm32-blink contains:</p>
<ul>
<li><p>Swift code that toggles GPIOs</p>
</li>
<li><p>A C startup file with vector table</p>
</li>
<li><p>A build.sh script that uses swiftc, clang, and a custom linker setup</p>
</li>
</ul>
<h3 id="heading-setup-the-stm32-board">Setup the STM32 Board</h3>
<p>Tell the build script which STM32 board is being used:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> STM_BOARD=STM32F746G_DISCOVERY
</code></pre>
<p>You can add your own board variant by defining the appropriate memory map and compiler flags in the script.</p>
<h3 id="heading-modify-buildsh-optional">Modify build.sh (Optional)</h3>
<p>Ensure the script correctly locates the following:</p>
<ul>
<li><p>swiftc: should point to the toolchain you installed with Swiftly</p>
</li>
<li><p>clang: can be macOS’s default Clang</p>
</li>
<li><p>libBuiltin.a, crt0.s, and macho2bin.py: used to provide minimal runtime support and convert output to flashable binaries</p>
</li>
</ul>
<p>If needed, update these paths:</p>
<pre><code class="lang-bash">SWIFT_EXEC=<span class="hljs-variable">${SWIFT_EXEC:-$(swiftly which swiftc)}</span>
CLANG_EXEC=<span class="hljs-variable">${CLANG_EXEC:-$(xcrun -f clang)}</span>
PYTHON_EXEC=<span class="hljs-variable">${PYTHON_EXEC:-$(which python3)}</span>
</code></pre>
<p>Ensure the linker flags match your target’s flash and RAM sizes.</p>
<h3 id="heading-build-and-flash-the-project">Build and Flash the Project:</h3>
<p>Run:</p>
<pre><code class="lang-bash">./build.sh
</code></pre>
<p>This compiles Swift and C code, links them, and produces a blink.bin file.</p>
<p>If successful, you’ll see:</p>
<pre><code class="lang-bash">.build/blink.bin  <span class="hljs-comment"># ready to flash Step 6: Flash the Firmware to STM32</span>
</code></pre>
<p>Use ST-Link tools or openocd to flash your board. Example using st-flash:</p>
<pre><code class="lang-bash">brew install stlink
st-flash write .build/blink.bin 0x8000000
</code></pre>
<p>You should now see an LED blinking.</p>
<p><a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded/stm32baremetalguide">Here’s</a> a more detailed step by step approach to writing a bare metal code on STM32. For comprehensive installation guides covering other platforms (Raspberry Pi Pico, ESP32, nRF52), detailed IDE configuration, troubleshooting, and advanced examples, you can check out the official documentation:</p>
<ul>
<li><p>Complete Setup Guide: <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded/installembeddedswift/">Install Embedded Swift</a></p>
</li>
<li><p>Platform Examples: <a target="_blank" href="https://github.com/apple/swift-embedded-examples">Swift Embedded Examples Repository</a></p>
</li>
<li><p>Getting Started Tutorial: <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded">Embedded Swift on Microcontrollers</a></p>
</li>
</ul>
<p>Now that we’ve set up Embedded Swift and explored how to build and run an example project, let’s look at a critical real-world scenario: interfacing Swift with low-level C drivers.</p>
<h2 id="heading-c-swift-linkages">C-Swift Linkages</h2>
<p>In many embedded projects, low-level hardware drivers are written in C because of its close-to-metal control and widespread ecosystem support. Embedded Swift supports seamless interoperability with C, which lets you reuse existing C libraries and drivers, write hardware control logic in C, and implement higher-level application logic in Swift.</p>
<p>This hybrid model lets you combine Swift’s safety and productivity with C’s hardware-level control, with no runtime overhead or object translation.</p>
<p>Let’s walk through an example where a low-level sensor driver is implemented in C and the application logic is written in Swift.</p>
<h3 id="heading-c-header-file-sensordriverh">C Header File (sensor_driver.h):</h3>
<p>This C header file defines the public interface for a low-level sensor driver. It includes standard fixed-width integer types and declares four functions:</p>
<ul>
<li><p>sensor_init(): Initializes the hardware sensor</p>
</li>
<li><p>sensor_read_temperature() and sensor_read_humidity(): Read raw sensor values</p>
</li>
<li><p>sensor_delay_ms(): Delays execution for a given number of milliseconds</p>
</li>
</ul>
<p>This interface acts as a bridge between Swift and C. Swift will link to these functions by name, no wrappers or bindings required.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">ifndef</span> SENSOR_DRIVER_H</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> SENSOR_DRIVER_H</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdint.h&gt;</span></span>

<span class="hljs-comment">// Low-level sensor driver functions</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-keyword">uint32_t</span> milliseconds)</span></span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
</code></pre>
<h3 id="heading-c-implementation-sensordriverc">C Implementation (sensor_driver.c):</h3>
<p>This implementation assumes the sensor is memory-mapped at a fixed address (<code>0x40001000</code>). Each register, temperature, humidity, and control, is accessed by offset from that base address.</p>
<p>The <code>sensor_init</code>() function writes <code>0x01</code> to the control register, presumably enabling or starting the sensor hardware.</p>
<p>The <code>sensor_read_temperature()</code> method and <code>sensor_read_humidity()</code> method reads from memory-mapped registers and return the raw ADC values from the sensor.</p>
<p>The <code>sensor_delay_ms()</code> method performs a simple busy-wait loop using nop (no-operation) instructions to approximate a delay. This is suitable for short, coarse-grained delays in bare-metal contexts.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"sensor_driver.h"</span></span>

<span class="hljs-comment">// Hardware register addresses</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> SENSOR_BASE_ADDR    0x40001000</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> TEMP_REG_OFFSET     0x00</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> HUMIDITY_REG_OFFSET 0x04</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> CONTROL_REG_OFFSET  0x08</span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-comment">// Initialize sensor hardware</span>
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* control_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + CONTROL_REG_OFFSET);
    *control_reg = <span class="hljs-number">0x01</span>; <span class="hljs-comment">// Enable sensor</span>
}

<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* temp_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + TEMP_REG_OFFSET);
    <span class="hljs-keyword">return</span> *temp_reg;
}

<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* humidity_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + HUMIDITY_REG_OFFSET);
    <span class="hljs-keyword">return</span> *humidity_reg;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-keyword">uint32_t</span> milliseconds)</span> </span>{
    <span class="hljs-comment">// Simple delay implementation</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">uint32_t</span> i = <span class="hljs-number">0</span>; i &lt; milliseconds * <span class="hljs-number">1000</span>; i++) {
        __asm__(<span class="hljs-string">"nop"</span>);
    }
}
</code></pre>
<h3 id="heading-swift-code-using-c-driver">Swift Code Using C Driver:</h3>
<p>To use these C functions from Swift, you declare them using <code>@_silgen_name</code>, which tells the Swift compiler to link directly to these symbol names at runtime.</p>
<p>The <code>SensorController</code> class encapsulates sensor-related logic. In its <code>init()</code> method, it calls the <code>sensor_init()</code> function defined in C to initialize the sensor hardware.</p>
<p>The <code>readSensors()</code> method reads the raw values from the C driver, converts them into human-readable units using helper functions, stores them internally, and returns the processed values.</p>
<p>The <code>convertTemperature()</code> and <code>convertHumidity()</code> conversion methods apply a basic linear formula to turn raw ADC values into temperature in Celsius and humidity in percentage, respectively. These formulas would be based on the specific sensor’s datasheet.</p>
<p>The <code>checkThresholds()</code> method applies simple threshold logic, a good example of where Swift’s readability and type safety shine. You could easily expand this logic to include error bounds, state machines, or alerts.</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Import C driver functions</span>

<span class="hljs-comment">/*
These declarations match the C function signatures exactly. 
They allow Swift to invoke the C functions as if they were native Swift functions 
— with zero overhead.
*/</span>
@_silgen_name(<span class="hljs-string">"sensor_init"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">()</span></span>

@_silgen_name(<span class="hljs-string">"sensor_read_temperature"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UInt32</span>

@_silgen_name(<span class="hljs-string">"sensor_read_humidity"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UInt32</span>

@_silgen_name(<span class="hljs-string">"sensor_delay_ms"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-number">_</span> ms: UInt32)</span></span>

<span class="hljs-comment">// Swift sensor controller using C driver</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SensorController</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> lastTemperature: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> lastHumidity: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>

    <span class="hljs-keyword">init</span>() {
        <span class="hljs-comment">// Initialize the C driver</span>
        sensor_init()
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readSensors</span><span class="hljs-params">()</span></span> -&gt; (temperature: <span class="hljs-type">Float</span>, humidity: <span class="hljs-type">Float</span>) {
        <span class="hljs-comment">// Read raw values from C driver</span>
        <span class="hljs-keyword">let</span> rawTemp = sensor_read_temperature()
        <span class="hljs-keyword">let</span> rawHumidity = sensor_read_humidity()

        <span class="hljs-comment">// Convert raw values to meaningful units in Swift</span>
        <span class="hljs-keyword">let</span> temperature = convertTemperature(rawValue: rawTemp)
        <span class="hljs-keyword">let</span> humidity = convertHumidity(rawValue: rawHumidity)

        <span class="hljs-comment">// Store for comparison</span>
        lastTemperature = temperature
        lastHumidity = humidity

        <span class="hljs-keyword">return</span> (temperature: temperature, humidity: humidity)
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">convertTemperature</span><span class="hljs-params">(rawValue: UInt32)</span></span> -&gt; <span class="hljs-type">Float</span> {
        <span class="hljs-comment">// Convert raw ADC value to Celsius</span>
        <span class="hljs-keyword">return</span> (<span class="hljs-type">Float</span>(rawValue) * <span class="hljs-number">3.3</span> / <span class="hljs-number">4095.0</span> - <span class="hljs-number">0.5</span>) * <span class="hljs-number">100.0</span>
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">convertHumidity</span><span class="hljs-params">(rawValue: UInt32)</span></span> -&gt; <span class="hljs-type">Float</span> {
        <span class="hljs-comment">// Convert raw ADC value to percentage</span>
        <span class="hljs-keyword">return</span> <span class="hljs-type">Float</span>(rawValue) * <span class="hljs-number">100.0</span> / <span class="hljs-number">4095.0</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">checkThresholds</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Bool</span> {
        <span class="hljs-comment">// Swift logic for threshold checking</span>
        <span class="hljs-keyword">let</span> tempThreshold: <span class="hljs-type">Float</span> = <span class="hljs-number">25.0</span>
        <span class="hljs-keyword">let</span> humidityThreshold: <span class="hljs-type">Float</span> = <span class="hljs-number">60.0</span>

        <span class="hljs-keyword">return</span> lastTemperature &gt; tempThreshold || lastHumidity &gt; humidityThreshold
    }
}

<span class="hljs-comment">// Main application loop</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Never</span> {
    <span class="hljs-keyword">let</span> sensorController = <span class="hljs-type">SensorController</span>()

    <span class="hljs-keyword">while</span> <span class="hljs-literal">true</span> {
        <span class="hljs-comment">// Read sensors using Swift controller with C driver</span>
        <span class="hljs-keyword">let</span> readings = sensorController.readSensors()

        <span class="hljs-comment">// Process data with Swift's type safety and expressiveness</span>
        <span class="hljs-keyword">if</span> sensorController.checkThresholds() {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"Warning: Temperature: \(readings.temperature)°C, Humidity: \(readings.humidity)%"</span>)
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"Normal: Temperature: \(readings.temperature)°C, Humidity: \(readings.humidity)%"</span>)
        }

        <span class="hljs-comment">// Delay using C driver function</span>
        sensor_delay_ms(<span class="hljs-number">1000</span>) <span class="hljs-comment">// 1 second delay</span>
    }
}
</code></pre>
<p>The <code>func main()</code> is the main event loop standard for embedded systems. It creates the sensor controller, reads sensor data in a loop, checks thresholds, and prints results accordingly. The loop includes a delay (via the C driver) to avoid hammering the sensor continuously.</p>
<p>In an actual embedded context, instead of using <code>print()</code>, you might blink an LED, send UART messages, or log data to memory.</p>
<p>With Embedded Swift and C now working together, let’s explore what lies ahead. The next section outlines ongoing improvements, emerging use cases, and research directions that are shaping the future of Embedded Swift.</p>
<h2 id="heading-future-work">Future Work</h2>
<p>Embedded Swift is still a young but rapidly evolving technology. Its modern language features, type safety, and performance make it an attractive option for embedded development, and ongoing work is expanding its capabilities, reach, and ecosystem.</p>
<h3 id="heading-ongoing-improvements">Ongoing Improvements</h3>
<p><strong>Compiler Optimizations</strong>: The Swift compiler team is actively improving code generation for embedded targets, including:</p>
<ul>
<li><p>Reducing binary size</p>
</li>
<li><p>Minimizing ARC overhead</p>
</li>
<li><p>Improving static dispatch performance</p>
</li>
</ul>
<p><strong>Hardware Support</strong>: Embedded Swift can target a wide variety of ARM and RISC-V microcontrollers, which are popular for building industrial applications. Support for additional architectures is being developed.</p>
<p><strong>Tooling Enhancements</strong>: Tooling support for Embedded Swift is still evolving, but several community-driven and open-source efforts are making development more accessible:</p>
<ul>
<li><p><strong>Build Systems</strong>: The Swift Embedded Working Group provides example projects that adapt Swift Package Manager (SwiftPM) for cross-compilation. Custom linker scripts and build helpers are available for platforms like STM32 and nRF52.</p>
</li>
<li><p><strong>Debugging Support</strong>: Developers can debug Embedded Swift programs using existing tools like GDB or OpenOCD, provided the build includes appropriate debug symbols. While not yet officially streamlined, this approach enables step-through debugging on real hardware.</p>
</li>
<li><p><strong>IDE Integration</strong>: There is no official IDE support yet, but some developers use VSCode with Swift syntax highlighting and external build tasks. These setups are still manual but serve as early prototypes for embedded workflows.</p>
</li>
</ul>
<h3 id="heading-emerging-use-cases">Emerging Use Cases</h3>
<p>There are a number of emerging use cases for embedded Swift. For example, Swift’s memory safety, type guarantees, and protocol-oriented design make it ideal for secure and scalable IoT devices, especially where firmware bugs could affect user safety or privacy.</p>
<p>The automotive sector is also exploring Swift for infotainment systems, driver assistance features, and safety-critical logic (where deterministic execution and safety matter).</p>
<p>Swift’s expressive syntax and compile-time safety make it suitable for industrial automation – think real-time control loops, sensor fusion systems, and edge devices in smart manufacturing.</p>
<p>It’s also useful for medical devices, as it aligns well with strict medical regulations around memory safety, type guarantees, and predictable resource usage.</p>
<h3 id="heading-community-and-ecosystem">Community and Ecosystem</h3>
<h4 id="heading-open-source-projects">Open Source Projects</h4>
<p>The Swift Embedded working group maintains <a target="_blank" href="https://github.com/swiftlang/swift-embedded-examples">example repositories</a> showcasing how to use Embedded Swift on microcontrollers such as STM32, nRF52, and ESP32. Early-stage libraries for UART, GPIO, and basic peripherals are emerging, though the ecosystem is still young compared to C or Rust.</p>
<h4 id="heading-learning-resources">Learning Resources</h4>
<p>While <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded">Embedded Swift</a> is not yet widely taught in formal curricula, community tutorials and exploratory projects (for example, Swift for Arduino) are lowering the barrier for hobbyists and independent learners. As tooling matures, educational adoption is likely to follow.</p>
<h4 id="heading-industry-interest">Industry Interest</h4>
<p>Embedded Swift is beginning to draw attention from developers and companies looking for safer, more maintainable alternatives to C. Although large-scale adoption remains limited, use cases like rapid prototyping, IoT development, and internal experimentation are gaining traction.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Embedded Swift represents a major step forward in embedded programming. By combining the power and safety of Swift with the low-level control needed for microcontrollers, it offers an exciting alternative to traditional C and C++ development.</p>
<p>While C will remain essential for hardware-level programming and performance-critical paths, Swift brings compelling advantages to many embedded scenarios:</p>
<ul>
<li><p><strong>Memory safety</strong>: Swift eliminates entire categories of bugs such as buffer overflows, use-after-free, and null pointer dereferencing.</p>
</li>
<li><p><strong>Type safety</strong>: Many logic errors are caught at compile time, long before they can cause runtime failures.</p>
</li>
<li><p><strong>Modern language features</strong>: Developers can use functional paradigms, generics, and protocol-oriented design even in embedded code.</p>
</li>
<li><p><strong>C interoperability</strong>: Swift works seamlessly with existing C libraries, allowing gradual adoption without rewriting low-level drivers.</p>
</li>
<li><p><strong>Developer productivity</strong>: Clear syntax, automatic memory management, and strong tooling lead to faster development and easier maintenance.</p>
</li>
</ul>
<p>Government and regulatory bodies are increasingly encouraging or mandating the use of memory-safe programming languages to reduce vulnerabilities in critical software systems. For example:</p>
<ul>
<li><p>In 2022, the <a target="_blank" href="https://media.defense.gov/2025/Jun/23/2003742198/-1/-1/0/CSI_MEMORY_SAFE_LANGUAGES_REDUCING_VULNERABILITIES_IN_MODERN_SOFTWARE_DEVELOPMENT.PDF"><strong>U.S. National Security Agency (NSA)</strong></a> recommended moving away from unsafe languages like C/C++ for new software projects, promoting memory-safe alternatives.</p>
</li>
<li><p>In June 2025, the NSA and CISA released a joint Cybersecurity Information Sheet titled “<a target="_blank" href="https://www.nsa.gov/Press-Room/Press-Releases-Statements/Press-Release-View/Article/4223298/nsa-and-cisa-release-csi-highlighting-importance-of-memory-safe-languages-in-so/">Memory Safe Languages: Reducing Vulnerabilities in Modern Software Development</a>”, which emphasized that memory safety flaws remain a persistent risk, and organizations should develop strategies to adopt memory-safe programming languages in new systems.</p>
</li>
<li><p>The <a target="_blank" href="https://www.trust-in-soft.com/resources/blogs/memory-safety-is-key-the-shift-in-u.s.-cyber-standards"><strong>U.S. Cybersecurity and Infrastructure Security Agency (CISA)</strong></a> and <a target="_blank" href="https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-218.pdf"><strong>NIST</strong></a> have echoed similar guidance in the context of national cybersecurity.</p>
</li>
</ul>
<p>While these documents do not mention Swift explicitly, Swift's strong type system, ARC-based memory model, and compile-time safety guarantees align closely with the goals outlined in these recommendations. As such, it offers a practical, developer-friendly path toward safer embedded development.</p>
<p>Swift may not be the right fit for every embedded system. In applications where every byte of memory or instruction cycle is critical, real-time guarantees are hard requirements, or toolchain maturity is essential (for example, RTOS integration, static analyzers), C or Rust may still be preferred.</p>
<p>But in many modern embedded applications, especially those involving rapid prototyping, fast product iteration, safety-critical or maintainable firmware, and interoperability with existing C codebases, Swift offers a highly productive and safe development experience.</p>
<p>Embedded Swift is still maturing, but its momentum is undeniable. With ongoing compiler work, community-driven examples, and growing interest from developers, it’s poised to play a major role in the future of embedded systems.</p>
<p>Whether you're building an IoT device, a piece of industrial equipment, or a proof-of-concept wearable, Swift can help you write safer, more expressive firmware, without giving up performance or control.</p>
<p>Swift can be especially powerful during the prototyping phase, when the primary goal is to validate functionality quickly and safely. And with its increasing support for multiple hardware platforms, it offers a strong foundation for bringing modern software development practices to the embedded world.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Understanding the Language Server Protocol – Easier Code Editing Across Languages and Tools ]]>
                </title>
                <description>
                    <![CDATA[ In the past, many code editors were built just for one specific language. To provide rich and smart code editing, tight integration between the editor and the language tooling was a must. On the other hand, there were (and still are) more general-pur... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-the-language-server-protocol-easier-code-editing-across-languages/</link>
                <guid isPermaLink="false">677ef3f83b47b21899e957c4</guid>
                
                    <category>
                        <![CDATA[ Language Server Protocol ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ lsp ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Alex Pliutau ]]>
                </dc:creator>
                <pubDate>Wed, 08 Jan 2025 21:54:00 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736371728078/f1da2e66-4095-44e6-bcdf-de44c92e81ad.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the past, many code editors were built just for one specific language. To provide rich and smart code editing, tight integration between the editor and the language tooling was a must.</p>
<p>On the other hand, there were (and still are) more general-purpose editors, but they lacked in functionality when it came to more advanced language-specific features like code completion, “go to definition”, and so on. As an example, code highlighting was done using regular expressions.</p>
<p>With the growing number of code editors and programming languages available, this became the classic <strong>M*N</strong> complexity problem.</p>
<p>But then Microsoft introduced the <a target="_blank" href="https://microsoft.github.io/language-server-protocol/">Language Server Protocol</a> (LSP) as a solution to the problem above, which elegantly transforms this <strong>M*N</strong> complexity into a more manageable <strong>M+N</strong> situation.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-microsoft-created-the-lsp">Why Microsoft Created the LSP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-language-server-protocol-lsp">What is the Language Server Protocol (LSP)?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-language-server-features">Language Server Features</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-lsp-work">How Does LSP Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-language-server-for-go">Language Server for Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-lsp-adoption">LSP Adoption</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-resources">Resources</a></p>
</li>
</ul>
<h2 id="heading-why-microsoft-created-the-lsp">Why Microsoft Created the LSP</h2>
<p>The LSP was initially driven by the needs of VS Code. VS Code had to work with hundreds of different Language Servers as part of its extensions. But there were multiple problems:</p>
<ul>
<li><p><strong>Language mismatch</strong>: Language Servers are often written in different languages than the editor (like VS Code's Node.js).</p>
</li>
<li><p><strong>Performance impact</strong>: Language features can be resource-intensive, potentially slowing down the editor.</p>
</li>
<li><p><strong>Integration complexity</strong>: Multiple editors and multiple languages introduces the <strong>M*N</strong> complexity mentioned above.</p>
</li>
</ul>
<p>Exactly because of that, Microsoft introduced LSP to standardize the communication between language tools and editors, allowing language servers to be written in any language, run separately for better performance, and easily integrate with any LSP-compliant editor. This simplifies language support for both tool providers and editor vendors.</p>
<p>You can find more info in this <a target="_blank" href="https://code.visualstudio.com/api/language-extensions/language-server-extension-guide">Language Server Extension Guide</a>.</p>
<h2 id="heading-what-is-the-language-server-protocol-lsp">What is the Language Server Protocol (LSP)?</h2>
<p>The LSP separates language servers from code editors (language clients). By making language servers independent processes dedicated to language understanding, the LSP enables any editor to utilize a standard language server. This means that a single standard language server can be used by all editors.</p>
<p>This interoperability is achieved through a defined set of standard messages and procedures that govern communication between language servers and editors. The LSP defines the format of the messages sent using JSON-RPC between the development tool and the language server.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/0*Vdycq7316e_hKTCe.png" alt="Communication between the editor and the Language Server" width="700" height="265" loading="lazy"></p>
<h2 id="heading-language-server-features"><strong>Language Server Features</strong></h2>
<p>The list of features may vary for each individual language server, but usually they provide the following functionalities:</p>
<ul>
<li><p>Auto-completion</p>
</li>
<li><p>Go to definition/declaration</p>
</li>
<li><p>Find references</p>
</li>
<li><p>Code formatting</p>
</li>
<li><p>Diagnostics</p>
</li>
<li><p>Documentation</p>
</li>
</ul>
<p>And more.</p>
<p>For example, <a target="_blank" href="https://github.com/golang/tools/blob/master/gopls/doc/features/README.md">here</a> you can see the list of editor features that <strong>gopls</strong> (the Go Language Server) provides.</p>
<p>And <a target="_blank" href="https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#languageFeatures">here</a> you can see the full LSP specification for available features.</p>
<p>There are hundreds of Language Servers out there. Typically, every mature programming language (or markup language) has at least one Language Server. You can see the full list of language servers that implement LSP <a target="_blank" href="https://microsoft.github.io/language-server-protocol/implementors/servers/">here</a>.</p>
<h2 id="heading-how-does-lsp-work"><strong>How Does LSP Work?</strong></h2>
<p>The Language Server Protocol is built upon <a target="_blank" href="https://www.jsonrpc.org/">JSON-RPC</a>. It specifically uses JSON RPC 2.0. You can think of JSON-RPC as a remote procedure call protocol that uses JSON for data encoding.</p>
<p>In a nutshell, it works like this. First, the editor establishes a connection with the language server. Then as the developer types code, the editor sends incremental changes to the language server. It then sends back insights like code completion suggestions and diagnostics.</p>
<p>Let’s see one real example for auto-completion. The request from the Language Client (editor) for this case will be:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"jsonrpc"</span>: <span class="hljs-string">"2.0"</span>,
  <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">"method"</span>: <span class="hljs-string">"textDocument/completion"</span>,
  <span class="hljs-attr">"params"</span>: {
    <span class="hljs-attr">"textDocument"</span>: {
      <span class="hljs-attr">"uri"</span>: <span class="hljs-string">"file:///home/alex/code/test/main.go"</span>
    },
    <span class="hljs-attr">"position"</span>: {
      <span class="hljs-attr">"line"</span>: <span class="hljs-number">35</span>,
      <span class="hljs-attr">"character"</span>: <span class="hljs-number">21</span>
    }
  }
}
</code></pre>
<p>As you can see, it sends the information about current cursor position and the buffer file. Let’s break it down:</p>
<ul>
<li><p><strong>ID</strong>: The client sets this field to identify the request uniquely. Once the request is processed, it will return a response with the same request ID so that the client can match which response is for what request.</p>
</li>
<li><p><strong>Method</strong>: A string containing the name of the method to be invoked.</p>
</li>
<li><p><strong>Params</strong>: The parameters to be passed to the method. This can be structured as an array or an object.</p>
</li>
</ul>
<p>Language server can access this file, analyze it, and respond with suggestions:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"jsonrpc"</span>: <span class="hljs-string">"2.0"</span>,
  <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">"result"</span>: {
    <span class="hljs-attr">"isIncomplete"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"items"</span>: [
      {
        <span class="hljs-attr">"label"</span>: <span class="hljs-string">"Println"</span>,
        <span class="hljs-attr">"kind"</span>: <span class="hljs-number">3</span>,
        <span class="hljs-attr">"insertText"</span>: <span class="hljs-string">"Println(${1:format}, ${2:a ...interface{}})$0"</span>,
        <span class="hljs-attr">"insertTextFormat"</span>: <span class="hljs-number">2</span>,
        <span class="hljs-attr">"detail"</span>: <span class="hljs-string">"func Println(a ...interface{}) (n int, err error)"</span>,
        <span class="hljs-attr">"documentation"</span>: <span class="hljs-string">"Println formats ..."</span>
      },
      <span class="hljs-comment">// ... other items</span>
    ]
  }
}
</code></pre>
<h2 id="heading-language-server-for-go"><strong>Language Server for Go</strong></h2>
<p>The most popular and commonly used language server for Go is <a target="_blank" href="https://github.com/golang/tools/tree/master/gopls">gopls</a>. It is used by many editors, for example by the <a target="_blank" href="https://github.com/golang/vscode-go">Visual Studio Code Go extension</a>. Previously, there was another popular Language Server for Go by the Sourcegraph team called <a target="_blank" href="https://github.com/sourcegraph/go-langserver">go-langserver</a>, but this is no longer under active maintenance.</p>
<p>Many editors install gopls Language Server automatically if it’s not present on the host machine. But you can install it manually as well:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># check if its' installed and which version</span>
gopls version
<span class="hljs-comment"># golang.org/x/tools/gopls v0.16.2</span>

<span class="hljs-comment"># install or upgrade</span>
go install golang.org/x/tools/gopls@latest
</code></pre>
<p>gopls also provides an experimental CLI interface:</p>
<pre><code class="lang-bash">gopls references ./main.go:35:8
</code></pre>
<h2 id="heading-lsp-adoption"><strong>LSP Adoption</strong></h2>
<p>The trend is definitely towards LSP adoption. Many editors that didn't initially support it are adding LSP capabilities due to its benefits.</p>
<p>But it's important to note that not all editors use LSP. Classic editors like <strong>Vi</strong>, <strong>Vim</strong> (in its basic configuration), and <strong>emacs</strong> (without specific plugins) traditionally rely on simpler methods for language support, such as syntax highlighting based on regular expressions.</p>
<p>Also, when your editor uses a Language Server, it can have a noticeable impact on CPU and memory, especially for large projects or complex languages. The good news is that you can choose a more efficient language server or disable them in your editor.</p>
<p>Here is how I can inspect what language servers my <a target="_blank" href="https://zed.dev/">Zed</a> editor is currently running:</p>
<pre><code class="lang-bash">ps aux | grep language-server

node yaml-language-server --stdio
node tailwindcss-language-server --stdio
...
</code></pre>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Thanks to the Language Server Protocol, advanced coding capabilities are becoming universally accessible across various programming languages and coding environments.</p>
<p>It’s good to know how your code editors work, so it’s beneficial to have an understanding of this widely used technology called LSP. In short, LSP knowledge helps you understand and better utilize modern coding tools.</p>
<p>LSP is a win for both language providers and tooling vendors.</p>
<h3 id="heading-resources"><strong>Resources</strong></h3>
<ul>
<li><p><a target="_blank" href="https://microsoft.github.io/language-server-protocol/">Language Server Protocol</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/golang/tools/tree/master/gopls">gopls</a></p>
</li>
<li><p>Discover more articles on <a target="_blank" href="https://packagemain.tech/">packagemain.tech</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python’s zip() Function Explained with Simple Examples ]]>
                </title>
                <description>
                    <![CDATA[ The zip() function in Python is a neat tool that allows you to combine multiple lists or other iterables (like tuples, sets, or even strings) into one iterable of tuples. Think of it like a zipper on a jacket that brings two sides together. In this g... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-zip-function-explained-with-examples/</link>
                <guid isPermaLink="false">6707eb818bd3718987eac606</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python 3 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ python beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sahil ]]>
                </dc:creator>
                <pubDate>Thu, 10 Oct 2024 14:58:09 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728351007032/90a321bb-4079-4480-90e7-7aa847c54d9d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The <code>zip()</code> function in Python is a neat tool that allows you to combine multiple lists or other iterables (like tuples, sets, or even strings) into one iterable of tuples. Think of it like a zipper on a jacket that brings two sides together.</p>
<p>In this guide, we’ll explore the ins and outs of the <code>zip()</code> function with simple, practical examples that will help you understand how to use it effectively.</p>
<h2 id="heading-how-does-the-zip-function-work">How Does the <code>zip()</code> Function Work?</h2>
<p>The <code>zip()</code> function pairs elements from multiple iterables, like lists, based on their positions. This means that the first elements of each list will be paired, then the second, and so on. If the iterables are not the same length, <code>zip()</code> will stop at the end of the shortest iterable.</p>
<p>The syntax for <code>zip()</code> is pretty straightforward:</p>
<pre><code class="lang-python">zip(*iterables)
</code></pre>
<p>You can pass in multiple iterables (lists, tuples, and so on), and it will combine them into tuples.</p>
<h3 id="heading-example-1-combining-two-lists">Example 1: Combining Two Lists</h3>
<p>Let’s start with a simple case where we have two lists, and we want to combine them. Imagine you have a list of names and a corresponding list of scores, and you want to pair them up.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Two lists to combine</span>
names = [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Charlie"</span>]
scores = [<span class="hljs-number">85</span>, <span class="hljs-number">90</span>, <span class="hljs-number">88</span>]

<span class="hljs-comment"># Using zip() to combine them</span>
zipped = zip(names, scores)

<span class="hljs-comment"># Convert the result to a list so we can see it</span>
zipped_list = list(zipped)
print(zipped_list)
</code></pre>
<p>In this example, the <code>zip()</code> function takes the two lists—<code>names</code> and <code>scores</code>—and pairs them element by element. The first element from <code>names</code> (<code>"Alice"</code>) is paired with the first element from <code>scores</code> (<code>85</code>), and so on. When we convert the result into a list, it looks like this:</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">[(<span class="hljs-string">'Alice'</span>, <span class="hljs-number">85</span>), (<span class="hljs-string">'Bob'</span>, <span class="hljs-number">90</span>), (<span class="hljs-string">'Charlie'</span>, <span class="hljs-number">88</span>)]
</code></pre>
<p>This makes it easy to work with related data in a structured way.</p>
<h3 id="heading-example-2-what-happens-when-the-lists-are-uneven">Example 2: What Happens When the Lists Are Uneven?</h3>
<p>Let’s say you have lists of different lengths. What happens then? The <code>zip()</code> function is smart enough to stop as soon as it reaches the end of the shortest list.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Lists of different lengths</span>
fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>]
prices = [<span class="hljs-number">100</span>, <span class="hljs-number">200</span>, <span class="hljs-number">150</span>]

<span class="hljs-comment"># Zipping them together</span>
result = list(zip(fruits, prices))
print(result)
</code></pre>
<p>In this case, the <code>fruits</code> list has two elements, and the <code>prices</code> list has three. But <code>zip()</code> will only combine the first two elements, ignoring the extra value in <code>prices</code>.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">[(<span class="hljs-string">'apple'</span>, <span class="hljs-number">100</span>), (<span class="hljs-string">'banana'</span>, <span class="hljs-number">200</span>)]
</code></pre>
<p>Notice how the last value (<code>150</code>) in the <code>prices</code> list is ignored because there’s no third fruit to pair it with. The <code>zip()</code> function ensures that you don’t get errors when working with uneven lists, but it also means you might lose some data if your lists are not balanced.</p>
<h3 id="heading-example-3-unzipping-a-zipped-object">Example 3: Unzipping a Zipped Object</h3>
<p>What if you want to reverse the <code>zip()</code> operation? For example, after zipping two lists together, you might want to split them back into individual lists. You can do this easily using the unpacking operator <code>*</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Zipped lists</span>
cities = [<span class="hljs-string">"New York"</span>, <span class="hljs-string">"London"</span>, <span class="hljs-string">"Tokyo"</span>]
populations = [<span class="hljs-number">8000000</span>, <span class="hljs-number">9000000</span>, <span class="hljs-number">14000000</span>]

zipped = zip(cities, populations)

<span class="hljs-comment"># Unzipping them</span>
unzipped_cities, unzipped_populations = zip(*zipped)

print(unzipped_cities)
print(unzipped_populations)
</code></pre>
<p>Here, we first zip the <code>cities</code> and <code>populations</code> lists together. Then, using <code>zip(*zipped)</code>, we can "unzip" the combined tuples back into two separate lists. The <code>*</code> operator unpacks the zipped tuples into their original components.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">(<span class="hljs-string">'New York'</span>, <span class="hljs-string">'London'</span>, <span class="hljs-string">'Tokyo'</span>)
(<span class="hljs-number">8000000</span>, <span class="hljs-number">9000000</span>, <span class="hljs-number">14000000</span>)
</code></pre>
<p>This shows how you can reverse the zipping process to get the original data back.</p>
<h3 id="heading-example-4-zipping-more-than-two-lists">Example 4: Zipping More Than Two Lists</h3>
<p>You aren’t limited to just two lists with <code>zip()</code>. You can zip together as many iterables as you want. Here’s an example with three lists.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Three lists to zip</span>
subjects = [<span class="hljs-string">"Math"</span>, <span class="hljs-string">"English"</span>, <span class="hljs-string">"Science"</span>]
grades = [<span class="hljs-number">88</span>, <span class="hljs-number">79</span>, <span class="hljs-number">92</span>]
teachers = [<span class="hljs-string">"Mr. Smith"</span>, <span class="hljs-string">"Ms. Johnson"</span>, <span class="hljs-string">"Mrs. Lee"</span>]

<span class="hljs-comment"># Zipping three lists together</span>
zipped_info = zip(subjects, grades, teachers)

<span class="hljs-comment"># Convert to a list to see the result</span>
print(list(zipped_info))
</code></pre>
<p>In this example, we are zipping three lists—<code>subjects</code>, <code>grades</code>, and <code>teachers</code>. The first item from each list is grouped together, then the second, and so on.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">[(<span class="hljs-string">'Math'</span>, <span class="hljs-number">88</span>, <span class="hljs-string">'Mr. Smith'</span>), (<span class="hljs-string">'English'</span>, <span class="hljs-number">79</span>, <span class="hljs-string">'Ms. Johnson'</span>), (<span class="hljs-string">'Science'</span>, <span class="hljs-number">92</span>, <span class="hljs-string">'Mrs. Lee'</span>)]
</code></pre>
<p>This way, you can combine multiple related pieces of information into easy-to-handle tuples.</p>
<h3 id="heading-example-5-zipping-strings">Example 5: Zipping Strings</h3>
<p>Strings are also iterables in Python, so you can zip over them just like you would with lists. Let’s try combining two strings.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Zipping two strings</span>
str1 = <span class="hljs-string">"ABC"</span>
str2 = <span class="hljs-string">"123"</span>

<span class="hljs-comment"># Zipping the characters together</span>
zipped_strings = list(zip(str1, str2))
print(zipped_strings)
</code></pre>
<p>Here, the first character of <code>str1</code> is combined with the first character of <code>str2</code>, and so on.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">[(<span class="hljs-string">'A'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'B'</span>, <span class="hljs-string">'2'</span>), (<span class="hljs-string">'C'</span>, <span class="hljs-string">'3'</span>)]
</code></pre>
<p>This is especially useful if you need to process or pair characters from multiple strings together.</p>
<h3 id="heading-example-6-zipping-dictionaries">Example 6: Zipping Dictionaries</h3>
<p>Although dictionaries are slightly different from lists, you can still use <code>zip()</code> to combine them. By default, <code>zip()</code> will only zip the dictionary keys. Let’s look at an example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Two dictionaries</span>
dict1 = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">25</span><span class="hljs-string">"}
dict2 = {"</span>name<span class="hljs-string">": "</span>Bo<span class="hljs-string">b", "</span>age<span class="hljs-string">": 30"</span>}

<span class="hljs-comment"># Zipping dictionary keys</span>
zipped_keys = list(zip(dict1, dict2))
print(zipped_keys)
</code></pre>
<p>Here, <code>zip()</code> pairs up the keys from both dictionaries.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">[(<span class="hljs-string">'name'</span>, <span class="hljs-string">'name'</span>), (<span class="hljs-string">'age'</span>, <span class="hljs-string">'age'</span>)]
</code></pre>
<p>If you want to zip the values of the dictionaries, you can do that using the <code>.values()</code> method:</p>
<pre><code class="lang-python">zipped_values = list(zip(dict1.values(), dict2.values()))
print(zipped_values)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">[(<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>), (<span class="hljs-number">25</span>, <span class="hljs-number">30</span>)]
</code></pre>
<p>Now you can easily combine the values of the two dictionaries.</p>
<h3 id="heading-example-7-using-zip-in-loops">Example 7: Using <code>zip()</code> in Loops</h3>
<p>One of the most common uses of <code>zip()</code> is in loops when you want to process multiple lists at the same time. Here’s an example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Lists of names and scores</span>
names = [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Charlie"</span>]
scores = [<span class="hljs-number">85</span>, <span class="hljs-number">90</span>, <span class="hljs-number">88</span>]

<span class="hljs-comment"># Using zip() in a loop</span>
<span class="hljs-keyword">for</span> name, score <span class="hljs-keyword">in</span> zip(names, scores):
    print(<span class="hljs-string">f"<span class="hljs-subst">{name}</span> scored <span class="hljs-subst">{score}</span>"</span>)
</code></pre>
<p>This loop iterates over both the <code>names</code> and <code>scores</code> lists simultaneously, pairing up each name with its corresponding score.</p>
<p><strong>Output:</strong></p>
<pre><code class="lang-python">Alice scored <span class="hljs-number">85</span>
Bob scored <span class="hljs-number">90</span>
Charlie scored <span class="hljs-number">88</span>
</code></pre>
<p>Using <code>zip()</code> in loops like this makes your code cleaner and easier to read when working with related data.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The <code>zip()</code> function is a handy tool in Python that lets you combine multiple iterables into tuples, making it easier to work with related data. Whether you're pairing up items from lists, tuples, or strings, <code>zip()</code> simplifies your code and can be especially useful in loops.</p>
<p>With the examples in this article, you should now have a good understanding of how to use <code>zip()</code> in various scenarios.</p>
<p>If you found this explanation of Python's <code>zip()</code> function helpful, you might also enjoy more in-depth programming tutorials and concepts I cover on my <a target="_blank" href="https://blog.theenthusiast.dev">blog</a>.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Programming Language Should I Learn First in 2024? [Solved] ]]>
                </title>
                <description>
                    <![CDATA[ Most people’s journey toward learning to program starts with a single late-night Google search. Usually it’s something like “Learn ______” But how do they decide which language to search for? “They always joke about Java on Silicon Valley. I guess I... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-programming-language-should-i-learn-first-19a33b0a467d/</link>
                <guid isPermaLink="false">66b8d69b2755c964523f0549</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Larson ]]>
                </dc:creator>
                <pubDate>Fri, 24 Nov 2023 08:17:00 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*1XEF9NuNQy0rSu4kVdbb6A.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most people’s journey toward learning to program starts with a single late-night Google search.</p>
<p>Usually it’s something like “Learn ______”</p>
<p>But how do they decide which language to search for?</p>
<blockquote>
<p>“They always joke about Java on Silicon Valley. I guess I should learn that.”</p>
</blockquote>
<p>Or:</p>
<blockquote>
<p>“Haskell. So hot right now. Haskell.”</p>
</blockquote>
<p>Or:</p>
<blockquote>
<p>“That Go gopher is just so gosh-darn cute.”</p>
</blockquote>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*7kbd-tVk3co-9RiilFN1TA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And then there’s the rest of us. We’ll probably search for something like:</p>
<blockquote>
<p>“Which programming language should I learn first?”</p>
</blockquote>
<p>Few questions are so commonly asked that they get the full infographic treatment. But this is one of them:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*OF594B5qtCJR9MFSRTI-5g.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_[Image credit](http://carlcheo.com/startcoding" rel="noopener" target="<em>blank" title=")</em></p>
<p>Deciding on your first programming language can be a fun process — kind of like one of those “Which Quentin Tarantino character are you?” personality quizzes.</p>
<p>But before you run off to learn Ruby because you enjoyed playing with Play-Doh as a kid, let me remind you: the stakes are pretty high here.</p>
<p>It will take you hundreds of hours of practice to become even remotely competent with your first programming language.</p>
<p>So you should consider the following factors:</p>
<ul>
<li><p>the job market for the language</p>
</li>
<li><p>the long term prospects for the language</p>
</li>
<li><p>how easy the language is to learn</p>
</li>
<li><p>what projects you can build while you’re learning (and share with friends so you can stay motivated)</p>
</li>
</ul>
<p>Every year brings new programming languages, and with them, new academic papers. And new web comics.</p>
<p>Seriously. Check out this gem from last month:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*she624Vf-hrpgLdWd8hKKw.jpeg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When it comes to choosing a first programming language, there’s no shortage of options. To narrow it down a bit, here are the most common Google searches related to learning programming, over the past 12 years:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*znaagCC5fn0-Dqy43ILeqQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Java has had its ups and downs.</p>
<p>Python has gradually risen to become the most popular choice.</p>
<p>But tucked away below these is the Little Engine That Could, slowly choo-choo’ing up in popularity over the past few years. And that engine is JavaScript.</p>
<p>Before I talk about these programming languages, let me clarify:</p>
<ul>
<li><p>I’m not arguing that any one language is objectively better than any other</p>
</li>
<li><p>I agree that developers should eventually learn more than one language</p>
</li>
<li><p>I’m arguing that first they should learn one language well. And — as you can probably guess from the upside down text in my headline — that language should be JavaScript.</p>
</li>
</ul>
<p>Let’s kick things off by exploring how programming is currently taught in school.</p>
<h3 id="heading-computer-science-101">Computer Science 101</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*eu4cWRZXUt3ybNFzeT-q8Q.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Universities have traditionally taught programming under the umbrella of computer science, which itself is often seen as an extension of mathematics, or tie-in to an electrical engineering degree.</p>
<p>Of course, as you may have heard by now:</p>
<blockquote>
<p>“Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.” — Eric S. Raymond</p>
</blockquote>
<p>Many universities still treat programming like it’s computer science, and computer science like it’s math.</p>
<p>As a result, many introductory programming courses focus on low-level-of-abstraction languages like C, or mathematically-focused languages like MATLAB.</p>
<p>And department chairs generally stay the course, pointing to annual programming language leaderboards like the <a target="_blank" href="http://www.tiobe.com/tiobe-index/">TIOBE Index</a>, or this one from the <a target="_blank" href="http://spectrum.ieee.org/computing/software/the-2016-top-programming-languages">IEEE</a>:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*8yWwh_UrWeoxYSVsWTnEBA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Most of these leaderboards look virtually identical to how they were 10 years ago.</p>
<p>But change does happen. Even in academia.</p>
<p>In 2014, Python <a target="_blank" href="http://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext">overtook Java</a> as a the most popular language of instruction at top US Computer Science programs.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*728HWv2YP3PjY1_QmGQg1g.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And yet another change is bound to… eventually… happen.</p>
<p>Because if you look at the languages actually used by the workforce, it paints a very different picture:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*fUxhG3xtbuyAH-NCPYs4lQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>JavaScript is by far the most popular language used by the 49,397 developers who responded to Stack Overflow’s Survey.</em></p>
<p>More than half of all developers use JavaScript. It’s vital to front-end web development and increasingly relevant for back-end development. And it’s rapidly expanding into areas like game development and the Internet of Things.</p>
<p>Job postings also mention JavaScript more than any programming language other than Java:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Nju6ZEORusBE-4UB290Ftw.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_Data from the world’s largest job posting aggregator, [Indeed.com](http://www.indeed.com/jobtrends/q-java-q-python-q-javascript-q-ruby-q-php-q-android-q-ios.html" rel="noopener" target="<em>blank" title=")</em></p>
<p>It’s no accident that we built our <a target="_blank" href="https://www.freecodecamp.com">open source community</a>’s curriculum around JavaScript. Over the past two years, more than 5,000 people have used Free Code Camp to get their first developer job.</p>
<p>I’m not advocating JavaScript because I teach it. I teach JavaScript because it’s the surest path to a first developer job.</p>
<p>But is JavaScript right for you? Is it worthy of being your first programming language? Let’s explore those factors I mentioned earlier.</p>
<h3 id="heading-factor-1-the-job-market">Factor #1: The job market</h3>
<p>If you’re learning to program purely out of intellectual curiosity, feel free to skip this factor. But if you — like the <a target="_blank" href="https://medium.freecodecamp.com/we-asked-15-000-people-who-they-are-and-how-theyre-learning-to-code-4104e29b2781#.30hlfqj32">vast majority of people learning to program</a> — want to use this skill to get a job, this is an important consideration.</p>
<p>As I mentioned earlier, Java is mentioned in more job postings than any other programming language. JavaScript is a close second.</p>
<p>But here’s the thing about JavaScript: even though it’s been around for 20 years, it only recently became a serious tool that companies like Netflix, Walmart, and PayPal would build entire applications around.</p>
<p>As a result, plenty of companies are hiring JavaScript developers, but there just aren’t that many on the job market.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*EanhlHoMIsF-By0gRrAcYQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_Data from [Indeed.com](http://www.indeed.com/jobtrends/q-java-q-python-q-javascript-q-ruby-q-php-q-android-q-ios.html" rel="noopener" target="<em>blank" title=")</em></p>
<p>There are 2.7 Java developers competing for every open Java position. Competition for PHP and iOS jobs is similarly fierce.</p>
<p>But for every open JavaScript position, there are only 0.6 JavaScript developers. It is very much a sellers’ market for developers with JavaScript skills.</p>
<h3 id="heading-factor-2-the-long-term-prospects">Factor #2: The long term prospects</h3>
<p>The average JavaScript project receives twice as many pull requests as the average Java, Python, or Ruby project. And on top of this, JavaScript is growing faster than any other popular language.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Cursor_and_The_top_programming_languages___The_State_of_the_Octoverse_--.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The most widely-used programming languages for GitHub projects, which is a good proxy for overall language popularity</em></p>
<p>JavaScript’s ecosystem also benefits from a heavy investment of money and engineering talent from companies like Google, Microsoft, Facebook, and Netflix.</p>
<p>For example, TypeScript (a statically-typed superset of JavaScript) has more than 100 open source contributors, many of whom are Microsoft and Google employees being paid to work on it.</p>
<p>This type of inter-company cooperation is harder to find with Java. Oracle — who effectively owns Java through its acquisition of Sun Microsystems — <a target="_blank" href="https://medium.freecodecamp.com/why-todays-victory-over-oracle-matters-so-much-to-developers-4e24b4a368b5#.pk8efc9um">often sues</a> companies who try to expand upon it.</p>
<h3 id="heading-factor-3-difficulty-to-learn">Factor #3: Difficulty to learn</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*d8TITW3skawGd-ioyHh2nQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_This is a parody of an [XKCD comic](https://xkcd.com/435/" rel="noopener" target="<em>blank" title=").</em></p>
<p>Most programmers would agree that high-level scripting languages are relatively easy to learn. JavaScript falls into this category, along with Python and Ruby.</p>
<p>Even though universities still teach languages like Java and C++ as first languages, they’re considerably harder to learn.</p>
<h3 id="heading-factor-4-projects-you-can-build-with-it">Factor #4: Projects you can build with it</h3>
<p>This is where JavaScript really shines. JavaScript runs on any device that has a browser, right there in the browser. You can build basically anything with JavaScript, and share it anywhere.</p>
<p>Because of JavaScript’s ubiquity, Stack Overflow co-founder Jeff Atwood coined his now-famous law:</p>
<blockquote>
<p>“Any application that <em>can</em> be written in JavaScript, <em>will</em> eventually be written in JavaScript.”</p>
</blockquote>
<p>And <a target="_blank" href="https://www.reddit.com/r/atwoodslaw/">with each passing month</a>, Atwood’s Law holds strong.</p>
<p>Java once promised to run everywhere, too. You may remember <a target="_blank" href="http://motherboard.vice.com/read/a-brief-history-of-the-java-applet">Java Applets</a>. Oracle officially killed them off earlier this year.</p>
<p>Python suffers from much the same problems:</p>
<blockquote>
<p>“How can I give this game I made to my friend? Even better, is there a way can I put this on my phone so I can show it to kids at school without them having to install it? Um.” — James Hague in <a target="_blank" href="http://prog21.dadgum.com/203.html">Retiring Python as a Teaching Language</a></p>
</blockquote>
<p>By contrast, here are some apps that members of our open source community built in their browsers on CodePen. You can click through and use these right in your browser:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/1_GtVQI4LUU0-_Soyhi93LBg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://codepen.io/safx/pen/abvNbv"><em>Conway's Game of Life</em></a></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/1_i-bre5pF0rk6Wgz5yjugjw.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://codepen.io/adambeagle/pen/qOamaz"><em>1970s-style Simon game</em></a></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/1_jkx-Vf8esZ0GYv_L6S2i9A.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Star Wars-themed Wikipedia Search</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/1_PiI9yXaUNJANSffWvdotDQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://codepen.io/Megabyteceer/pen/qbXJMQ"><em>A rougelike dungeon crawler game</em></a></p>
<h3 id="heading-learn-one-language-well-then-learn-a-second-one">Learn one language well. Then learn a second one.</h3>
<p>If you keep jumping from language to language, <a target="_blank" href="https://medium.freecodecamp.com/a-cautionary-tale-of-learning-to-code-my-own-eddb24d9d5a7">you won’t get far</a>.</p>
<p>In order to move beyond the basics, you need to learn your first language well. Then your second language will be much, much easier.</p>
<p>From there, you can branch out, and become a more well-rounded developer by learning lots of languages:</p>
<ul>
<li><p>C is a great way to learn how computers actually work in terms of memory management, and is useful in high-performance computing</p>
</li>
<li><p>C++ is great for game development.</p>
</li>
<li><p>Python is awesome for science and statistics.</p>
</li>
<li><p>Java is important if you want to work at large tech companies.</p>
</li>
</ul>
<p><strong>But learn JavaScript first.</strong></p>
<p>OK, now I’m going to attempt the impossible — I’m going to try and anticipate objections from the comments section.</p>
<h3 id="heading-objection-1-but-isnt-javascript-slow">Objection #1: But isn’t JavaScript slow?</h3>
<p>JavaScript is — for most practical purposes — as fast as high-performance languages.</p>
<p>JavaScript (Node.js) is orders of magnitude faster than Python, Ruby, and PHP.</p>
<p>It is also nearly as fast as high-performance languages like C++, Java, and Go.</p>
<p>Here are the results of the most comprehensive recent cross-language benchmark:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*h91cfcE8NlgyHfm4CLbV6w.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-objection-2-but-javascript-isnt-statically-typed">Objection #2: But JavaScript isn’t statically typed</h3>
<p>Like Python and Ruby, JavaScript is dynamically typed, which is convenient. But you can get into trouble. Here I intend for <code>exampleArray</code> to be an array. I set its values, then check its length — meaning the number of elements it contains.</p>
<pre><code class="lang-javascript">exampleArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
-&gt; [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]

exampleArray.length
-&gt; <span class="hljs-number">2</span>
</code></pre>
<p>But then I accidentally assign it to be a string.</p>
<pre><code class="lang-javascript">exampleArray = “text”
-&gt; “text”

exampleArray.length
-&gt; <span class="hljs-number">4</span>
</code></pre>
<p>These kinds of errors happen all the time in dynamically typed languages. Most developers just put checks in place to prevent them, and write tests accordingly.</p>
<p>If you absolutely must have static typing in your first programming language, then I still recommend you learn JavaScript first. Then you can quickly pick up TypeScript.</p>
<blockquote>
<p>“Typescript has a learning curve, but if you already know JavaScript, it will be a smooth one.” — <a target="_blank" href="https://medium.freecodecamp.com/when-should-i-use-typescript-311cb5fe801b#.j920zs7g2">Alex Ewerlöf on TypeScript</a></p>
</blockquote>
<h3 id="heading-objection-3-but-i-really-want-to-make-a-mobile-app">Objection #3: But I really want to make a mobile app</h3>
<p>I still recommend learning JavaScript first.</p>
<ol>
<li><p>JavaScript features several tools for making native mobile apps, such as <a target="_blank" href="https://cordova.apache.org/">Angular Cordova</a> and <a target="_blank" href="https://facebook.github.io/react-native/">React Native</a>.</p>
</li>
<li><p>In order for your mobile app to actually do anything interesting, it will probably need a proper back end, which you’ll want to build with a proper web development framework, like Node.js + Express.js.</p>
</li>
</ol>
<p>Also, it’s worth pointing out that the mobile app development’s best days may very well be behind it.</p>
<p>For starters, as much as people use mobile apps, nearly half of all developer jobs are web development. Compare this with a mere 8% of jobs that involve mobile app development.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/Stack_Overflow_Developer_Survey_2023.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Developers by occupation, according to the 2023 Stack Overflow Survey. This question had 76,872 responses from developers who took the survey, so it's quite representative.</em></p>
<p>The grand vision of “there’s an app for that” has not come to pass. Instead, most smartphone owners have <a target="_blank" href="http://www.recode.net/2016/9/16/12933780/average-app-downloads-per-month-comscore">stopped downloading new apps</a>.</p>
<p>Sure — they still use apps. Mostly Facebook, Google Maps, and handful of others. As such, much of the demand for mobile app developers is concentrated in a few large employers.</p>
<p>The outlook for those mobile development jobs is hard to forecast. Many aspects of developing, maintaining, and distributing mobile apps are easier with JavaScript. So companies like Facebook and Google are investing heavily in better tools for building these using JavaScript.</p>
<p>Pretty much all development is web development. Everything touches that big platform that is “the web.” And the next wave of devices that you’ll talk to around your home, and cars that pick your kids up from school — they’ll all be piped together using the web, too.</p>
<p>And that means JavaScript.</p>
<h3 id="heading-objection-4-isnt-javascript-a-toy-language-that-was-written-in-10-days">Objection #4: Isn’t JavaScript a toy language that was written in 10 days?</h3>
<p>JavaScript has a <a target="_blank" href="https://www.w3.org/community/webed/wiki/A_Short_History_of_JavaScript">quirky history</a>.</p>
<p>You will undoubtedly hear people crack jokes at its expense.</p>
<p>Well people love to hate on C++, too. And like JavaScript, C++ has succeeded despite this hate, and now it’s pretty much everywhere as well.</p>
<p>So if anybody ever gives you a hard time for learning JavaScript instead of elite-language-of-the-week, just remember the famous words of the guy who created C++:</p>
<blockquote>
<p>“There are only two kinds of programming languages: those people always bitch about and those nobody uses.” — Bjarne Stroustrup</p>
</blockquote>
<p><strong>I only write about programming and technology. If you</strong> <a target="_blank" href="https://twitter.com/ossia"><strong>follow me on Twitter</strong></a> <strong>I won’t waste your time. ?</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are BNF and EBNF in Programming? ]]>
                </title>
                <description>
                    <![CDATA[ As programmers, we communicate with computers through many languages: Python, JavaScript, SQL, C... you name it. But do you know how the creators of these languages precisely describe their syntax to us, leaving no room for doubt? They could've relie... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-bnf-and-ebnf/</link>
                <guid isPermaLink="false">66c5f74ffdf18f48a8c0c35f</guid>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ syntax ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ashutosh Biswas ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jul 2023 17:26:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/ryan-wallace-azA1hLbjBBo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As programmers, we communicate with computers through many languages: Python, JavaScript, SQL, C... you name it. But do you know how the creators of these languages precisely describe their syntax to us, leaving no room for doubt?</p>
<p>They could've relied on plain English, but that would not be a good solution because of the potential verbosity and ambiguity. So they used specially designed languages for it. </p>
<p>In this article, you'll learn about two of these widely used languages: BNF and EBNF.</p>
<p>Another fascinating aspect of these special languages or notations is that you can write the grammar of your own language using them and give it as input to some magical computer programs called "parser generators". These can output other programs capable of parsing any text according to the grammar you used. How amazing is that? </p>
<p>This feature can save you a lot of time since manually writing such programs is challenging and time-consuming.</p>
<p>Before learning (E)BNF, it's helpful to be able to distinguish between syntax and semantics. So let's start from there.</p>
<h2 id="heading-syntax-vs-semantics-in-programming-languages">Syntax vs Semantics in Programming Languages</h2>
<p>Syntax refers to the structure of the elements of a language based on its type. On the other hand, semantics are all about the meaning.</p>
<p>Something written syntactically correctly in a language can be completely meaningless. And no text can be meaningful if its syntax is incorrect.</p>
<p>Two of the most famous sentences regarding syntax and semantics are <a target="_blank" href="https://en.wikipedia.org/wiki/Colorless_green_ideas_sleep_furiously">composed by Noam Chomsky</a>:</p>
<ol>
<li>Colorless green ideas sleep furiously.</li>
<li>Furiously sleep ideas green colorless.</li>
</ol>
<p>The first sentence's syntax is correct but it's meaningless. And since the second one is syntactically wrong, it is far from being meaningful.</p>
<p>The same is true for programming languages too. Let's look at the following two JavaScript code snippets to see what I mean.</p>
<p>The following code is syntactically correct but semantically wrong because it's not possible to reassign something to a constant variable:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">"Palash"</span>;
name = <span class="hljs-string">"Akash"</span>;
</code></pre>
<p>The following is syntactically incorrect and thus does not even have any chance to be semantically correct.</p>
<pre><code class="lang-js"><span class="hljs-string">"Palash"</span> = <span class="hljs-keyword">const</span> name;
<span class="hljs-string">"Akash"</span> = name;
</code></pre>
<p>You check the syntax of your JavaScript code online with a tool like the <a target="_blank" href="https://esprima.org/demo/validate.html">Esprima Syntax Validator</a>.</p>
<p>There are two more concepts you need to understand before learning to read BNF/EBNF.</p>
<h2 id="heading-terminals-and-non-terminals">Terminals and Non-Terminals</h2>
<p>BNF/EBNF is usually used to specify the grammar of a language. Grammar is a set of <em>rules</em> (also called <em>production rules</em>). Here language refers to nothing but a set of strings that are valid according to the rules of its grammar.</p>
<p>A BNF/EBNF grammar description is an unordered list of rules. <em>Rules</em> are used to define <em>symbols</em> with the help of other symbols.</p>
<p>You can think of <em>symbols</em> as the building blocks of grammar. There are two kinds of symbols:</p>
<ul>
<li><strong>Terminal (or Terminal symbol)</strong>: Terminals are strings written within quotes. They are meant to be used as they are. Nothing is hidden behind them. For example <code>"freeCodeCamp"</code> or <code>"firefly"</code>.</li>
<li><strong>Non-terminal (or Non-terminal symbol)</strong>: Sometimes we need a name to refer to something else. These are called <em>non-terminals</em>. In BNF, <em>non-terminal</em> names are written within angle brackets (for example <code>&lt;statement&gt;</code>), while in EBNF they don't usually use brackets (for example <code>statement</code>).</li>
</ul>
<p>The whole language is derived from a single <em>non-terminal</em> symbol. This is called the <strong>start</strong> or <strong>root</strong> <strong>symbol</strong> of the grammar. By convention, it is written as the first non-terminal in the BNF/EBNF grammar description.</p>
<p>Finally, you are ready to learn BNF. It's easier than you might think it is.</p>
<h2 id="heading-what-is-bnf">What is BNF?</h2>
<p>BNF stands for <strong>B</strong>ackus–<strong>N</strong>aur <strong>F</strong>orm which resulted primarily from the contributions of <a target="_blank" href="https://en.wikipedia.org/wiki/John_Backus">John Backus</a> and <a target="_blank" href="https://en.wikipedia.org/wiki/Peter_Naur">Peter Naur</a>.</p>
<p>The syntax of BNF/EBNF is so simple that many people adopted their styles. So in different places, you will most likely see different styles. If the syntax is different from conventional ones, that's usually documented there. In this article I will use one particular style, just to keep things simple.</p>
<p>Below is an example of a simple <em>production rule</em> in BNF:</p>
<pre><code class="lang-bnf">&lt;something&gt; ::= "content"
</code></pre>
<p>Each rule in BNF (also in ENBF) has three parts:</p>
<ul>
<li><strong>Left-hand side</strong>: Here we write a non-terminal to define it. In the above example, it is <code>&lt;something&gt;</code>.</li>
<li><strong><code>::=</code></strong>: This character group separates the <strong>Left hand side</strong> from <strong>Right hand side</strong>. Read this symbol as "is defined as".</li>
<li><strong>Right-hand side</strong>: The definition of the non-terminal specified on the right-hand side. In the above example, it's <code>"content"</code>.</li>
</ul>
<p>The above <code>&lt;something&gt;</code> is just one thing fixed thing. Let's now see all the ways you can compose a <em>non-terminal</em>.</p>
<h3 id="heading-how-to-compose-a-non-terminal">How to compose a non-terminal</h3>
<p>BNF offers two methods to us:</p>
<ul>
<li>Sequencing</li>
<li>Choice</li>
</ul>
<p>You can just write a combination of one or more terminals or non-terminals in a sequence and the result is their concatenation, with non-terminals being replaced by their content. For example, you can express your breakfast in the following ways:</p>
<pre><code class="lang-bnf">&lt;breakfast&gt; ::= &lt;drink&gt; " and biscuit"
&lt;drink&gt; ::= "tea"
</code></pre>
<p>It means the only option for breakfast for you is <code>"tea and biscuit"</code>. Note that here, the order of symbols is important.</p>
<p>Let's say someday you want to drink coffee instead of tea. In this case, you can express your possible breakfast items like below:</p>
<pre><code class="lang-bnf">&lt;breakfast&gt; ::= &lt;drink&gt; " and biscuit"
&lt;drink&gt; ::= "tea" | "coffee"
</code></pre>
<p>The <code>|</code> operator indicates that the parts separated by it are choices. Which means the non-terminal on the left can be any such part. Here the order is <em>unimportant</em>, that is there is no difference between <code>"tea" | "coffee</code> and <code>"coffee" | "tea"</code>.</p>
<p>That is really all you need to know about BNF to read and understand it and even express the syntax of your own language using it. Believe it or not, it's that simple. And yet it can be used to describe the syntax of many programming languages and other kinds of coding languages.</p>
<p>The thing that makes it possible to break down complex syntax programming languages easily is the ability to define non-terminal symbols recursively. </p>
<p>As a simple example let's see how you express one or more digits in BNF:</p>
<pre><code class="lang-bnf">&lt;digits&gt; ::= &lt;digit&gt; | &lt;digit&gt; &lt;digits&gt;
&lt;digit&gt; ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
</code></pre>
<p>If you want to see a simple real-world example of BNF grammar checkout: <a target="_blank" href="https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions">Semver notation</a>.</p>
<h2 id="heading-what-is-ebnf">What is EBNF?</h2>
<p>BNF is fine, but sometimes it can become verbose and hard to interpret. EBNF (which stands for <strong>E</strong>xtended <strong>B</strong>ackus–<strong>N</strong>aur <strong>F</strong>orm) may help you in those cases. For example, the previous example can be written in EBNF like below:</p>
<pre><code class="lang-ebnf">digits = digit { digit }
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
</code></pre>
<p>The braces above mean that its inner part may be repeated 0 or more times. It frees your mind from getting lost in recursion.</p>
<p>One interesting fact is that everything you can express in EBNF can also be expressed in BNF.</p>
<p>EBNF usually uses a slightly different notation than BNF. For example:</p>
<ul>
<li><code>::=</code> becomes just <code>=</code>.</li>
<li>There are no angle brackets around non-terminals.</li>
</ul>
<pre><code class="lang-ad-info">For concatenation, instead of juxtaposition, some prefer `,` to be more explicit. However, I will not use it here.
</code></pre>
<p>Don't assume that these styles to be universal. There are several variants of them and they are usually clear from the context. The more important thing to focus on is the new operations it offers like the braces we've seen above.</p>
<p>EBNF extends BNF by adding the following 3 operations:</p>
<ul>
<li>Option</li>
<li>Repetition</li>
<li>Grouping</li>
</ul>
<h3 id="heading-option">Option</h3>
<p>Option uses square brackets to make the inner content optional. Example:</p>
<pre><code class="lang-ebnf">thing = "water" [ "melon" ]
</code></pre>
<p>So the above <code>thing</code> is either <code>water</code> or <code>watermelon</code>.</p>
<h3 id="heading-repetition">Repetition</h3>
<p>Curly braces indicate the inner content may be repeated 0 or more times. You have already seen a good example of it above. Below is a very simple one just to make the idea solid in your mind:</p>
<pre><code class="lang-ebnf">long_google = "Goo" { "o" } "gle"
</code></pre>
<p>So <code>"Google"</code>, <code>"Gooogle"</code>, <code>"Gooooooogle"</code> are all valid <code>long_google</code> non-terminal.</p>
<h3 id="heading-grouping">Grouping</h3>
<p>Parentheses can be used to indicate grouping. It means everything they wrap can be replaced with any of the valid strings that the contents of the group represent according to the rules of EBNF. For example:</p>
<pre><code class="lang-ebnf">fly = ("fire" | "fruit") "fly"
</code></pre>
<p>Here  <code>fly</code> is either <code>"firefly"</code> or <code>"fruitfly"</code>.</p>
<p>With BNF we could not do that in one line. It would look like the following in BNF:</p>
<pre><code class="lang-ebnf">&lt;fly&gt; ::= &lt;type&gt; "fly"
&lt;type&gt; ::= "fire" | "fruit"
</code></pre>
<h2 id="heading-the-bnf-playground">The BNF Playground</h2>
<p>There is a very nice online playground for BNF and EBNF: <a target="_blank" href="https://bnfplayground.pauliankline.com/"> Playground</a>.</p>
<p>I recommend you check it out and play with it. It uses a slightly different notation so read the "Grammar Help" section beforehand.</p>
<p>It can test if a string is valid according to the grammar you entered. It can also generate random strings based on your grammar!</p>
<p>For fun this is the syntax of a poem-like text (credit goes to chatGPT):</p>
<pre><code class="lang-ebnf">&lt;poem&gt; ::= &lt;line&gt; | &lt;line&gt; "\n" &lt;poem&gt;
&lt;line&gt; ::= &lt;noun_phrase&gt; " " &lt;verb_phrase&gt; " " &lt;adjective&gt;
&lt;noun_phrase&gt; ::= "the " &lt;adjective&gt; " " &lt;noun&gt; | &lt;noun&gt;
&lt;verb_phrase&gt; ::= &lt;verb&gt; | &lt;verb&gt; " " &lt;adverb&gt;
&lt;adjective&gt; ::= "red" | "blue" | "green" | "yellow"
&lt;noun&gt; ::= "sky" | "sun" | "grass" | "flower"
&lt;verb&gt; ::= "shines" | "glows" | "grows" | "blooms"
&lt;adverb&gt; ::= "brightly" | "slowly" | "vividly" | "peacefully"
</code></pre>
<p>Go ahead and copy-paste it into the playground and press the "Generate Random" button to get some mostly meaningless lines of a grammatically correct poem.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>BNF and EBNF are simple and powerful notations to write what computer scientists call <em>context-free grammar</em>. </p>
<p>In simple terms it means the expansion of a non-terminal is not dependent on the context (surrounding symbols), that is it's context-free. It is the most widely used grammar form to formalize the syntax of coding languages.</p>
<p>Here are some resources you might find interesting:</p>
<ul>
<li><a target="_blank" href="https://tomassetti.me/ebnf/">EBNF: How to Describe the Grammar of a Language</a></li>
<li><a target="_blank" href="https://matt.might.net/articles/grammars-bnf-ebnf/">The language of languages</a></li>
<li>Parser generators:<ul>
<li><a target="_blank" href="https://www.antlr.org/">ANTLR</a>, a very powerful parser generator capable of writing parsers in many languages.</li>
<li>If you are a JavaScript person like me and want to get started with a parser generator, take a look at <a target="_blank" href="https://nearley.js.org/">nearly.js</a> for a gentle start.</li>
</ul>
</li>
</ul>
<p>Below are some real-world grammars written using BNF/EBNF or similar notations that you might find interesting:</p>
<ul>
<li><a target="_blank" href="https://iamwilhelm.github.io/bnf-examples/lisp">Lisp</a></li>
<li><a target="_blank" href="https://www.lua.org/manual/5.4/manual.html#9">Lua</a></li>
<li><a target="_blank" href="https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions">Semver</a></li>
<li><a target="_blank" href="https://tc39.es/ecma262/multipage/grammar-summary.html#sec-grammar-summary">JavaScript</a></li>
<li><a target="_blank" href="https://facebook.github.io/jsx/">JSX</a></li>
<li><a target="_blank" href="https://docs.python.org/3/reference/grammar.html">Python</a></li>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/Value_definition_syntax">Value Definition Syntax in CSS</a></li>
</ul>
<p>Thanks for reading. Let me know on <a target="_blank" href="https://twitter.com/ashutoshbw">Twitter</a> if you have any questions or found this article helpful. Happy learning!</p>
<p>Photo by <a target="_blank" href="https://unsplash.com/@accrualbowtie?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ryan Wallace</a> on <a target="_blank" href="https://unsplash.com/photos/azA1hLbjBBo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Best Programming Language to Learn – Beginners Guide to Coding ]]>
                </title>
                <description>
                    <![CDATA[ Technology is changing how we live. We use and rely on web applications and electronic devices daily to complete various tasks. And behind these modern-day software programs are thousands of lines of code. Coding is one of the most valuable skills to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-best-programming-language-to-learn-beginners-guide-to-coding/</link>
                <guid isPermaLink="false">66b1e4bda48ebbb08ba2089a</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Fri, 28 Oct 2022 21:03:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/pexels-christina-morillo-1181677.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Technology is changing how we live. We use and rely on web applications and electronic devices daily to complete various tasks. And behind these modern-day software programs are thousands of lines of code.</p>
<p>Coding is one of the most valuable skills to learn today. You can not only build any idea you have and see it come to life, but you can also improve your future.</p>
<p>Knowing how to code increases your chances of getting a higher-paying job.</p>
<p>According to the <a target="_blank" href="https://www.bls.gov/ooh/computer-and-information-technology/software-developers.htm">U.S. Bureau of labor statistics</a>, software engineers earned a median annual salary of $109,020 in 2021.</p>
<p>In addition, the computer programming and software engineering industry is growing fast, and coding jobs are in high demand.</p>
<p>According to the <a target="_blank" href="https://www.bls.gov/ooh/computer-and-information-technology/software-developers.htm">U.S. Bureau of labor statistics</a>, the anticipated change for 2021-2031 is a 25% growth, which is much faster than average.</p>
<p>All the data above sound great, but with hundreds of programming languages available today, choosing the best one to learn can leave you confused, intimidated, or even overwhelmed.</p>
<p>The truth is, there is no one correct answer to the question 'What is the <em>best</em> programming language to learn?'.</p>
<p>The language you choose to learn will depend on many things, such as what you want to build, what projects you want to work on, your individual career goals, the desired path you want to take, or even how much you want to challenge yourself.</p>
<p>In this article, I first explain what programming languages are and go over the differences between programming, scripting, and markup languages.</p>
<p>I also list some of the most popular languages that beginners choose to learn according to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#most-popular-technologies-language-learn">Stack Overflow Developer Survey for 2022</a>.</p>
<p>Here is what we will cover:</p>
<ol>
<li><a class="post-section-overview" href="#programming-language">What are programming languages?</a><ol>
<li><a class="post-section-overview" href="#differences">Programming languages vs scripting languages vs markup languages - what's the difference?</a></li>
</ol>
</li>
<li><a class="post-section-overview" href="#list">The most popular programming languages to learn</a><ol>
<li><a class="post-section-overview" href="#html+css">HTML and CSS</a></li>
<li><a class="post-section-overview" href="#js">JavaScript</a></li>
<li><a class="post-section-overview" href="#python">Python</a></li>
<li><a class="post-section-overview" href="#sql">SQL</a></li>
<li><a class="post-section-overview" href="#c++">C++</a></li>
<li><a class="post-section-overview" href="#java">Java</a></li>
</ol>
</li>
</ol>
<p>Let's dive in.</p>
<h2 id="heading-what-are-programming-languages">What Are Programming Languages? <a></a></h2>
<p>Coding involves telling a computer what to do how to do it. You do this by providing it with a sequence of instructions using a language both humans and machines understand.</p>
<p>The machine interprets the instructions and carries them out to achieve a specific result.</p>
<p>Computers do not understand human languages. They only speak binary – a language consisting of <code>0</code>s and <code>1</code>s.</p>
<p>In binary, <code>0</code> represents off, and <code>1</code> represents on.</p>
<p>It makes perfect since that binary is the primary language of all machines since electronic devices have thousands of transistors (or tiny switches) inside them. And the switches turn on or off depending on the flow of electricity.</p>
<p>But coding in binary is time-consuming and very error-prone. So, humans invented computer programming languages that are readable, easier to learn and understand, and much more human-friendly.</p>
<p>Computer programming languages fall into one of two groups: low-level and high-level.</p>
<p>Low-level programming languages have little or no abstraction from the machine's instruction set. Essentially, their instructions are close to the machine's processor's instructions.</p>
<p>Binary code (or machine code) and assembly language are considered low-level programming languages.</p>
<p>High-level programming languages are more human-friendly.</p>
<p>They are similar to human languages and look a lot like English. They offer a shorter, more precise, and less verbose way to create instructions that the computer can understand.</p>
<h3 id="heading-programming-languages-vs-scripting-languages-vs-markup-languages-whats-the-difference">Programming Languages VS Scripting Languages VS Markup Languages - What's the Difference? <a></a></h3>
<p>At this point, it is worth mentioning that every language fits into a specific category.</p>
<p>There are three categories of languages:</p>
<ul>
<li>Programming languages</li>
<li>Scripting languages</li>
<li>Markup languages</li>
</ul>
<p><strong>Programming languages</strong> are used for writing logical sets of instructions for computers to execute and solve a problem.</p>
<p>Programming languages are written in a human-readable form but get converted to machine code (binary). </p>
<p>And this conversion happens with the help of a <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-compiler-in-c/">compiler</a>, which fully translates at once all the instructions written in a high-level programming language into something the computer's <a target="_blank" href="https://www.freecodecamp.org/news/what-is-cpu-meaning-definition-and-what-cpu-stands-for/">CPU</a> can easily understand.</p>
<p>Once the instructions are in a machine-readable form, the computer executes them, and they can run on the machine.</p>
<p><strong>Scripting languages</strong> go hand in hand with programming languages – you can think of them as a subset or subcategory of programming languages.</p>
<p>The main difference between programming and scripting languages is how each gets compiled.</p>
<p>Scripting languages get <a target="_blank" href="https://www.freecodecamp.org/news/compiled-versus-interpreted-languages/">intrerpreted rather than compiled</a>.</p>
<p>Scripting languages use an interpreter which translates each instruction, executes it, and then moves on to the next instruction and continues to do the same line by line instead of all at once as a compiler does.</p>
<p><strong>Markup languages</strong> are presentational languages and <em>not</em> programming or scripting languages. They are entirely different since they don't involve logical processing.</p>
<p>Markup languages are languages used for defining, describing, and structuring data on a web page. They also lay out and style data on a page.</p>
<h2 id="heading-the-most-popular-programming-languages-to-learn">The Most Popular Programming Languages to Learn <a></a></h2>
<p>In the following sections, I list some of the most popular languages that beginners choose to learn. I also list their use cases and some resources for you to get started learning them.</p>
<h3 id="heading-html-and-css">HTML and CSS <a></a></h3>
<p>HTML and CSS are <em>not</em> technically programming languages, but according to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#technology-most-popular-technologies">Stack Overflow developer survey for 2022</a>, they rank first as the most popular languages for people learning to code.</p>
<p>HTML and CSS are markup languages, and you use them to create static web pages.</p>
<p>They are two languages you need to learn if you are interested in becoming a frontend developer. You can also learn them alongside JavaScript to add interactivity to the static pages you create.</p>
<p>HTML (which stands for HyperText Markup Language) defines the structure and content of a web page. So, the paragraphs, headings, lists, forms, and links you see on a page, along with their hierarchies, are all HTML code.</p>
<p>And thanks to the latest version of HTML, HTML5, you can embed images, videos, and audio in web pages eliminating the need to use extra plugins like you had to in the past.</p>
<p>CSS (short for Cascading Style Sheets) styles HTML elements. It is responsible for presenting content in a visually appealing way.</p>
<p>CSS code enables all the different colors and fonts. The sizing of elements and how those elements get displayed on the page. The page layout and how items get arranged next to one another.</p>
<p>To learn HTML and CSS, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-html-beginners-course/">Learn HTML – Beginner's Course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-css-in-this-free-6-hour-video-course/">Learn CSS in this free 6-hour video course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/html-css-11-hour-course/">Learn HTML and CSS with this free 11 hour course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-html-and-css-in-spanish-course-for-beginners/">Learn HTML and CSS in Spanish – Course for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/2022/responsive-web-design/">Responsive Web Design Certification</a></li>
</ul>
<h3 id="heading-javascript">JavaScript <a></a></h3>
<p>According to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#technology-most-popular-technologies">Stack Overflow developer survey for 2022</a>, JavaScript has ranked first as the most commonly used programming language for ten consecutive years. And it is the second most popular language for people learning to code.</p>
<p>JavaScript (not to be confused with Java) is a scripting language that lets you add interactivity and dynamic behaviors to otherwise static web pages. </p>
<p>Some interactive features JavaScript can add are:</p>
<ul>
<li>A map with a user’s current location</li>
<li>A message shown to a user once they land on the page</li>
<li>A change on the page based on user input</li>
<li>An animation when a user clicks a button</li>
<li>A smooth scroll effect when there is a button to scroll back up to the top of the page.</li>
<li>Mouseover effects</li>
</ul>
<p>One of JavaScript's strengths as a language is that you don't need to compile your code to see the results of your work.</p>
<p>Javascript is built in and runs in browsers, meaning you don't need to install it on your local machine and go through a complicated and error-prone installation process.</p>
<p>JavaScript is used primarily for client-side programming and server-side scripting. </p>
<p>Specifically, JavaScript is used for frontend web development and even backend web development with the help of Node.js, a JavaScript runtime environment for running JavaScript on a server and not just the browser.</p>
<p>Knowing JavaScript is a must if you want to work as a frontend developer, and it is a popular language of choice for backend and full stack web development roles.</p>
<p>To learn more about the differences between frontend and backend web development, give <a target="_blank" href="https://www.freecodecamp.org/news/frontend-vs-backend-whats-the-difference/">this article</a> a read. And to learn what the job of a full stack web developer entails, give <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-full-stack-developer-full-stack-engineer-guide/">this article</a> a read.</p>
<p>Besides creating complex web applications, JavaScript is also used for creating browser games.</p>
<p>To learn JavaScript, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/full-javascript-course-for-beginners/">Full JavaScript Course for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-in-spanish-full-course-for-beginners/">Learn JavaScript in Spanish – Full Course for Beginners</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=ec8vSKJuZTk&amp;t=82s">Learn JavaScript by Building 7 Games - Full Course</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=8xPsg6yv7TU">JavaScript Tutorial: Build Flappy Bird and Doodle Jump</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">JavaScript Algorithms and Data Structures certification</a></li>
</ul>
<h3 id="heading-python">Python <a></a></h3>
<p>Python is a general-purpose server-side scripting language. And according to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#most-popular-technologies-language-learn">Stack Overflow Developer Survey for 2022</a>, it is the third most popular language for people learning to code.</p>
<p>Python is a great language for beginners thanks to its readable, intuitive, concise, and beginner-friendly syntax.</p>
<p>It is a popular language when working with large amounts of data, so it's often used for machine learning, data science, data analysis, and data processing.</p>
<p>It is also the language of choice for web scraping. Web scraping is an automated technique that extracts, collects, and processes large amounts of raw data from the web.</p>
<p>You can also use Python for backend web development to create web applications with the help of frameworks such as Django and Flask.</p>
<p>In addition, Python is a popular language for test automation.</p>
<p>Instead of writing all the tests for your programs manually, you can rely on automation tools, Python libraries, and Python scripts to get the job done.</p>
<p>To get started learning Python, check out the following recourses:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/freecodecamp-python-courses-ranked-from-best-to-worst/">Python For Beginners Courses Ranked from Best to Worst – freeCodeCamp Edition</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/20-beginner-python-projects/">How to Code 20 Beginner Python Projects</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-how-to-build-12-python-projects-in-one-course/">Learn Python by Building 12 Projects in This 3-Hour Course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/backend-web-development-with-python-full-course/">Backend Web Development with Python - Full Course</a></li>
</ul>
<h3 id="heading-sql">SQL <a></a></h3>
<p>SQL is short for Structured Query Language.</p>
<p>You will likely hear it pronounced one of two ways – "S. Q. L." (ess-kew-ell) or "sequel" (like a sequel to a movie).</p>
<p>Either way, SQL is a language used for working with databases and any job that involves storing, managing, accessing, and analyzing data. It is one of the languages of choice for data scientists, data analysts, statisticians, and marketers.</p>
<p>Specifically, with SQL, you can access, query, manipulate and interact with data stored in relational databases.</p>
<p>A database is an electronic storage localization for data. In databases, you can easily retrieve and search through your data.</p>
<p>And a relational database stores data in a structured and tabular format. That is, it stores information in tables (which you can think of as storage containers for the data) organized in columns and rows. All data items stored have pre-defined relationships with each other.</p>
<p>With SQL, you can write database queries to perform any CRUD (Create, Read, Update, Delete) operations on the data.</p>
<p>It is worth mentioning that SQL is not technically a programming language - you cannot build web applications or software tools using it. It is a query language and a tool used for managing relational databases and performing operations on the data stored in them.</p>
<p>And although it ranks fifth as the most popular language for people learning to code according to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#most-popular-technologies-language-prof">Stack Overflow Developer Survey for 2022</a>, it ranks third as the most popular language for professional developers. </p>
<p>So, it is a good idea to learn SQL as you may need to use it in a professional setting.</p>
<p>To learn SQL, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-free-relational-database-courses-for-beginners/">Learn SQL – Free Relational Database Courses for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-in-10-minutes/">SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/sql-recipes/">Learn SQL with These 5 Easy Recipes</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/sql-and-databases-full-course/">SQL and Databases - A Full Course for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/relational-database/">Relational Database Certification</a></li>
</ul>
<h3 id="heading-c">C++ <a></a></h3>
<p>In the early 1980s, Bjarne Stroustrup created a language influenced by the C programming language. It could get close to the machine hardware and do demanding low-level computational tasks, but it also provided a higher level of abstraction without losing the low-level efficiency of C. </p>
<p>So, the language 'C with classes' was created, and in 1984 'C with classes' was renamed C++.</p>
<p>C++ is a superset of C and provides additional capabilities to the C language. </p>
<p>C++ allows the programmer close access to and manipulation of the machine while providing efficiency and high performance for large-scale systems. At the same time, it is higher level with enough abstraction away from the machine.</p>
<p>C++ is both a procedural and an object oriented programming language. OOP  divides a program into objects.</p>
<p>Everything gets organized and divided into smaller groups of related parts or objects, which are an instance of a class, following a bottom-up approach.</p>
<p>This programming style creates more readable and usable code that is easier to maintain while providing better data security.</p>
<p>C++ is a popular language for:</p>
<ul>
<li>creating game engines</li>
<li>creating computer graphics</li>
<li>creating applications</li>
<li>creating VR applications</li>
<li>creating web browsers such as Google Chrome, Mozilla Firefox, Safari</li>
<li>creating web browser extensions - the Google Search Engine is built in C++ </li>
</ul>
<p>According to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#technology">Stack Overflow Developer Survey for 2022</a>, it ranks sixth as the most popular programming language for people learning to code. And it is a great language if you want to get a software engineering job and develop programs and applications.</p>
<p>To learn C++, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-learn-the-c-programming-language/">How to Learn the C++ Programming Language</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-object-oriented-programming-oop-in-c-full-video-course/">Learn Object Oriented Programming (OOP) in C++ | Full Video Course</a></li>
</ul>
<h3 id="heading-java">Java <a></a></h3>
<p>Java is an object-oriented, general-purpose programming language whose syntax is based on the C and C++ programming languages.</p>
<p>One of the language's advantages is its portability. Portability in computing means that programs get written once on one machine and can be transferred and run smoothly on another.</p>
<p>The Java Virtual Machine lets Java run on any device and operating system.</p>
<p>Java is used for:</p>
<ul>
<li>Building mobile applications for the Android Operating System</li>
<li>Backend web development</li>
<li>Game development</li>
<li>Creating embedded systems</li>
<li>Building desktop applications</li>
<li>Building enterprise-level software tools for the banking industry</li>
<li>Building artificial intelligence and Internet of Things (or IoT) devices</li>
</ul>
<p>Keep in mind that Java is not the same as JavaScript – they are in no way related to each other despite having the word 'Java' in their names.</p>
<p>JavaScript is an interpreted scripting language that runs in the browser and doesn't need to be compiled.</p>
<p>Java uses a combination of a compiler and an interpreter and runs on machines - not in browsers.</p>
<p>According to the <a target="_blank" href="https://survey.stackoverflow.co/2022/#technology">Stack Overflow Developer Survey for 2022</a>, Java ranked 4th as the most popular language for people learning to code. </p>
<p>Java coding skills can help you get a job as a software engineer, a web developer, and an android developer.</p>
<p>To start learning Java, check out the following resources:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-java-free-java-courses-for-beginners/">Learn Java – Free Java Courses for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-java-handbook/">The Java Handbook – Learn Java Programming for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-java-programming/">Learn Java Programming (version 17)</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/build-a-sudoku-java-desktop-application/">How to Build a Sudoku Game Java Desktop Application – A Free 2-hour Course</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Hopefully, this guide was helpful and gave you some insight into some of the best languages to learn as a beginner programmer.</p>
<p>Thank you for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Haskell Programming Language – How to Install and Use Haskell Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ By MacBobby Chibuzor What is Haskell? What is it used for? Why are there relatively few Haskell programmers? How can I get started with Haskell? If you're asking yourself these questions, then this article is for you. In it, I'll answer your question... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/haskell-programming-language-introduction/</link>
                <guid isPermaLink="false">66d46012d7a4e35e3843497d</guid>
                
                    <category>
                        <![CDATA[ Haskell ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 04 Mar 2022 19:57:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/haskell_freecodecamp.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By MacBobby Chibuzor</p>
<p>What is Haskell? What is it used for? Why are there relatively few Haskell programmers? How can I get started with Haskell?</p>
<p>If you're asking yourself these questions, then this article is for you. In it, I'll answer your questions about the Haskell programming language and demystify it for you.  </p>
<p>You will learn about the Haskell ecosystem and how to set it up for development. You will also learn the beauty of Haskell and where the language can be applied for real world problem solving.</p>
<p>Given the complexity of Haskell, you should know the basics of programming prior to diving into Haskell. It'll also help if you're very comfortable with another functional programming language to best understand Haskell syntax.</p>
<h1 id="heading-what-well-cover">What We'll Cover</h1>
<ul>
<li>Haskell — A Proper Introduction</li>
<li>Functional Programming</li>
<li>Strongly Statically Typed Programming</li>
<li>The Haskell Ecosystem</li>
<li>How to Set Up Haskell Development Environment</li>
<li>The Code Editor</li>
<li>Hacking into the Beauty of Haskell</li>
<li>The <code>ghci</code> Compiler</li>
<li>Python vs Haskell – the Easiest vs the Hardest</li>
<li>Major Use Cases for Haskell</li>
<li>Web development: Backend with Spock, Frontend with Elm</li>
<li>Cardano Blockchain Development with Plutus</li>
</ul>
<h1 id="heading-haskell-a-proper-introduction">Haskell — A Proper Introduction</h1>
<p>Haskell is a fully functional programming language that supports lazy evaluation and type classes. </p>
<p>Haskell forces the developer to write very correct code, which is the quintessential nature of the language.</p>
<h2 id="heading-functional-programming">Functional Programming</h2>
<p>The world of computer programming allows different programming styles: functional, imperative, object-oriented. </p>
<p>The functional programming style treats functions as the first-class citizens – the most important parts of a program. </p>
<p>In functional programming languages, functions can be passed as values or data types. Functions can be passed as arguments to other functions, returned as results from functions, and assigned to variables. This promotes code reuse in a single codebase.</p>
<p>Haskell is a functional programming language and it supports these properties. Modern Java, C++, Go, and C# are all tethered to the functional style of programming.</p>
<h2 id="heading-strongly-statically-typed-language">Strongly Statically Typed Language</h2>
<p>Programming languages can either have a dynamic or static type system. In dynamic typing, values are tagged to data types during execution. This is common among languages like Python and JavaScript which allow implicit conversion between data types. </p>
<p>In static typing, tagging is done during compilation and is common among low-level languages. In statically typed languages, programs are evaluated by the compiler before they are compiled into machine or bytecode and run.</p>
<p>Haskell is statically typed as its programs must be type checked before compilation and execution. Unlike Java and C#, the Haskell compiler only does type checking once, which boosts performance. </p>
<p>Also, Haskell’s type system is called strong because of the error safety at compile time. As such, a common phrase among Haskell developers is, “Once it compiles, it works.”</p>
<h1 id="heading-the-haskell-ecosystem">The Haskell Ecosystem</h1>
<p>The most challenging aspect of starting out with a new language is configuring the development environment perfectly. </p>
<p>To install and set up Haskell, you need to grab the entire Haskell ecosystem. The Haskell ecosystem contains:</p>
<ul>
<li>The compiler called Glasgow Haskell Compiler (GHC)</li>
<li>The Interpreter called Glasgow Haskell Interpreter, (GHCi)</li>
<li>The Stack tool for managing Haskell projects</li>
<li>Other Haskell packages</li>
</ul>
<p>You can get the one-for-all software package from <a target="_blank" href="http://www.haskell.org/downloads#platform">www.haskell.org/downloads#platform</a>. Haskell, like every other programming language widely adopted, has a database for its libraries, called <a target="_blank" href="http://hackage.haskell.org/">Hackage</a>.</p>
<h2 id="heading-how-to-set-up-the-haskell-development-environment">How to Set Up the Haskell Development Environment</h2>
<h3 id="heading-linux-environment">Linux Environment</h3>
<p>If you use a Linux machine, it’s easier to run a shell command. The command below will install the Haskell platform on your machine.</p>
<pre><code class="lang-bash">$ sudo apt-get install haskell-platform
</code></pre>
<p>Next, type <code>ghc</code> on the Linux command line and hit <strong>Enter</strong>. This should prompt whether you install the GHCi interpreter or not. Type Y and hit <code>Enter</code>.  You should also install the Cabal build tool by running this chain of commands:</p>
<pre><code class="lang-bash">$ sudo apt-get install software-properties-common
$ sudo add-apt-repository ppa:hvr/ghc
$ sudo apt install cabal-install
</code></pre>
<p>After installation, you should see the following output when you re-run <code>ghci</code> on the shell:</p>
<pre><code class="lang-bash">$ ghci
GHCi, version 8.8.4: &lt;https://www.haskell.org/ghc/&gt;  :? <span class="hljs-keyword">for</span> <span class="hljs-built_in">help</span>
Prelude&gt;
</code></pre>
<p>Run a simple arithmetic to confirm that <code>ghci</code> works properly.</p>
<h3 id="heading-windows-and-mac-os">Windows and Mac OS</h3>
<p>The Haskell platform can be gotten from the official download page for both Windows and macOS. </p>
<p>You can install the Cabal libraries tool on Windows from <a target="_blank" href="https://downloads.haskell.org/~cabal/cabal-install-3.6.2.0/cabal-install-3.6.2.0-x86_64-windows.zip">here.</a> You can install it for macOS <a target="_blank" href="https://downloads.haskell.org/~cabal/cabal-install-3.6.2.0/cabal-install-3.6.2.0-x86_64-darwin.tar.xz">here</a>.</p>
<h2 id="heading-the-code-editor">The Code Editor</h2>
<p>Haskell does not have a specially suitable code editor for writing its programs. You can write Haskell code in any of these Code Editors:</p>
<ul>
<li><a target="_blank" href="https://www.jetbrains.com/idea/download/download-thanks.html?platform=linux&amp;code=IIC">IntelliJ IDEA</a> with the <a target="_blank" href="https://plugins.jetbrains.com/plugin/8258-intellij-haskell">Haskell Plugin</a> installed</li>
<li>Visual Studio Code with Haskell plugins installed</li>
<li>Emacs in Haskell Mode</li>
<li>Neovim</li>
</ul>
<p>Alternatively, you can also write Haskell code on a “dumb” code editor like Notepad++ and Sublime Text and then compile with the GHC. </p>
<p>What Haskell does is condition you to write codes in bits or modules, reiterating over it to make sure each module is correct and perfect for production. Thus, a smart or dumb code editor has minimal impact whatsoever on the finished code.</p>
<p>Feel free to check for extensions in the code editor marketplaces that will make writing Haskell source files a lot easier, like Haskero or <a target="_blank" href="https://github.com/Meowcolm024/has-go">Haskell Runner for VSCode</a>.</p>
<h1 id="heading-hacking-into-the-beauty-of-haskell">Hacking into the Beauty of Haskell</h1>
<p>The beauty of Haskell lies in:</p>
<ul>
<li>The logic</li>
<li>The ease of reading Haskell code like mathematical expressions</li>
<li>You can specify the probable output for a program and the language does the rest</li>
<li>Its self-documenting nature</li>
<li>The magnificent GHCi compiler</li>
<li>The concept of purity</li>
</ul>
<h2 id="heading-the-ghci-compiler">The <code>ghci</code> Compiler</h2>
<p>Unlike other programming languages, the <code>ghci</code> compiler allows you to interactively use the compiler.</p>
<p>Also, multi-line coding which isn’t allowed in other compilers is allowed in <code>ghci</code>. For example, if you want to write a full script in Python IDLE, you would have to write it step by step, with each line being complete. But Haskell’s compiler makes it possible to do multi-line coding like this:</p>
<pre><code class="lang-haskell">$ ghci
<span class="hljs-type">GHCi</span>, version <span class="hljs-number">8.8</span><span class="hljs-number">.4</span>: &lt;https://www.haskell.org/ghc/&gt;  :? for help
<span class="hljs-type">Prelude</span>&gt; :{
<span class="hljs-type">Prelude</span>| <span class="hljs-number">60</span> +
<span class="hljs-type">Prelude</span>| <span class="hljs-number">30</span>
<span class="hljs-type">Prelude</span>| :}
<span class="hljs-number">90</span>
<span class="hljs-type">Prelude</span>&gt;
</code></pre>
<h2 id="heading-python-vs-haskel-the-easiest-vs-the-hardest">Python vs Haskel – the Easiest vs the Hardest</h2>
<p>Haskell is considered a very hard language to learn and master. On the other hand, Python is considered the easiest and most useful programming language to use.</p>
<p>Given that a lot of programmers are comfortable with Python programming, it is logical to explain Haskell in terms of Python:</p>
<ol>
<li>Haskell is a functional language, as mentioned before, while Python is a mixture of procedural, object-oriented, and functional programming styles. Haskell has procedural programming support, but the side-effects in the language do not make it easy.</li>
<li>Python and Haskell have a strong type system, which means explicit conversions have to be done. However, while Python is dynamically typed, Haskell is statically typed.</li>
<li>Python is a lot slower than Haskell.</li>
<li>As mentioned earlier, Python is easier than Haskell to learn. The learning curve for Haskell is steep, especially for those with no prior functional programming experience.</li>
<li>In terms of library support, Python has more libraries and use-cases than Haskell.</li>
</ol>
<h1 id="heading-major-use-cases-for-haskell">Major Use Cases for Haskell</h1>
<p>The major uses of the Haskell language today include Web Development and Cardano Blockchain Development.</p>
<h2 id="heading-haskell-for-web-development">Haskell for Web Development</h2>
<p>You can use Haskell for web development. Just as Python has Flask and Django, Go has Gin, Echo, and Bevel, Haskell has Scotty, Servant, and Yesod all built on top of Wai.</p>
<p>Wai is the Haskell package for managing HTTP requests/responses. Among the three popular Haskell frameworks, Yesod is more of a complete web framework than the others.</p>
<p>Haskell also has the <code>blaze-html</code> package used to build HTML files, similar to <code>gohtml</code>.</p>
<h2 id="heading-haskell-for-cardano-blockchain-development"><strong>Haskell for Cardano Blockchain Development</strong></h2>
<p>Cardano is a new blockchain platform that adopts the Proof-of-Stake consensus algorithm. It is the first to allow peer-review research and it was created to address the downsides of Bitcoin and Ethereum.</p>
<p>The Cardano cryptocurrency, ADA, is a popular coin in Japan, and they have ADA ATMs installed in Tokyo. </p>
<p>The Cardano blockchain system is written in Plutus, a Haskell-based, Turing-complete programming language. </p>
<p>Plutus makes use of several tools to build smart contracts on the Cardano blockchain. It has the Plutus Application Backend which provides the environment and tools used to interact with smart contracts. Plutus also provides a fee estimator for in-house cost calculations.</p>
<p>You can preview and run Plutus code on the <a target="_blank" href="https://playground.plutus.iohkdev.io/">Plutus Playground</a>.</p>
<p>Since Haskell is a high assurance language built for users in the financial industry, it tackles the problem of transaction exchanged failures due to bad code, and multi-sig failures that enable hackers to steal digital money.</p>
<h1 id="heading-final-words">Final Words</h1>
<p>Thank you for reading this introduction to Haskell and its ecosystem and main uses. I hope you are inspired to start learning more about it.</p>
<p>In my future articles, you will be able to learn the basics of Haskell programming, as well as more about its main use cases.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Get Started in Tech ]]>
                </title>
                <description>
                    <![CDATA[ By Njoku Samson Ebere If you are just starting out in tech but do not know which path to take, then this article is for you. If you've started learning, but you're still confused on which programming language or tools to choose, don't worry – we'll d... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-started-in-tech/</link>
                <guid isPermaLink="false">66d84fa9da89a73e2ddf57a7</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 03 Feb 2022 16:31:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/pexels-christina-morillo-1181359--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Njoku Samson Ebere</p>
<p>If you are just starting out in tech but do not know which path to take, then this article is for you.</p>
<p>If you've started learning, but you're still confused on which programming language or tools to choose, don't worry – we'll discuss that here.</p>
<p>And if you've ever wondered how many tutorials you need to read to become a better programmer, we'll talk about that, too.</p>
<p>Let's begin with which programming language to choose. Then we'll look at how to best use tutorials to make yourself a better programmer.</p>
<h2 id="heading-what-programming-language-do-i-learn-first">What Programming Language Do I Learn First?</h2>
<p>This question has been asked by almost everyone you know in tech today. There are so many different areas in the tech field, along with a ton of design tools, writing tools, programming languages, frameworks and so on. All this makes your choices quite difficult and possibly overwhelming.</p>
<p>So let's start with one of the most basic questions: which programming language should you learn first?</p>
<p>The most common answer to this question is: <em>"Learn any language you want, and the others will become easy to learn afterwards"</em>. I totally agree with this answer.</p>
<p>Sometimes, it might still be difficult to just pick one at random. Here are a few points that will help you make your choice.</p>
<h2 id="heading-choose-a-programming-language-based-on-your-interests">Choose a programming language based on your interests</h2>
<p>You'll likely learn faster if you have interest in the subject you're learning about. So you might want to ask yourself what your interests in the tech field are. </p>
<p>First, this will help you pick a language that aligns with your interests. And second, it will make it easier and more interesting to learn. Most importantly, you will hardly find a reason to give up.</p>
<p>For example, if you have interest in hardware, you might consider a language that helps you build robotics like C/C++, Python, MATLAB, Java and so on. </p>
<p>If you are interested in animation, you might want to look for a language that is often used for animation like CSS, JavaScript, or Python. </p>
<p>If you love aesthetics, you might want to go for design or frontend development using tools like Figma, Adobe XD, CSS, PhotoShop and others. </p>
<p>If you love writing, you can consider technical writing or documentation using tools like snipper for image capturing, Photoshop for image editing, grammarly for proofreading, and a markdown editor for formatting content. </p>
<h2 id="heading-choose-a-programming-language-based-on-its-community">Choose a programming language based on its community</h2>
<p>Most popular programming languages have a large community built up around them. These are people in that field who use the language regularly, and they might even work on or contribute to it if it's open source.  </p>
<p>The size and robustness of the community determines how many contributions are made to that language and how much support you might find if you have issues with it. </p>
<p>For example, if you're learning a language like Python that has a large and thriving community, you probably won't have to wait very long before a bug gets fixed if you find one. </p>
<p>JavaScript and its accompanying frameworks or libraries enjoy a large community and this is why there are so many packages built by the people of that community to make building applications with it a lot easier and faster. This also means that the language will last a very long time. </p>
<p>PHP didn't used to have frameworks, but people who use and love the language went ahead and built some for it such as Code Igniter and Laravel. And other devs built packages that you can just add to your code to get a lot done in very little time. </p>
<p>Another benefit of this is that you will have a lot of people with similar interests to network with. If you have a good network, you get to learn not just about the language but also about opportunities around it. </p>
<p>In general, there is usually a higher probability of getting help from a community of 10,000 people compared to a community of 1,000 people.</p>
<h2 id="heading-choose-a-programming-language-based-on-job-availability">Choose a programming language based on job availability</h2>
<p>Unless you have a particular project you want to build or you work as a freelancer, you should focus on learning a language that many companies use, especially those around your area. This is a practical consideration for when you start looking for a developer job.</p>
<p>So you might want to ask around and find out which languages the companies use that you wish to work for.</p>
<p>For example, it would be wise to learn JavaScript if most companies you want to work for use JavaScript.</p>
<h2 id="heading-choose-a-programming-language-based-on-your-background">Choose a programming language based on your background</h2>
<p>Your educational background can also help you choose a programming language to learn. If you learn a programming language related to your background, you will find it easier to pick up and you'll likely make progress more quickly.</p>
<p>For example, if you have a background in statistics and analysis, you will find it more interesting to learn programming languages used for those purposes, such as Python and R. If you have a background in creative art, you might find design and frontend web development more interesting.</p>
<h2 id="heading-choose-a-programming-language-based-on-your-ability-to-persevere">Choose a programming language based on your ability to persevere</h2>
<p>Every developer (that is, problem solver) should strive to become patient, resilient, and tough. When you're learning to code, you'll have to persevere through a lot of hard times. </p>
<p>And learning some programming languages requires more of these qualities than others.</p>
<p>So you might want to ask yourself the following questions:<br>"Am I in a hurry to get a job?", "Am I a total tech beginner with no previous programming experience?" or  "Am I the type that gives up a little easier?"</p>
<p>If you answered "YES" to those questions, or if you just want to start slow, you should start with a language that is clearer and easier to understand instead of jumping right into a language that might be very complicated.</p>
<p>For example, if you are going into backend web development and you already know or learned JavaScript while doing frontend, it will be easier to go for Nodejs since it is based off the JavaScript syntax. </p>
<p>This will help you focus more on learning backend programming structures, database relationships, and so on. On the other hand, if you jumped straight into PHP, Java, or Python (which have a totally different syntax), things would be more difficult at first. </p>
<p>And then, if you later choose to learn another backend language, it becomes even easier because you already have experience in backend development. So now you can focus on learning the syntax of the new language only. </p>
<p>If you keep these five points in mind when you're choosing a language to learn, you are most likely going to find it a lot easier to find your way.</p>
<p>But after you choose a language, there is another crucial question that bothers many new developers: "How many more tutorials do I need to go through to become a better programmer?" The next section of this article addresses that question.</p>
<h2 id="heading-how-many-coding-tutorials-should-you-go-through">How many coding tutorials should you go through?</h2>
<p>The answer to that question is this: tutorials alone don't make you a better programmer.  You don't need to follow tutorials to become a professional programmer. What you really need is constant practice.</p>
<p>Don't get me wrong: I am not saying you shouldn't go through tutorials – but no amount of tutorials will make you a pro.</p>
<p>Programming is just like every other thing you do in this life. You don't learn by just looking (that is, only theory) but rather by also doing (that is, continuous practice).</p>
<p>You don't learn how to drive just by watching someone drive.<br>You don't learn how to cook just by watching someone cook.<br>You don't learn how to do anything just by watching someone do it.</p>
<p>Let me relate with you a bit: You get a tutorial and you read or watch it as the case maybe. You see the instructor do everything step by step and it looks so easy – so you feel like you can do it and you say to yourself: <em>"When I need this I will refer to this tutorial"</em> and you move to another tutorial.</p>
<p>Well, this is OKAY. Many of us have made this mistake already so we understand!</p>
<p><strong>But have you ever thought to yourself:</strong></p>
<blockquote>
<p>Why are these tutorials usually bug-free?</p>
<p>Why does it take you so much time to do what took the instructor a short time to accomplish?</p>
</blockquote>
<p>Now, think about that for a moment!</p>
<p>Well, the answer is simple - the teacher has practiced and thought through the tutorial carefully before coming to teach you!</p>
<p>Just like that teacher, you have to practice constantly. When you practice, this is what will follow:</p>
<ol>
<li>You will come across bugs (problems) – after all, programming is all about problem solving.</li>
<li>You go through the pain and joy of solving the problem.</li>
<li>When you finally do, you will have really learned something and become a better programmer.</li>
</ol>
<h2 id="heading-my-advise">My Advise</h2>
<p>Please grab your cup of coffee or tea and follow me:</p>
<ol>
<li>Learn the basics of programming (any language of your choice).</li>
<li>Pick up a project (It could be anything ranging from a TODO App, a blog, a portfolio, geo-search app, and so on – <a target="_blank" href="https://www.freecodecamp.org/news/javascript-projects-for-beginners/">here</a> and <a target="_blank" href="https://www.freecodecamp.org/news/python-projects-for-beginners/">here</a> are some beginner-friendly project ideas in JavaScript and Python to get you started).</li>
<li>Draw out a plan to build the app (This might include how the front-end (UI) looks, how the databases are related or connected, how the back-end works, and so on).</li>
<li>Set a reasonable deadline and work towards it (This is very important as it keeps you focused – you know when you are moving fast and when you are slow).</li>
<li>Always use Documentation (Don't try to learn everything in the documentation – just focus on what you need for the completion of the project you chose).</li>
<li>Don't forget Google Search and Youtube, especially when you run into bugs (Most problems you will run into have been faced by someone and documented online).</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Starting out in tech is not easy but anyone can do it with some hard work and determination. In this article, I've explained five points that can help you make a decision about how to start learning.</p>
<p>It is important to note that the qualities mentioned in point five can be built on or worked on over time. So don't give up if it doesn't come easily! </p>
<p><strong>Just remember: PRACTICE! PRACTICE!! PRACTICE!!!</strong></p>
<p>That is what you really need to become a professional programmer. Build projects – lots of them – and use tutorials to help you more fully understand concepts or problems you come across. Some of us have already made this mistake, so learn from us.</p>
<p>If you're struggling to learn your first language, don't worry. It might be because you have not been building stuff. So build something, anything at all, fix bugs, write about what you are learning if you want to. All this will help you grow as a developer.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 7 Questions New Developers Ask When Learning How to Code ]]>
                </title>
                <description>
                    <![CDATA[ If you're relatively new to coding, you surely have some questions – how should you get started, what should you learn first, what does "front-end development" really mean...? In this article, I've shared 7 questions I had when I first started learni... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/questions-new-developers-ask-when-learning-how-to-code/</link>
                <guid isPermaLink="false">66d45f39052ad259f07e4aec</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jacob Stopak ]]>
                </dc:creator>
                <pubDate>Mon, 15 Nov 2021 17:14:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/11/7-questions-new-developers-ask.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're relatively new to coding, you surely have some questions – how should you get started, what should you learn first, what does "front-end development" really mean...?</p>
<p>In this article, I've shared 7 questions I had when I first started learning to code about 20 years ago (man, now I feel old). And I've answered them as thoroughly as possible to help you start your coding journey.</p>
<h2 id="heading-what-programming-language-should-i-learn-first">What programming language should I learn first?</h2>
<p>In my opinion, it doesn't really matter! There are certainly languages that are easier for beginners to pick up, such as Python, Ruby, or JavaScript. But most programming languages have a plethora of things in common, and the core concepts are usually fairly similar.</p>
<p>In most cases, the <em>syntax</em> (the keywords, structure, and semantics) of languages differ much more than the underlying concepts.</p>
<p>Once you know the basics of any programming language, it becomes a lot easier to pick up another one. It is also likely that the language you learn first won't be the central one you end up using at your job or side hustle.</p>
<p>For example, I started with Python back in the day, dabbled with JavaScript and PhP, but now use Java for my job and side hustle.</p>
<p>Of course, you probably don't want to start by learning some obscure and difficult language that isn't commonly used. But you really can't go wrong by starting with a popular modern language like Python, Java, Ruby, or JavaScript.</p>
<p>The most important part isn't what language you learn first, but that you <em>actually start</em> and incrementally improve your skills over time. In a nutshell, <a target="_blank" href="https://initialcommit.com/store/coding-essentials-guidebook-for-developers">focus on mastering essential coding concepts</a> as opposed to the syntax of a specific language.</p>
<h2 id="heading-how-do-we-categorize-programming-languages">How do we categorize programming languages?</h2>
<p>Although most programming languages have a lot in common, there are many ways to organize languages into various categories.</p>
<p>These categories are used to group together languages with a particular feature or trait, although two languages with an overlapping trait might very well differ with respect to others.</p>
<p>Here are 5 of the most useful programming language categories for new devs to know about:</p>
<ul>
<li><p>Compiled programming languages</p>
</li>
<li><p>Interpreted programming languages</p>
</li>
<li><p>Statically-typed programming languages</p>
</li>
<li><p>Dynamically-typed programming languages</p>
</li>
<li><p>Object-oriented programming languages</p>
</li>
</ul>
<p>Below, is a short description of each of these categories, along with a short list of languages in each one.</p>
<h3 id="heading-compiled-programming-languages">Compiled programming languages</h3>
<p>A compiled language is one that uses a <strong>compiler</strong> to convert source code (the code you write yourself) into a form the computer knows how to understand (often called <strong>machine code</strong>).</p>
<p>Usually, the output from the compiler is saved in one or more files called <strong>executables</strong>. Executables can be packaged for sale and distribution in standard formats that make it easy for users to download, install, and run the program.</p>
<p>An important characteristic of the compiling process is that the source code is compiled <em>before</em> the program is executed by the end user. In other words, code compilation typically takes place separately from program execution.</p>
<p>Popular compiled languages:</p>
<ul>
<li><p>C</p>
</li>
<li><p>C++</p>
</li>
<li><p>Java</p>
</li>
<li><p>Rust</p>
</li>
<li><p>Go</p>
</li>
</ul>
<h3 id="heading-interpreted-programming-languages">Interpreted programming languages</h3>
<p>An interpreted language is one that uses an <strong>interpreter</strong> to convert source code (the code you write yourself) into a form the computer knows how to understand.</p>
<p>An interpreter is a program that takes a set of source code written in a specific programming language, converts it into a form the computer can understand, and immediately executes it in real-time.</p>
<p>A primary difference between compiling and interpreting is that the interpreting process has no gap between code conversion and execution – both of these steps happen at program run time or on-the-fly. Whereas with compiling, the code conversion takes place in advance (sometimes far in advance) of program execution.</p>
<p>Popular interpreted languages:</p>
<ul>
<li><p>Python</p>
</li>
<li><p>JavaScript</p>
</li>
<li><p>Ruby</p>
</li>
</ul>
<h3 id="heading-statically-typed-programming-languages">Statically-typed programming languages</h3>
<p>Static-typing means that the data types of the variables in a programming language are known and established at the time the program is compiled. Furthermore, the datatype of a variable is not allowed to change during program compilation or execution.</p>
<p>For example, each time you create a variable in a statically-typed language, you must explicitly specify the datatype of that variable. This datatype could be an integer, string, boolean, and so on. This is called variable <strong>declaration</strong>. Once you declare a variable’s data type, it can only hold that type of data throughout the execution of the program.</p>
<p>Popular statically-typed languages:</p>
<ul>
<li><p>C</p>
</li>
<li><p>C++</p>
</li>
<li><p>Java</p>
</li>
</ul>
<h3 id="heading-dynamically-typed-programming-languages">Dynamically-typed programming languages</h3>
<p>Dynamic-typing means variable data types are established during program execution, also known as <strong>runtime</strong>.</p>
<p>Variable data types are not explicitly stated in the source code and variables can be easily reassigned to store values of any datatype on the fly.</p>
<p>Popular dynamically-typed languages:</p>
<ul>
<li><p>Python</p>
</li>
<li><p>JavaScript</p>
</li>
<li><p>Ruby</p>
</li>
</ul>
<h3 id="heading-object-oriented-programming-languages">Object-oriented programming languages</h3>
<p>Object-oriented programming (OOP) is a coding paradigm that allows programmers to create and work with "objects". An object is a representation or model of something the programmer needs to describe via code.</p>
<p>This probably sounds super vague, because it is. Pretty much anything can be modeled as an "object" in code. Objects often represent real things, such as the products for sale in a store or the customers buying those products.</p>
<p>But objects can also represent digital things such as web forms, and even more abstract stuff like URL endpoints, network sockets, and so on.</p>
<p>Object-oriented programming is usually implemented in a language using <strong>Classes</strong>. You can think of a class as a template (or model) for the type of object that is being created.</p>
<p>A class contains a set of <strong>attributes</strong> (properties or characteristics) that define each object of the class. Classes also contain a set of <strong>methods</strong> (functions) that allow operations to be performed on specific objects of the class.</p>
<p>For example, a "Product" class might have the following attributes:</p>
<ul>
<li><p>Product SKU (unique identifier for each product)</p>
</li>
<li><p>Product name (descriptive name for each product)</p>
</li>
<li><p>Product type</p>
</li>
<li><p>Product price</p>
</li>
<li><p>Product discount</p>
</li>
</ul>
<p>As mentioned, a class is really just a template for <em>creating objects</em>. Creating an object using a class as a template is known as <strong>instantiation</strong>. You can create as many objects as you want from the same class, and each object created is known as an <strong>instance</strong> of that class. The instance is usually stored as a variable in code that you can use as you need it by interacting with its attributes and methods.</p>
<p>Continuing with our example, you can use our "Product" class above to create multiple objects of type "Product". Each product would have its own set of attribute values, such as SKU, name, type, price, and discount.</p>
<p>Representing structured sets of data in this object-oriented fashion can be a very intuitive way for programmers to write and organize their code. This is likely because humans tend to be naturally good at thinking in terms of identifiable entities that exist in the real world.</p>
<h2 id="heading-whats-the-difference-between-front-end-back-end-and-full-stack-development">What's the difference between front-end, back-end, and full-stack development?</h2>
<p>As a newer dev, you've likely browsed job opportunities in tech and noticed frequent mention of the terms "front-end", "back-end" and "full-stack".</p>
<p>These terms generally refer to the part of the application you'll be working on. Moreover, they also imply that you'll be working on a software application, usually a web application or mobile app.</p>
<p>The front end refers to the parts of the application that users (also known as "clients") interact with directly. For a web application, the front end is the collection of webpages (and functionality) that are presented in the user's browser. For a mobile app, the front end is the set of screens that the user interacts with on their mobile device.</p>
<p>Development tasks related to the front end include user experience design, user interface creation, client-side networking, integration and use of client-side libraries, and collecting/validating/submitting user input.</p>
<p>As a front-end dev, you'll implement these tasks primarily using HTML to define the structure of web pages, CSS to add styling, and JavaScript to add interactivity.</p>
<p>The back end refers to the parts of the application that run behind the scenes and aren't presented directly to the user/client.</p>
<p>The back end typically includes a web server which handles HTTP connections received from the front-end client (usually a web browser). The web server handles these connections and directs them to the back-end code which performs the logic necessary to respond to the client. This part of the back end is called <strong>routing</strong> or the <strong>API (application programming interface)</strong>.</p>
<p>The back-end code itself is traditionally a standalone monolith codebase that is deployed as a single unit. But depending on the application's architecture, the back-end code can operate as a set of <strong>serverless</strong> functions running on a cloud service as opposed to a standalone codebase.</p>
<p>The back-end code validates user input, applies business logic, interacts with data storage such as a database, and crafts a response that gets sent back to the front-end client.</p>
<p>Now that we've covered the front end and back end, full-stack development is easy! :) Full stack simply includes both the front end AND back end! The term "full stack" comes from the term "stack" which is a shortened form of "software stack". The software stack is the collection of tools, frameworks, programming languages, and operating systems that are used to support an application.</p>
<h2 id="heading-what-are-some-popular-software-stacks">What are some popular software stacks?</h2>
<p>Now that we know what a software stack is, we'll briefly discuss some popular options for you to choose from.</p>
<h3 id="heading-lamp-stack-linux-apache-mysql-php">LAMP Stack (Linux, Apache, MySQL, PHP)</h3>
<p>The LAMP stack is a time-tested and industry standard back-end stack that uses the Linux operating system as its foundation. On top of that, you use an Apache webserver to handle web requests and direct them to a PHP codebase. Data is stored in a MySQL database, which is a free and open-source (FOSS) relational database platform.</p>
<p>This stack is great for fairly standardized content-serving websites like blogs.</p>
<p>You might notice that I didn't explicitly mention any front-end tools as being a part of this stack – so this means that LAMP is a back-end stack.</p>
<h3 id="heading-mean-stack-mongodb-expressjs-angularjs-nodejs">MEAN Stack (MongoDB, Express.js, Angular.js, Node.js)</h3>
<p>The MEAN stack is a more modern stack that uses the MongoDB unstructured database platform for storing data. You use Express.js as the back-end web framework and Angular.js for the front end. Finally, you use Node.js to run JavaScript on the back end.</p>
<p>A major benefit of the MEAN stack is that all components are designed to natively operate using the JavaScript programming language, via JSON (JavaScript Object Notation).</p>
<p>Note that this stack's components are geared toward both the front end (Angular.js) and back end (MongoDB, Express.js, Node.js), so MEAN can be considered full stack.</p>
<h3 id="heading-mern-stack-mongodb-expressjs-reactjs-nodejs">MERN Stack (MongoDB, Express.js, React.js, Node.js)</h3>
<p>As you can probably see, the MERN stack is very similar to the MEAN stack except it uses React.js library as the front end instead of Angular.js.</p>
<p>This stack is well suited to devs who like React for its flexible and intuitive style of creating user interfaces.</p>
<h3 id="heading-notable-frameworks">Notable frameworks</h3>
<p>I wanted to take a brief moment to point out two other popular backend <em>frameworks</em> (not stacks) that you can incorporate or swap out for specific components of the stacks mentioned above.</p>
<p><strong>Spring Boot</strong> is a Java framework (technically a special case of the broader Spring Framework) that is excellent for developing back-end Java code for web applications and mobile apps. If you are new to Java coding, I highly recommend you check it out.</p>
<p><strong>Django</strong> is a Python framework that is specifically crafted for use with the Python programming language. If you prefer building web apps in Python, it is definitely worth looking into.</p>
<h2 id="heading-how-do-devs-collaborate-on-code-without-being-in-the-same-room">How do devs collaborate on code without being in the same room?</h2>
<p>When I started coding, I opened up a Python text editor on my local machine and created a single file which grew to contain all the code for my project. I quickly found that this became unruly, so I split my code up into several Python <code>.py</code> files (or modules as they are known).</p>
<p>When I coded with a friend, they would usually be sitting there behind me while I typed, or I would be sitting there behind them. If we needed to exchange code snippets or files, we would just send them back and forth via email.</p>
<p>It was years before I learned how devs successfully collaborate while coding, and that it is often done remotely.</p>
<p>The key to successful code collaboration is learning to use a <strong>Version Control System (VCS)</strong>. A VCS is a tool that tracks changes that multiple developers make to code files over time, and enables developers to efficiently work together on the same set files.</p>
<p>Version control systems create a <strong>repository</strong> that stores the data necessary to recreate any version of the code files as they existed at specific points in time. This is called <strong>version control</strong>.</p>
<p>Version control systems are very versatile tools, since they serve multiple useful functions for development teams:</p>
<ul>
<li><p>Tracks changes made to code files</p>
</li>
<li><p>Allows devs to easily share their changes with others and access changes made by others</p>
</li>
<li><p>Offers simple ways for merging code changes made by multiple devs or teams</p>
</li>
<li><p>Provides a full-history backup of a project's code as it evolves over time, and a way to efficiently restore any previous version of the code</p>
</li>
<li><p>Allows developers to easily manage code conflicts made on the same lines of the same files</p>
</li>
<li><p>Provides various other tools to improve team collaboration and efficiency</p>
</li>
</ul>
<p><a target="_blank" href="https://initialcommit.com/blog/Technical-Guide-VCS-Internals">There are many version control systems out there</a>, but you've almost certainly heard of one: GitHub.</p>
<p>Actually, GitHub itself is <em>not</em> a version control system. GitHub is a company that provides online hosting for projects using version control. GitHub gets its name from the specific version control system that it uses: <strong>Git</strong>.</p>
<p><a target="_blank" href="https://initialcommit.com/store/baby-git-guidebook-for-developers">The first version of Git</a> was created in 2005, and it has evolved into by far the most well-known and most popular version control system on the planet. Git is used by the vast majority of development teams today, and it is an <a target="_blank" href="https://initialcommit.com/store/coding-essentials-guidebook-for-developers">essential tool to learn if you plan on coding professionally</a>.</p>
<h2 id="heading-does-it-matter-what-operating-system-i-use">Does it matter what operating system I use?</h2>
<p>When it comes to learning to code for the first time, I would answer this question similarly to the first in this list. I think what matters much more than which operating system you have, is that you get started learning as soon as possible with what you have.</p>
<p>That being said, I feel my answer would be a cop-out if I leave it at that. Let's assume you're trying to make an active decision about what OS to choose for coding work.</p>
<p>Taking into account the fact that there are many subjective reasons people prefer <em>their</em> operating system, in my opinion an operating system that provides access to a quality command-line terminal can be very useful to wrap your head around.</p>
<p>For that reason, my preference is using <a target="_blank" href="https://en.wikipedia.org/wiki/Unix-like">Unix-like</a> operating systems such as a Linux flavor or MacOS if possible for development work. Full disclosure – I develop mostly on MacOS.</p>
<p>My reasoning for this is that learning to work on the command-line (much like learning to use Git) is an <a target="_blank" href="https://www.freecodecamp.org/news/how-to-learn-programming/">essential coding skill to learn</a>. A fully featured and intuitive command line is a core part of software development. In my opinion, Linux and MacOS better incorporate modern command lines than Windows.</p>
<h2 id="heading-what-text-editor-or-ide-should-i-use">What text editor or IDE should I use?</h2>
<p>Text editors and IDE's (Integrated Development Environments) have evolved massively over the years, and developers pick favorites for many reasons.</p>
<p>One reason could be that a particular editor or IDE was created specifically for a particular programming language or framework. Another could be that your company uses a specific editor, so that is the one you learned and stuck with. I found this reason to be especially true in my experience.</p>
<p>If you are primarily working with interpreted, dynamically-typed languages such as Python, JavaScript, Ruby, or PHP, I recommend that you start with a GUI-based editor such as Sublime Text or Visual Studio Code. These are two of the most popular text editors out there and provide a plethora of features and customizations to make your life easier as a developer.</p>
<p>If you work with Java, I recommend either Eclipse or IntelliJ IDEA which offer a multitude of features specifically crafted for working in the Java ecosystem.</p>
<p>Finally, regardless of which editor you choose for your main dev work, I recommend that you learn <a target="_blank" href="https://initialcommit.com/blog/7-versatile-vim-commands">a bit of Vim</a>. Vim is a text editor that is meant to be used directly within your command-line terminal. It definitely takes more time to get used to since you have to learn to use Vim's keyboard commands to interact with your files instead of point-and-click with your mouse.</p>
<p>But in my experience is well worth it. Even if you only learn the basic commands, these will help you immensely if you find yourself browsing through a non-GUI terminal at work, and need to inspect or modify some files.</p>
<p>I highly recommend the built-in Vimtutor program that is downloaded automatically when you install Vim. It walks through the basic directly in your command-line terminal.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, I discussed 7 questions commonly asked by new coders. We cast a fairly wide net, covering questions about programmings language selection, software dev stacks, operating systems, and text editors.</p>
<p>If there are any questions you have that I didn't cover, feel free to message me at <a target="_blank" href="mailto:jacob@initialcommit.io">jacob@initialcommit.io</a>.</p>
<h2 id="heading-next-steps">Next steps</h2>
<p>If you got value out of this article, I wrote a book called <a target="_blank" href="https://initialcommit.com/store/coding-essentials-guidebook-for-developers">Coding Essentials Guidebook for Developers</a> which has 14 chapters, each covering a core coding concept, language, or tool.</p>
<p>Topics include computer architecture, the Internet, Command Line, HTML, CSS, JavaScript, Python, Java, SQL, Git, and more.</p>
<p>These topics were meticulously selected to help put together a bigger picture of the development puzzle, instead of focusing on one topic in depth. This might be a good resource for you to check out if you got value out of this article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Why Are There So Many Programming Languages? ]]>
                </title>
                <description>
                    <![CDATA[ By Vasyl Lagutin There are so many programming languages out there, and more are developed every few years. We have Python, JavaScript, PHP, C++, Ruby, Java, C#, and way too many more to list here.  So you might be wondering – why are there so many p... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/why-are-there-so-many-programming-languages/</link>
                <guid isPermaLink="false">66d45e0a182810487e0ce13b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 14 Sep 2021 16:11:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/joshua-coleman-fXls-tVemno-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Vasyl Lagutin</p>
<p>There are so many programming languages out there, and more are developed every few years. We have Python, JavaScript, PHP, C++, Ruby, Java, C#, and way too many more to list here. </p>
<p>So you might be wondering – why are there so many programming languages, and do we even need all of them?</p>
<p>In this article, you will learn why developers keep creating more programming languages and how you can choose which one to learn.</p>
<h2 id="heading-the-evolution-of-technology-and-programming-languages">The Evolution of Technology and Programming Languages</h2>
<p>The first and perhaps the biggest reason why we have so many programming languages is that technology is always evolving. As more technologies come into being and advance, we need more tools that can make software for these technologies.</p>
<p>The programming languages we currently have might not be able to deal with specific problems that arise because of the nature of the languages' capabilities. The issue might be so unique that there are no existing solutions that address their needs, so people or companies decide to create a new language themselves.</p>
<p>Here are some notable examples of programming languages that developed from specific needs:</p>
<ol>
<li><strong>C</strong> – Dennis Ritchie and Bell Labs created C in 1972 to overcome older languages' problems. They first used it to run the Unix operating system. Today, it can run on almost all kinds of software and hardware.</li>
<li><strong>C++</strong> – Bjarne Stroustrup create C++ in 1985 for two main reasons. The first reason was to upgrade the features of the C programming language, and the second reason was to make it accessible for everyone to use in all fields.</li>
<li><strong>PHP</strong> – PHP was created in 1994 by Rasmus Lerdorf, and he initially used it for a personal project. Later he improved the language and released it to the public, and developers started using it heavily for web development.</li>
<li><strong>Go</strong> – Google created Go in 2009 because the languages they worked with at the time took were too slow and inconvenient for certain tasks. Also, Google wanted a programming language that was fast in performance but still relatively simple to read.</li>
<li><strong>JavaScript</strong> – Netscape created JavaScript in 1995. They initially created it for front end development so both web developers and designers could learn and create website features in a short timeframe. Now we use it for back end, front end, and mobile development.</li>
</ol>
<h2 id="heading-different-kinds-of-developer-jobs-require-different-languages">Different Kinds of Developer Jobs Require Different Languages</h2>
<p>Another reason we have so many programming languages is that there are different kinds of developer jobs out there that require different tools.</p>
<p>Think of it like a doctor and their patients. A doctor's job is to treat patients. There are different kinds of illness and injuries, and each one is complex enough to treat with different remedies. So doctors specialize in certain areas such as a cardiology, dentistry, surgery, and so on.</p>
<p>The same is true for programmers. As there are different kinds of software and platforms, each one requiring its own tools and features, programmers can specialize just like doctors.</p>
<p>Here are some developer jobs and the main programming languages they use:</p>
<ul>
<li>Game developers use C++ or C# to make video games for PCs and consoles.</li>
<li>Web developers use HTML, CSS, JavaScript, and PHP to make websites and web applications.</li>
<li>Mobile app developers use Java and Kotlin to make Android applications or use Swift to make iOS applications.</li>
<li>Software developers use C++, C#, and Java to make desktop applications, business applications, and system software.</li>
<li>Data scientists use Python, R, and MatLab to analyze data for scientific research and educational purposes.</li>
</ul>
<p>These aren't the only languages you can use to perform these tasks. These are just examples of some of the most commonly used.</p>
<h2 id="heading-developer-have-different-needs-and-goals-for-their-projects">Developer Have Different Needs and Goals for their Projects</h2>
<p>The third reason there are so many programming languages is that not all of them will meet a developer or a company's goals. Different developers have their own goals and priorities, and some programming languages are better suited for certain types of tasks than others.</p>
<ul>
<li>Some developers want a programming language that's super fast and performant. Welcome Go or C++. These languages enable very granular control over system resources like memory and threads.</li>
<li>Other developers want a programming language that can build the program in a few days and not weeks. Say hello to JavaScript! It's hard to find a more versatile language. You can <a target="_blank" href="https://learn.coderslang.com/0102-what-can-i-do-with-javascript/">use JS everywhere from the backend to web and mobile apps</a>.</li>
<li>Then some developers prefer a programming language for a specific task. In 2021 a ton of data science gets delivered in Python.</li>
<li>And finally, some developers want a programming language that is fun to work with. Try Haskell or Lisp and let me know how it goes :)</li>
</ul>
<h2 id="heading-how-to-choose-a-programming-language">How to Choose a Programming Language</h2>
<p>Now that you understand why there are so many programming languages, there is one more question you are probably asking next:</p>
<p>Which programming language should I learn?</p>
<p>Luckily, there is a pretty straightforward answer: instead of looking at the programming languages themselves, you should think of your end goals. </p>
<p>What type of programming job do you want to work in? What do you want to build? What do job postings require in your area? Once you look at these factors, you can pick a programming language that helps you achieve your goal.</p>
<p>For example, if your goal is to make a professional website, then learn HTML, CSS, and JavaScript. </p>
<p>If you want to break into game development, then go for C++ and C#. </p>
<p>Or, if you wish to start your career in mobile applications, you should check out Swift for iOS applications and Java or Kotlin for Android applications.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>To sum it up, the main reason why there are many programming languages out there is that different problems require different tools to solve them. Each programming language has certain features and characteristics that make it suitable for specific tasks.</p>
<p>Just like how doctor's jobs are divided into various specialties, and each solves complex problems and uses the right tools for their job, the same is true for programming.</p>
<p>I hope this article has answered your questions and given you a better idea of what programming language to choose for your career as a programmer.</p>
<p>If you want to learn more, you can get my <a target="_blank" href="https://learn.coderslang.com/free-ebooks/">free e-book</a> to prepare for technical interviews or start <a target="_blank" href="https://js.coderslang.com/">Learning Full-Stack JavaScript</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python VS JavaScript – What are the Key Differences Between The Two Popular Programming Languages? ]]>
                </title>
                <description>
                    <![CDATA[ Welcome! If you want to learn the differences between Python and JavaScript, then this article is for you.  These two languages are very popular and powerful, but they do have key differences. We will cover them in detail here. In this article, you w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-vs-javascript-what-are-the-key-differences-between-the-two-popular-programming-languages/</link>
                <guid isPermaLink="false">66b1f87d32a6794893871316</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Estefania Cassingena Navone ]]>
                </dc:creator>
                <pubDate>Thu, 28 Jan 2021 16:04:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/Python-vs.-JavaScript-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><strong>Welcome!</strong> If you want to learn the differences between Python and JavaScript, then this article is for you. </p>
<p>These two languages are very popular and powerful, but they do have key differences. We will cover them in detail here.</p>
<p><strong>In this article, you will learn:</strong></p>
<ul>
<li>The different real-world applications of Python and JavaScript.</li>
<li>The key syntactic and functional differences between Python and JavaScript.</li>
</ul>
<p><strong>Let's begin!</strong> ✨</p>
<h2 id="heading-python-vs-javascript-real-world-applications">🔹 Python VS JavaScript: Real-World Applications</h2>
<p>We will start with a quick tour of their real-world applications.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-187.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-python">Python</h3>
<p>Python has become an essential tool in virtually every scientific application around the world because of its power and versatility. It is a general-purpose programming language that supports different programming paradigms.</p>
<p>It is widely used in scientific and specialized applications, including data science, artificial intelligence, machine learning, computer science education, computer vision and image processing, medicine, biology, and even astronomy. </p>
<p>It is also used for web development. This is where we can start to compare its applications to the applications of JavaScript. Python is used for back-end development, which is the area of web development in charge of creating the elements that users don't see, such as the server side of an application. </p>
<h3 id="heading-javascript">JavaScript</h3>
<p>While Python can be used to develop the back-end part of a web application, JavaScript can be used to develop both the back-end and the front-end of the application. </p>
<p>The front-end is the part of the application that the user sees and interacts with. Whenever you see or interact with a website or web application, you are using JavaScript "behind the scenes". </p>
<p>Similarly, when you interact with a mobile app, you might be using JavaScript because frameworks like <a target="_blank" href="https://reactnative.dev/">React Native</a> let us write applications that adapt to different platforms.</p>
<p>JavaScript is so widely used in web development because it is a versatile language that gives us the tools we need to develop the components of a web application. </p>
<h3 id="heading-differences-between-the-applications-of-python-and-javascript">Differences between the applications of Python and JavaScript</h3>
<p>In short, developers use Python for a range of scientific applications. They use JavaScript for web development, user-facing functionality, and servers</p>
<h2 id="heading-python-vs-javascript-syntax">🔸 Python VS JavaScript: Syntax</h2>
<p>Now that you know what they are used for, let's see how they are written and the differences in their syntax.</p>
<p>We will cover the differences in their main elements:</p>
<ul>
<li>Code Blocks</li>
<li>Variable Definitions</li>
<li>Variable Naming Conventions</li>
<li>Constants</li>
<li>Data Types and Values</li>
<li>Comments</li>
<li>Built-in Data Structures</li>
<li>Operators</li>
<li>Input/Output</li>
<li>Conditional Statements</li>
<li>For Loops and While Loops</li>
<li>Functions</li>
<li>Object-Oriented Programming</li>
</ul>
<h2 id="heading-code-blocks-in-python-and-javascript">Code Blocks in Python and JavaScript</h2>
<p>Each programming language has its own style to define code blocks. Let's see their differences in Python and JavaScript:</p>
<h3 id="heading-how-python-defines-code-blocks">How Python defines code blocks</h3>
<p>Python relies on indentation to define code blocks. When a series of continuous lines of code are indented at the same level, they are considered part of the same code block. </p>
<p>We use this to define conditionals, functions, loops, and basically every compound statement in Python. </p>
<p>These are some examples:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-127.png" alt="Image" width="600" height="400" loading="lazy">
<em>Use of indentation to define code blocks in Python</em></p>
<p><strong>💡 Tip:</strong> We will see the specific differences between these elements in Python and JavaScript in just a moment. At this moment, please focus on the indentation.</p>
<h3 id="heading-how-javascript-defines-code-blocks">How JavaScript defines code blocks</h3>
<p>In contrast, in JavaScript we use curly braces (<code>**{}**</code>) to group statements that belong to the same code block. </p>
<p>These are some examples:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-128.png" alt="Image" width="600" height="400" loading="lazy">
<em>Use of curly braces to define code blocks in JavaScript</em></p>
<h2 id="heading-variable-definitions-in-python-and-javascript">Variable Definitions in Python and JavaScript</h2>
<p>The assignment statement is one of the most fundamental statements in any programming language. Let's see how we can define a variable in Python and JavaScript.</p>
<h3 id="heading-how-to-define-a-variable-in-python">How to define a variable in Python</h3>
<p>To define a variable in Python, we write the name of the variable followed by an equal sign (<code>**=**</code>) and the value that will be assigned to the variable. </p>
<p>Like this:</p>
<pre><code class="lang-python">&lt;variable_name&gt; = &lt;value&gt;
</code></pre>
<p>For example:</p>
<pre><code class="lang-python">x = <span class="hljs-number">5</span>
</code></pre>
<h3 id="heading-how-to-define-a-variable-in-javascript">How to define a variable in JavaScript</h3>
<p>The syntax is very similar in JavaScript, but we just need to add the keyword <code>**var**</code> or <code>**let**</code> before the name of the variable and end the line with a semicolon (<code>**;**</code>). </p>
<p>Like this:</p>
<pre><code><span class="hljs-keyword">var</span> &lt;variable_name&gt; = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>;</span>
</code></pre><p><strong>💡 Tip:</strong> When you define a variable using <code>**var**</code>, the variable has function scope. </p>
<p>For example:</p>
<pre><code><span class="hljs-keyword">var</span> x = <span class="hljs-number">5</span>;
</code></pre><p>We can also use the keyword <code>**let**</code>:</p>
<pre><code><span class="hljs-keyword">let</span> &lt;variable_name&gt; = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>;</span>
</code></pre><p>For example:</p>
<pre><code><span class="hljs-keyword">let</span> x = <span class="hljs-number">5</span>;
</code></pre><p><strong>💡 Tip:</strong> In this case, when we use <code>**let**</code>, the variable will have block scope. It will only be recognized in the code block where it was defined. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-125.png" alt="Image" width="600" height="400" loading="lazy">
<em>Variable definitions in Python and JavaScript</em></p>
<p>💡 <strong>Tip:</strong> In JavaScript, the end of a statement is marked with a semicolon (<code>;</code>) but in Python, we just start a new line to mark the end of a statement. </p>
<h2 id="heading-variable-naming-conventions-in-python-and-javascript">Variable Naming Conventions in Python and JavaScript</h2>
<p>Python and JavaScript follow two different variable naming conventions.</p>
<h3 id="heading-how-to-name-variables-in-python">How to name variables in Python</h3>
<p>In Python, we should use the <code>**snake_case**</code> naming style.</p>
<p>According to the <a target="_blank" href="https://www.python.org/dev/peps/pep-0008/#function-and-variable-names">Python Style Guide</a>:</p>
<blockquote>
<p>Variable names follow the same convention as function names.  </p>
<p>Function names should be <strong>lowercase, with words separated by underscores</strong> as necessary to improve readability.</p>
</blockquote>
<p>Therefore, a typical variable name in Python would look like this:</p>
<pre><code class="lang-python">first_name
</code></pre>
<p>💡 <strong>Tip:</strong> The style guide also mentions that "<code>**mixedCase**</code> is allowed only in contexts where that's already the prevailing style, to retain backwards compatibility."</p>
<h3 id="heading-how-to-name-variables-in-javascript">How to name variables in JavaScript</h3>
<p>In contrast, we should use the <code>**lowerCamelCase**</code> naming style in JavaScript. The name starts with a lowercase letter and then every new word starts with an uppercase letter. </p>
<p>According to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/MDN/Guidelines/Code_guidelines/JavaScript#Variable_naming">JavaScript guidelines</a> article by the MDN Web Docs:</p>
<blockquote>
<p>For variable names use lowerCamelCasing, and use concise, human-readable, semantic names where appropriate.</p>
</blockquote>
<p>Therefore, a typical variable name in JavaScript should look like this:</p>
<pre><code class="lang-javascript">firstName
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-178.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-constants-in-python-and-javascript">Constants in Python and JavaScript</h2>
<p>Great. Now you know more about variables, so let's talk a little bit about constants. Constants are values that cannot be changed during the execution of the program. </p>
<h3 id="heading-how-to-define-constants-in-python">How to define constants in Python</h3>
<p>In Python, we rely on naming conventions to define constants because there are no strict rules in the language to prevent changes to their values.</p>
<p>According to the <a target="_blank" href="https://www.python.org/dev/peps/pep-0008/#constants">Python Style Guide</a>:</p>
<blockquote>
<p>Constants are usually defined on a module level and <strong>written in all capital letters with underscores separating words</strong>. </p>
</blockquote>
<p>This is the naming style that we should use to define a constant in Python:</p>
<pre><code>CONSTANT_NAME
</code></pre><p>For example:</p>
<pre><code class="lang-javascript">TAX_RATE_PERCENTAGE = <span class="hljs-number">32</span>
</code></pre>
<p>💡 <strong>Tip:</strong> This serves as a red warning for ourselves and for other developers indicating that this value should not be modified in the program. But technically, the value can still be modified. </p>
<h3 id="heading-how-to-define-constants-in-javascript">How to define constants in JavaScript</h3>
<p>In contrast, in JavaScript we can define constants that cannot be changed in the program, and the variable identifier cannot be reassigned. </p>
<p>But this does not mean that the value itself cannot be changed. </p>
<p>According to the article <code>**const**</code> in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">MDN Web Docs</a>:</p>
<blockquote>
<p>The <code>const</code> declaration creates a read-only reference to a value. It does <strong>not</strong> mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.</p>
</blockquote>
<p>To define a constant in JavaScript, we add the keyword <code>**const**</code> before the name of the variable:</p>
<pre><code><span class="hljs-keyword">const</span> TAX_RATE_PERCENTAGE = <span class="hljs-number">32</span>;
</code></pre><p>If we try to change the value of the constant, we will see this error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-180.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Therefore, the value cannot be changed. </p>
<p><strong>💡 Tip:</strong> To run and test small code snippets of JavaScript code, you can use the <a target="_blank" href="https://developers.google.com/web/tools/chrome-devtools/console">console in Chrome Developer Tools</a>. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-181.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-data-types-and-values-in-python-and-javascript">Data Types and Values in Python and JavaScript</h2>
<p>Let's see the main differences between Python and JavaScript data types. </p>
<h3 id="heading-numeric-data-types">Numeric Data Types</h3>
<p><strong>Python</strong> has three numeric types to help us perform precise calculations for scientific purposes. These numeric types include: <code>int</code> (integers),  <code>float</code> (floating-point numbers), and <code>complex</code>. Each one of them has its own properties, characteristics, and applications. </p>
<p>In contrast, <strong>JavaScript</strong> has only two numeric types: <code>**Number**</code> and <code>**BigInt**</code>. Integers and floating-point numbers are both considered to be of type <code>**Number**</code>. </p>
<p>According to the article <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a> in MDN Web Docs:</p>
<blockquote>
<p>A number literal like <code>37</code> in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript now has a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt">BigInt</a> type, but it was not designed to replace Number for everyday uses. <code>37</code> is still a Number, not a BigInt.)</p>
</blockquote>
<h3 id="heading-none-vs-null">None vs. null</h3>
<p>In <strong>Python</strong>, there is a special value called <code>**None**</code> that we typically use to indicate that a variable doesn't have a value at a particular point in the program. </p>
<p>The equivalent value in <strong>JavaScript</strong> is <code>**null**</code>, which "represents the intentional absence of any object value" (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null">source</a>).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-144.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-undefined-value">The <code>undefined</code> Value</h3>
<p>In <strong>JavaScript</strong>, we have a special value that is assigned automatically when we declare a variable without assigning an initial value.</p>
<p>This is an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-142.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, the value of the variable <code>**x**</code> is <code>**undefined**</code>.</p>
<p>In <strong>Python</strong>, you have to assign an initial value to the variable. We can't declare it without an initial value.</p>
<p><strong>💡 Tip:</strong> You can assign <code>**None**</code> as the initial value of a variable in Python to represent the absence of a value.</p>
<h3 id="heading-primitive-data-types-in-python-and-javascript">Primitive Data Types in Python and JavaScript</h3>
<p>Primitive data types represent the most fundamental values that we can work with in a programming language. Let's compare the primitive data types of these two languages:</p>
<ul>
<li><strong>Python</strong> has four primitive data types: Integers (<code>int</code>), Floats (<code>float</code>), Booleans (<code>bool</code>), and strings (<code>str</code>).</li>
<li><strong>JavaScript</strong> has seven primitive data types: <code>undefined</code><strong>,</strong> Boolean, String, Number, <code>BigInt</code>, <code>Symbol</code>, and <code>null</code> (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">source</a>).</li>
</ul>
<h2 id="heading-how-to-write-comments-in-python-and-javascript">How to Write Comments in Python and JavaScript</h2>
<p>Comments are very important to write clean and readable code. Let's see how you can use them in Python and JavaScript:</p>
<h3 id="heading-single-line-comments">Single-Line Comments</h3>
<ul>
<li>In <strong>Python</strong>, we use a hashtag (<code>**#**</code>) to write a comment. All the characters on the same line after this symbol are considered part of the comment. </li>
<li>In <strong>JavaScript</strong>, we write two slashes (<code>**//**</code>) to start a single-line comment. </li>
</ul>
<p>This is a graphical example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-145.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Comment</span>
</code></pre>
<p>In JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Comment</span>
</code></pre>
<h3 id="heading-multi-line-comments">Multi-Line Comments</h3>
<ul>
<li>In <strong>Python</strong>, to write a multi-line comment we start each line with a hashtag.</li>
<li>In <strong>JavaScript</strong>, multi-line comments start with a <code>**/***</code> and end with a <code>***/**</code>. All the characters between these symbols are considered part of the comment. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-146.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Multi-line comment </span>
<span class="hljs-comment"># in Python to explain</span>
<span class="hljs-comment"># the code in detail.</span>
</code></pre>
<p>In JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* 
Multi-line comment 
in JavaScript to explain 
the code in detail.
*/</span>
</code></pre>
<h2 id="heading-built-in-data-structures-in-python-and-javascript">Built-in Data Structures in Python and JavaScript</h2>
<p>The built-in data structures in Python and JavaScript also have key differences. </p>
<h3 id="heading-tuples">Tuples</h3>
<ul>
<li>In <strong>Python</strong>, we have a built-in data structure called <strong>tuple</strong> that is very similar to a list but immutable. Therefore, it cannot be changed during the execution of the program, so it is used to store data that should not be modified.</li>
<li>In <strong>JavaScript</strong>, there isn't a built-in data structure with these characteristics. Although you can implement a similar data structure with certain features of the language.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-182.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-lists-vs-arrays">Lists vs. Arrays</h3>
<ul>
<li>In <strong>Python,</strong> <strong>lists</strong> are used to store a sequence of values in the same data structure. They can be modified, indexed, sliced, and used in the program. </li>
<li>In <strong>JavaScript</strong>, an equivalent version of this data structure is called <strong>array</strong>.</li>
</ul>
<p>This is an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-147.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-hash-tables">Hash Tables</h3>
<ul>
<li>In <strong>Python</strong>, there is a built-in data structure called <strong>dictionary</strong> that helps us map certain values to other values and create key-value pairs. This works as a hash table. </li>
<li><strong>JavaScript</strong> doesn't have this type of built-in data structure, but there are certain ways to reproduce its functionality with certain elements of the language. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-183.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-operators-in-python-and-javascript">Operators in Python and JavaScript</h2>
<p>Operators are essential to write expressions in any programming language. Let's see their key differences in Python and JavaScript.</p>
<h3 id="heading-floor-division">Floor Division</h3>
<p>While most of the arithmetic operators work exactly the same in Python and JavaScript, the floor division operator is a little bit different. </p>
<ul>
<li>In <strong>Python</strong>, the floor division operation (also called "integer division") is represented with a double slash (<code>**//**</code>).</li>
<li>In <strong>JavaScript</strong>, we don't have a particular floor division operator. Instead, we call the <code>**Math.floor()**</code> method to round down the result to the nearest integer.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-149.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-comparing-values-and-types">Comparing Values and Types</h3>
<p>In <strong>Python</strong>, we use the <code>**==**</code> operator to compare if two values and their data types are equal. </p>
<p>For example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Comparing Two Integers</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-number">0</span> == <span class="hljs-number">0</span>     
<span class="hljs-literal">True</span>
<span class="hljs-comment"># Comparing Integer to String</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-number">0</span> == <span class="hljs-string">"0"</span>
<span class="hljs-literal">False</span>
</code></pre>
<p>In <strong>JavaScript</strong>, we also have this operator but it works a little bit differently because it converts the two objects to the same type before actually performing the comparison. </p>
<p>If we check the result of the "integer vs. string" comparison from the previous example using JavaScript (<code>0 == "0"</code>), the result is <code>**True**</code> instead of <code>**False**</code> because the values are converted to the same data type before being compared:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-150.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In JavaScript, to check if the value <strong>and</strong> the data type are both equal, we need to use this operator <code>**===**</code> (a triple equal sign). </p>
<p>Now we get the result that we were expecting:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-151.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Awesome, right? </p>
<p><strong>💡 Tip:</strong> The <code>**==**</code> operator in Python works like the <code>**===**</code> operator in JavaScript. </p>
<h3 id="heading-logical-operators">Logical Operators</h3>
<ul>
<li>In <strong>Python</strong>, the three logical operators are: <code>**and**</code>, <code>**or**</code>, and <code>**not**</code>.</li>
<li>In <strong>JavaScript</strong>, these operators are: <code>**&amp;&amp;**</code>, <code>**||**</code>, and <code>**!**</code> (respectively).</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-152.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-type-operators">Type Operators</h3>
<ul>
<li>In <strong>Python</strong>, to check the type of an object we use the <code>**type()**</code> function.</li>
<li>In <strong>JavaScript</strong>, we use the <code>**typeof**</code> operator.</li>
</ul>
<p>This is a graphical description of their syntax:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-153.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-input-and-output-in-python-and-javascript">Input and Output in Python and JavaScript</h2>
<p>Asking for user input and displaying values to the user are very common operations. Let's see how you can do this in Python and JavaScript:</p>
<h3 id="heading-input">Input</h3>
<ul>
<li>In <strong>Python</strong>, we use the <code>**input()**</code> function to ask for user input. We write the message within parentheses. </li>
<li>In <strong>JavaScript</strong>, one alternative (if you are running the code on a browser) is to display a small prompt with <code>**window.prompt(message)**</code> and assign the result to a variable. </li>
</ul>
<p>The main difference between these two approaches is that in Python, the user will be prompted to enter a value in the console while in JavaScript, a small prompt will be displayed on the browser and it will ask the user to enter a value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-161.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> You will see this in the Python console to enter a value:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-184.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In JavaScript, if you open Chrome Developer tools and enter this line of code in the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-163.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This prompt will be displayed:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-162.png" alt="Image" width="600" height="400" loading="lazy">
<em>Prompt displayed when window.prompt() is called</em></p>
<h3 id="heading-output">Output</h3>
<ul>
<li>In <strong>Python</strong>, we print a value to the console with the <code>**print()**</code> function, passing the value within parentheses. </li>
<li>In <strong>JavaScript</strong>, we print a value to the console using <code>**console.log()**</code>, passing the value within parentheses as well.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-164.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> If you are working on a browser, you can also call <code>**alert()**</code> to display a small prompt with the message (or value) passed within parentheses. </p>
<h2 id="heading-conditional-statements-in-python-and-javascript">Conditional Statements in Python and JavaScript</h2>
<p>With conditionals, we can choose what happens in the program based on whether a specific condition is <code>**True**</code> or <code>**False**</code>. Let's see their differences in Python and JavaScript.</p>
<h3 id="heading-if-statement"><code>if</code> Statement</h3>
<ul>
<li>In <strong>Python</strong>, we rely on indentation to indicate which lines of code belong to the conditional. </li>
<li>In <strong>JavaScript</strong>, we have to surround the condition with parentheses and the code with curly braces. The code should also be indented.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-154.png" alt="Image" width="600" height="400" loading="lazy">
<em>Conditional in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-ifelse-statement"><code>if/else</code> Statement</h3>
<p>The else clause is very similar in both languages. The only difference is that:</p>
<ul>
<li>In <strong>Python</strong>, we write a colon (<code>**:**</code>) after the <code>**else**</code> keyword </li>
<li>In <strong>JavaScript</strong>, we surround the code that belongs to this clause with curly braces (<code>**{}**</code>) . </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-155.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-multiple-conditions">Multiple Conditions</h3>
<p>To write multiple conditions:</p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>**elif**</code> followed by the condition. After the condition, we write a colon (<code>:</code>) and the code indented on the next line.</li>
<li>In <strong>JavaScript</strong>, we write the keywords <code>**else if**</code> followed by the condition (surrounded by parentheses). After the condition, we write curly braces and the code indented within the braces. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-156.png" alt="Image" width="600" height="400" loading="lazy">
<em>Conditional in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-switch-in-javascript">Switch in JavaScript</h3>
<ul>
<li>In <strong>JavaScript</strong>, we have an additional control structure that we can use to choose what happens based on the value of an expression. This statement is called <code>**switch**</code>.</li>
<li><strong>Python</strong> doesn't have this type of built-in control structure.</li>
</ul>
<p>This is the general syntax of this statement:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-159.png" alt="Image" width="600" height="400" loading="lazy">
<em>Switch statement in JavaScript</em></p>
<p>In JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">switch</span> (expression) {
    <span class="hljs-keyword">case</span> value1:
        <span class="hljs-comment">// Code</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> value2:
        <span class="hljs-comment">// Code</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> value3:
        <span class="hljs-comment">// Code</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">default</span>:
        <span class="hljs-comment">// Code</span>
}
</code></pre>
<p><strong>💡 Tip:</strong> We can add as many cases as we need and the expression can be a variable.</p>
<h2 id="heading-for-loops-and-while-loops-in-python-and-javascript">For Loops and While Loops in Python and JavaScript</h2>
<p>Now let's see how we can define different types of loops in Python and JavaScript and their main differences. </p>
<h3 id="heading-for-loops">For Loops</h3>
<p>The syntax to define a for loop in Python is relatively simpler than the syntax in JavaScript. </p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>for</code> followed by the name of the loop variable, the keyword <code>in</code>, and a call to the <code>range()</code> function specifying the necessary parameter(s). Then, we write a colon (<code>:</code>) followed by the body of the loop indented. </li>
<li>In <strong>JavaScript</strong>, we have to specify several values explicitly. We start with the <code>for</code> keyword followed by parentheses. Within those parentheses, we define the loop variable with its initial value, the condition that must be <code>False</code> to stop the loop, and how the variable will be updated on every iteration. Then, we write curly braces to create a code block and within the braces we write the body of the loop indented. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-165.png" alt="Image" width="600" height="400" loading="lazy">
<em>For Loop in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-iterating-over-iterables">Iterating Over Iterables</h3>
<p>We can use a for loop in Python and JavaScript to iterate over the elements of an iterable.</p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>for</code> followed by the loop variable, the <code>in</code> keyword, and the iterable. Then, we write a colon (<code>:</code>) and the body of the loop (indented).</li>
<li>In <strong>JavaScript</strong>, we can use a <code>**for .. of**</code> loop. We write the <code>for</code> keyword followed by parentheses and within those parentheses, we write the keyword <code>var</code> or <code>let</code> followed by the loop variable, the keyword <code>of</code>, and the iterable. We surround the body of the loop with curly braces and then we indent it.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-167.png" alt="Image" width="600" height="400" loading="lazy">
<em>For Loop in Python (left) and JavaScript (right)</em></p>
<p>In <strong>JavaScript</strong>, we also have <code>**for .. in**</code> loops to iterate over the properties of an object.</p>
<p>According to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">MDN Web Docs</a>:</p>
<blockquote>
<p>The <strong><code>for...in</code> statement</strong> iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.</p>
</blockquote>
<p>This is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">c</span>: <span class="hljs-number">3</span> };

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> property <span class="hljs-keyword">in</span> object) {
  <span class="hljs-built_in">console</span>.log(property, object[property]);
}
</code></pre>
<p>The output when we run this code in the console of Chrome Developer Tools is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-168.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-while-loops">While Loops</h3>
<p>While loops are very similar in Python and JavaScript. </p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>while</code> followed by the condition, a colon (<code>:</code>), and in a new line, the body of the loop (indented).</li>
<li>In <strong>JavaScript</strong>, the syntax is very similar. The differences are that we have to surround the condition with parentheses and the body of the loop with curly braces.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-169.png" alt="Image" width="600" height="400" loading="lazy">
<em>While Loop in Python (left) and JavaScript (right)</em></p>
<h3 id="heading-dowhile-loops-in-javascript"><code>do..while</code> Loops in JavaScript</h3>
<p>In <strong>JavaScript</strong>, we also have a type of loop that doesn't exist in Python. </p>
<p>This type of loop is called a <code>**do..while**</code> loop because it does something at least once and it continues running while a condition is <code>True</code>. </p>
<p>This is the basic syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">do</span> {
    <span class="hljs-comment">// Code</span>
} <span class="hljs-keyword">while</span> (condition);
</code></pre>
<p>💡 <strong>Tip:</strong> This type of loop guarantees that the code will be executed at least once. </p>
<p>This is particularly helpful when we ask for user input because the user will be prompted to enter the input. If the input is valid, we can continue with the program. But if it's not valid, we can prompt the user to enter the value again until it is valid.</p>
<h2 id="heading-functions-in-python-and-javascript">Functions in Python and JavaScript</h2>
<p>Functions are incredibly important to write concise, maintainable, and readable programs. The syntax is very similar in Python and JavaScript, but let's analyze their key differences:</p>
<ul>
<li>In <strong>Python</strong>, we write the keyword <code>**def**</code> followed by the name of the function, and within parentheses the parameters list. After this list, we write a colon (<code>:</code>) and the body of the function (indented). </li>
<li>In <strong>JavaScript</strong>, the only differences are that we define a function using the <code>**function**</code> keyword and surround the body of the function with curly braces. </li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-170.png" alt="Image" width="600" height="400" loading="lazy">
<em>Function in Python (top) and JavaScript (bottom)</em></p>
<p>In addition, there is a very important difference between Python and JavaScript functions:</p>
<h3 id="heading-number-of-function-arguments">Number of Function Arguments</h3>
<ul>
<li>In <strong>Python</strong>, the number of arguments passed to the function call has to match the number of parameters defined in the function definition (unless default values have been assigned for them in the function definition). If this is not the case, an exception will occur.</li>
</ul>
<p>This is an example:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">foo</span>(<span class="hljs-params">x, y</span>):</span>
    print(x, y)


<span class="hljs-meta">&gt;&gt;&gt; </span>foo(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#3&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    foo(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
TypeError: foo() takes <span class="hljs-number">2</span> positional arguments but <span class="hljs-number">3</span> were given
</code></pre>
<ul>
<li>In <strong>JavaScript</strong>, this is not necessary since parameters are optional. You can call a function with fewer or more arguments than the parameters that were defined in the function definition. Missing arguments are assigned the value <code>**undefined**</code> by default and extra arguments can be accessed with the <code>**arguments**</code> object.</li>
</ul>
<p>This is an example in JavaScript:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-171.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice how the function was called with three arguments but only two parameters were included in the parameters list of the function definition.</p>
<p>💡 <strong>Tip:</strong> To get the number of arguments passed to the function, you can use <strong><code>arguments.length</code></strong> within the function. </p>
<h2 id="heading-object-oriented-programming-in-python-and-javascript">Object-Oriented Programming in Python and JavaScript</h2>
<p>Both Python and JavaScript support Object-Oriented Programming, so let's see how you can create and use the main elements of this programming paradigm.</p>
<h3 id="heading-classes">Classes</h3>
<p>The first line of a class definition is very similar in Python and JavaScript. We write the keyword <code>**class**</code> followed by the name of the class. </p>
<p>The only difference is that:</p>
<ul>
<li>In <strong>Python</strong>, after the name of the class, we write a colon (<code>**:**</code>) </li>
<li>In <strong>JavaScript</strong>, we surround the content of the class with curly braces (<code>**{}**</code>)</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-172.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class definition in Python (left) and JavaScript (right)</em></p>
<p><strong>💡 Tip:</strong> In Python and JavaScript, class names should start with an uppercase letter and each word should start with an uppercase letter as well.</p>
<h3 id="heading-constructor-and-attributes">Constructor and Attributes</h3>
<p>The constructor is a special method that is called when a new instance of the class (a new object) is created. Its main purpose is to initialize the attributes of the instance.</p>
<ul>
<li>In <strong>Python</strong>, the constructor that initializes the new instance is called <code>**init**</code> (with two leading and trailing underscores). This method is called automatically when an instance of the class is created to initialize its attributes. Its parameters list defines the values that we have to pass to create the instance. This list starts with <code>**self**</code> as the first parameter.</li>
<li>In <strong>JavaScript</strong>, the constructor method is called <code>**constructor**</code> and it has a parameters list as well. </li>
</ul>
<p><strong>💡 Tip:</strong> In Python, we use <code>**self**</code> to refer to the instance while in JavaScript we use <code>**this**</code>.</p>
<p>To assign values to the attributes in <strong>Python</strong>, we use this syntax:</p>
<pre><code>self.attribute = value
</code></pre><p>In contrast, we use this syntax in <strong>JavaScript</strong>:</p>
<pre><code><span class="hljs-built_in">this</span>.attribute = value;
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2021/01/image-174.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class Example in Python (left) and JavaScript (right)</em></p>
<h2 id="heading-methods-in-python-and-javascript">Methods in Python and JavaScript</h2>
<ul>
<li>In <strong>Python</strong>, we define methods with the <code>**def**</code> keyword followed by their name and the parameters list within parentheses. This parameters list starts with the <code>**self**</code> parameter to refer to the instance that is calling the method. After this list, we write a colon (<code>**:**</code>) and the body of the method indented. </li>
</ul>
<p>This is an example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, radius, color</span>):</span>
        self.radius = radius
        self.color = color

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calc_diameter</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.radius * <span class="hljs-number">2</span>
</code></pre>
<ul>
<li>In <strong>JavaScript</strong>, methods are defined by writing their name followed by the parameters list and curly braces. Within the curly braces, we write the body of the method. </li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> </span>{

    <span class="hljs-keyword">constructor</span>(radius, color) {
        <span class="hljs-built_in">this</span>.radius = radius;
        <span class="hljs-built_in">this</span>.color = color;
    }

    calcDiameter() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.radius * <span class="hljs-number">2</span>;
    }
}
</code></pre>
<h3 id="heading-instances">Instances</h3>
<p>To create instances of a class:</p>
<ul>
<li>In <strong>Python</strong>, we write the name of the class and pass the arguments within parentheses.</li>
</ul>
<pre><code class="lang-python">my_circle = Circle(<span class="hljs-number">5</span>, <span class="hljs-string">"Red"</span>)
</code></pre>
<ul>
<li>In <strong>JavaScript</strong>, we need to add the <code>**new**</code> keyword before the name of the class. </li>
</ul>
<pre><code class="lang-javascript">my_circle = <span class="hljs-keyword">new</span> Circle(<span class="hljs-number">5</span>, <span class="hljs-string">"Red"</span>);
</code></pre>
<h2 id="heading-to-summarize">🔹 To Summarize</h2>
<p>Python and JavaScript are very powerful languages with different real-world applications. </p>
<p>Python can be used for web development and for a wide range of applications, including scientific purposes. JavaScript is mainly used for web development (front-end and back-end) and for mobile app development. </p>
<p>They have important differences, but they both have the same basic elements that we need to write powerful programs. </p>
<p><strong>I hope you liked this article and found it helpful.</strong> Now you know the key differences between Python and JavaScript. </p>
<p>⭐ <a target="_blank" href="https://www.youtube.com/channel/UCng0h8WiHLmT57JJ8At4LfQ"><strong>Subscribe to my YouTube channel</strong></a> and follow me on <a target="_blank" href="https://twitter.com/EstefaniaCassN"><strong>Twitter</strong></a> to find more coding tutorials and tips.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Rust for Beginners – Get Started with the Most Loved Programming Language ]]>
                </title>
                <description>
                    <![CDATA[ Rust has been voted Stack Overflow’s most loved programming language for five years in a row. This article will tell you why Rust is awesome. Rust is a systems programming language that you can use to write applications with high performance. Rust is... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rust-getting-started-with-the-most-loved-programming-language/</link>
                <guid isPermaLink="false">66d0361c871ae63f179f6b96</guid>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Tue, 18 Aug 2020 22:09:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/08/rust-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Rust has been voted Stack Overflow’s most loved programming language for five years in a row. This article will tell you why Rust is awesome.</p>
<p>Rust is a <a target="_blank" href="https://www.techopedia.com/definition/9616/system-programming">systems programming language</a> that you can use to write applications with high performance. Rust is used by some of the top tech companies like Dropbox and Cloudflare to deliver speed and concurrency to their customers.</p>
<p>For the last five years in a row, Rust has been voted as the most loved programming language. </p>
<p>But chances are, you might not have worked with Rust. Or worse, you might not have heard of it before. So let's learn more about it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/1-5.png" alt="Image" width="600" height="400" loading="lazy">
<em>StackOverflow 2020 Survey</em></p>
<h2 id="heading-why-rust">Why Rust?</h2>
<p>Let’s look at why a developer would choose Rust.</p>
<p>Typical programming languages like Python and C++ abstract a lot of details away from developers. </p>
<p>If you are a junior developer working on a simple web application, this might not an issue. You just want to find a solution to a problem.</p>
<p>For large scale applications that millions of users will use on a daily basis, the ‘problem-solving’ approach will not work. More users consume more system resources. And more resources mean bigger bills for your company.</p>
<p>This is where Rust shines. Rust combines ease of programming with access to core system configurations. Rust is built with memory-safety, concurrency, and security from the ground up.</p>
<blockquote>
<p>Rust is a “systems programming language that focuses on speed, memory safety, and parallelism”.</p>
</blockquote>
<p>Rust is also considered to be a great alternative for C++. Rust offers high performance in addition to helping you <a target="_blank" href="https://polyfloyd.net/post/how-rust-helps-you-prevent-bugs/">eliminate common bugs caused by languages like C++.</a></p>
<p>Now that you know what Rust can do for you, let's look at Rust in detail.</p>
<h2 id="heading-origins"> Origins</h2>
<p>Rust is an open-source programming language. It was first introduced to the world in 2010 by Graydon Hoare, while he was working at Mozilla. Shortly after, Mozilla began sponsoring this project and is still a core contributor to Rust.</p>
<p>Rust started gaining popularity over the years. Even Microsoft uses Rust to build secure and safety-critical software components.</p>
<h2 id="heading-core-features"> Core Features</h2>
<p>Let's look at some core features that make Rust stand out from other programming languages.</p>
<h3 id="heading-performance">Performance</h3>
<p>Rust was built to be high performance form the ground up. Rust offers fine-grained control of memory management and has a minimal standard library.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/performance.png" alt="Image" width="600" height="400" loading="lazy">
<em>Source: Figma</em></p>
<p>If you look at some of the <a target="_blank" href="https://www.figma.com/blog/rust-in-production-at-figma/">metrics shared by Figma</a>, they had incredible improvements in performance once they switched to Rust.</p>
<p>Rust’s low memory footprint also makes it an ideal choice for embedded systems programming. You can use Rust to write software for IoT devices like home automation hubs, smart security systems, and so on.</p>
<h3 id="heading-security">Security</h3>
<p>One of the major reasons Microsoft decided to root for Rust is its security. </p>
<p>The majority of vulnerabilities in Microsoft software were due to poor memory management in C &amp; C++. This lead to simple yet powerful exploits like the <a target="_blank" href="https://www.imperva.com/learn/application-security/buffer-overflow">Buffer Overflow exploit</a> that had crippled Windows for years.</p>
<p>So Microsoft decided to look for the best alternative to C++. And they found Rust.</p>
<p>Using Rust eliminates an entire class of security vulnerabilities from software applications. This helps companies build applications with better performance and higher security.</p>
<h3 id="heading-concurrency">Concurrency</h3>
<p>Concurrency is when two or more tasks start, run, and complete in overlapping time. Database operations are a great example to explain concurrency.</p>
<p>When thousands of users are using your application at the same time to perform different actions, your database handles them concurrently. Concurrency is a key concept when it comes to scaling applications.</p>
<p>Concurrency and parallelism are also built into Rust. Rust solves most of the concurrency problems during compile time by using the concept of Ownerships. <a target="_blank" href="https://doc.rust-lang.org/book/ch16-00-concurrency.html">Learn how Rust handles concurrency here</a>.</p>
<h2 id="heading-working-with-rust">Working With Rust</h2>
<p>Now that you understand the core features of Rust, let's write a few lines of code. You can <a target="_blank" href="https://www.rust-lang.org/tools/install">find installation instructions here</a> if you want to try out Rust on your computer.</p>
<p>Let's start with a simple “Hello World!” function.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Main function</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello World!"</span>);
}
</code></pre>
<p>Yep. That's pretty much it. Let's try to add two numbers.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Main function</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">100</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">200</span>;
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result is {}"</span>,a+b);
}
</code></pre>
<p>Again, pretty standard. Now let's look at an array operation.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Main function</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>(){
    <span class="hljs-keyword">let</span> arr:[<span class="hljs-built_in">i32</span>;<span class="hljs-number">4</span>] = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>];
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"array size is {}"</span>,arr.len());
}
</code></pre>
<p>If you look at line 3, we use “:[i32;4]”. Here we tell Rust that we are declaring an array of length 4 with 32-bit integers.</p>
<p>Declaring data types in detail is a key factor in improving the performance of a program. You are helping the compiler save time by explicitly declaring what type of data you are about to assign to a variable.</p>
<p>Letting the compiler figure out the data type is one of the main reasons you run into performance issues while scaling your application. </p>
<p>Also, <a target="_blank" href="https://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages">Rust is a statically typed language</a>, which means it must know the types of all variables at compile time.</p>
<p>Though Rust is syntactically similar to C and C++, don't let its simplicity fool you. Rust does come with a steep learning curve. But it is totally worth it once you get a good grasp of the basics.</p>
<h2 id="heading-who-uses-rust">Who Uses Rust?</h2>
<p>Now that you have a good grasp of what Rust is, let's look at who uses Rust.</p>
<h3 id="heading-microsoft">Microsoft</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/1-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once a fierce adversary of open source, Microsoft is now an avid contributor to a number of open-source projects. Their .net core project is one of the most popular open-source frameworks used by developers today.</p>
<p>Microsoft has chosen Rust for security and performance-critical applications. Rust is also used extensively in Azure, especially in its <a target="_blank" href="https://azure.microsoft.com/en-in/services/iot-edge/">IoT Edge platform</a> to run AI applications on IoT devices.</p>
<h3 id="heading-dropbox">Dropbox</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/1-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Dropbox uses Rust to improve its data center efficiency. Rust is now powering core services of Dropbox serving more than 500 million users. </p>
<p>Dropbox <a target="_blank" href="https://dropbox.tech/infrastructure/rewriting-the-heart-of-our-sync-engine">recently wrote a detailed article</a> on how they re-wrote their core engine.</p>
<p>In Dropbox’s own words,</p>
<blockquote>
<p>Rust has been a force multiplier for our team, and betting on Rust was one of the best decisions we made.</p>
</blockquote>
<p>Rust was also a contributing factor that helped Dropbox move its infrastructure from AWS to its own data centers.</p>
<h3 id="heading-figma">Figma</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/figma.png" alt="Image" width="600" height="400" loading="lazy"></p>
<hr>
<p>Figma is a cloud-based designing and prototyping tool that you can use in your browser. It is an excellent tool for designing, prototyping, and exporting your designs into code. <a target="_blank" href="https://www.figma.com/">Learn more about Figma here</a>.</p>
<p>Concurrency is crucial for a collaborative tool where many users will be working on a single design at a time. Figma used Rust to write a high-performance server that helped them scale their product and achieve the performance they were looking for.</p>
<p><a target="_blank" href="https://www.figma.com/blog/rust-in-production-at-figma/">Here is the article Figma wrote</a> about their experience with Rust.</p>
<h2 id="heading-tldr">TL;DR</h2>
<p>Rust is a systems programming language that has been voted as <a target="_blank" href="https://stackoverflow.blog/2020/01/20/what-is-rust-and-why-is-it-so-popular/">StackOverflow’s most loved programming languages</a>, four years in a row. </p>
<p>Rust gives you control over low-level details and provides remarkable improvements in speed and stability. </p>
<p>It has helped companies like Dropbox, Figma, and Microsoft build better applications for their customers.</p>
<p>The language is being increasingly adopted by companies looking to scale their applications with higher performance and concurrency. Sounds interesting? <a target="_blank" href="https://doc.rust-lang.org/stable/rust-by-example/">Start learning Rust here</a>.</p>
<hr>
<p><em>I regularly write about Machine Learning, Cyber Security, and DevOps. You can signup for my</em> <a target="_blank" href="https://www.manishmshiva.com/"><em>weekly newsletter</em></a> <em>here.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Kotlin VS Java – Which Programming Language Should You Learn? ]]>
                </title>
                <description>
                    <![CDATA[ By Pramono Winata It has been several years since Kotlin came out, and it has been doing well. Since it was created specifically to replace Java, Kotlin has naturally been compared with Java in many respects. To help you decide which of the two langu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kotlin-vs-java-which-language-to-learn-in-2020/</link>
                <guid isPermaLink="false">66d460957df3a1f32ee7f885</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kotlin ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 27 Jul 2020 19:10:12 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9987740569d1a4ca2041.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Pramono Winata</p>
<p>It has been several years since Kotlin came out, and it has been doing well. Since it was created specifically to replace Java, Kotlin has naturally been compared with Java in many respects.</p>
<p>To help you decide which of the two languages you should pick up, I will compare some of the main features of each language so you can choose the one you want to learn.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/asa-1-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>These are the 8 points I'll discuss in this article:</p>
<ul>
<li><p>Syntax</p>
</li>
<li><p>Lambda Expressions</p>
</li>
<li><p>Null Handling</p>
</li>
<li><p>Model Classes</p>
</li>
<li><p>Global Variables</p>
</li>
<li><p>Concurrency</p>
</li>
<li><p>Extension Functions</p>
</li>
<li><p>Community</p>
</li>
</ul>
<h2 id="heading-syntax-comparison">Syntax comparison</h2>
<p>To start it all let's do some basic syntax comparison. Many of you who are reading this might already have some knowledge about Java and/or Kotlin, but I will give out a basic example below so we can compare them directly:</p>
<h3 id="heading-java">Java</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloClass</span> </span>{ 

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">FullName</span><span class="hljs-params">(String firstName, String lastName)</span> </span>{
        String fullName = firstName + <span class="hljs-string">" "</span> + lastName;
        System.out.println(<span class="hljs-string">"My name is : "</span> + fullName); 
    } 

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Age</span><span class="hljs-params">()</span> </span>{ 
        <span class="hljs-keyword">int</span> age = <span class="hljs-number">21</span>;
        System.out.println(<span class="hljs-string">"My age is : "</span> + age); 
    } 

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{ 
        HelloClass hello = <span class="hljs-keyword">new</span> HelloClass(); 
        hello.FullName(<span class="hljs-string">"John"</span>,<span class="hljs-string">"Doe"</span>);
        hello.Age();
    } 
}
</code></pre>
<h3 id="heading-kotlin">Kotlin</h3>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NameClass</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">FullName</span><span class="hljs-params">(firstName: <span class="hljs-type">String</span>, lastName:<span class="hljs-type">String</span>)</span></span> {
        <span class="hljs-keyword">var</span> fullName = <span class="hljs-string">"<span class="hljs-variable">$firstName</span> <span class="hljs-variable">$lastName</span>"</span>
        println(<span class="hljs-string">"My Name is : <span class="hljs-variable">$fullName</span>"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">Age</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> age : <span class="hljs-built_in">Int</span>
    age = <span class="hljs-number">21</span>
    println(<span class="hljs-string">"My age is: <span class="hljs-variable">$age</span>"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">(args: <span class="hljs-type">Array</span>&lt;<span class="hljs-type">String</span>&gt;)</span></span> {
    NameClass().FullName(<span class="hljs-string">"John"</span>,<span class="hljs-string">"Doe"</span>)
    Age()
}
</code></pre>
<p>The feel of the code isn't that different aside from some small syntax changes in the methods and classes.</p>
<p>But the real difference here is that Kotlin supports type inference where the variable type does not need to be declared. Also we don't need semicolons ( <code>;</code> ) anymore.</p>
<p>We can also note that Kotlin does not strictly enforce OOP like Java where everything must be contained inside a class. Take a look at <code>fun Age</code> and <code>fun main</code> in the example where it is not contained inside any class.</p>
<p>Kotlin also typically has fewer lines of codes, whereas Java adheres more to a traditional approach of making everything verbose.</p>
<p>One advantage of Kotlin over Java is Kotlin's flexibility – it can choose to do everything in the traditional OOP approach or it can go a different way.</p>
<h2 id="heading-lambda-expressions">Lambda Expressions</h2>
<p>If we are talking about Java and Kotlin, of course we have to talk about the famous lambda expression. Kotlin has native Lambda support (and always has), while lambda was first introduced in Java 8.</p>
<p>Let's see how they both look.</p>
<h3 id="heading-java-1">Java</h3>
<pre><code class="lang-java"><span class="hljs-comment">//syntaxes</span>
parameter -&gt; expression
(parameter1, parameter2) -&gt; { code }

<span class="hljs-comment">//sample usage</span>
ArrayList&lt;Integer&gt; numbers = <span class="hljs-keyword">new</span> ArrayList&lt;Integer&gt;();
numbers.add(<span class="hljs-number">5</span>);
numbers.add(<span class="hljs-number">9</span>);
numbers.forEach( (n) -&gt; { System.out.println(n); } );
</code></pre>
<h3 id="heading-kotlin-1">Kotlin</h3>
<pre><code class="lang-kotlin"><span class="hljs-comment">//syntax</span>
{ parameter1, parameter2 -&gt; code }

<span class="hljs-comment">//sample usage</span>
max(strings, { a, b -&gt; a.length &lt; b.length })
</code></pre>
<p>In Java, the parentheses are more lenient: if only one parameter exists, there is no need for parenthesis. But in Kotlin brackets are always required. Overall, however, there are not many differences aside from syntax.</p>
<p>In my opinion, lambda functions won't be used much aside from using them as callback methods. Even though lambda functions have so many more uses, <strong>readability</strong> issues make it less desirable. They'll make your code shorter, but figuring out the code later will be much more difficult.</p>
<p>It's just a matter of preference, but I think it's helpful that Kotlin enforces the mandatory brackets to help with readability.</p>
<h2 id="heading-null-handling">Null Handling</h2>
<p>In an object oriented language, null type values have always been an issue. This issue comes in the form of a Null Pointer Exception (NPE) when you're trying to use the contents of a null value.</p>
<p>As NPEs have always been an issue, both Java and Kotlin have their own way of handling null objects, as I will show below.</p>
<h3 id="heading-java-2">Java</h3>
<pre><code class="lang-java">Object object = objServ.getObject();

<span class="hljs-comment">//traditional approach of null checking</span>
<span class="hljs-keyword">if</span>(object!=<span class="hljs-keyword">null</span>){
    System.out.println(object.getValue());
}

<span class="hljs-comment">//Optional was introduced in Java 8 to further help with null values</span>

<span class="hljs-comment">//Optional nullable will allow null object</span>
Optional&lt;Object&gt; objectOptional = Optional.ofNullable(objServ.getObject());

<span class="hljs-comment">//Optional.of - throws NullPointerException if passed parameter is null</span>
Optional&lt;Object&gt; objectNotNull = Optional.of(anotherObj);

<span class="hljs-keyword">if</span>(objectOptional.isPresent()){
    Object object = objectOptional.get();
    System.out.println(object.getValue());
}

System.out.println(objectNotNull.getValue());
</code></pre>
<h3 id="heading-kotlin-2">Kotlin</h3>
<pre><code class="lang-kotlin"><span class="hljs-comment">//Kotlin uses null safety mechanism</span>
<span class="hljs-keyword">var</span> a: String = <span class="hljs-string">"abc"</span> <span class="hljs-comment">// Regular initialization means non-null by default</span>
a = <span class="hljs-literal">null</span> <span class="hljs-comment">// compilation error</span>

<span class="hljs-comment">//allowing null only if it is set Nullable</span>
<span class="hljs-keyword">var</span> b: String? = <span class="hljs-string">"abc"</span> <span class="hljs-comment">// can be set null</span>
b = <span class="hljs-literal">null</span> <span class="hljs-comment">// ok</span>
print(b)
</code></pre>
<p>For as long as I can remember, Java has been using traditional null checking which is prone to human error. Then Java 8 came out with optional classes which allow for more robust null checking, especially from the API/Server side.</p>
<p>Kotlin, on the other hand, provides null safety variables where the variable must be nullable if the value can be null.</p>
<p>I haven't really used optional class yet, but the mechanism and purpose seems pretty similar to Kotlin's null safety. Both help you identify which variable can be null and help you make sure the correct check is implemented.</p>
<p>Sometimes in code there might be just too many variables lying around and too many to check. But adding checking everywhere makes our code base ugly, and nobody likes that, right?</p>
<p>In my opinion, though, using Java's optional feels a bit messy because of the amount of code that needs to be added for the checks. Meanwhile in Kotlin, you can just add a small amount of code to do null checking for you.</p>
<h2 id="heading-model-class">Model Class</h2>
<p>Some people might also refer to this as the Entity class. Below you can see how both classes are used as model classes in each language.</p>
<h3 id="heading-java-3">Java</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{

     <span class="hljs-keyword">private</span> String name;
     <span class="hljs-keyword">private</span> Integer age;

     <span class="hljs-comment">// Default constructor</span>
       <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Student</span><span class="hljs-params">()</span> </span>{ }

     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
         <span class="hljs-keyword">this</span>.name = name;
     }

     <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
         <span class="hljs-keyword">return</span> name;
     }

     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(Integer age)</span> </span>{
         <span class="hljs-keyword">this</span>.age = age;
     }

     <span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{
         <span class="hljs-keyword">return</span> age;
     }
}
</code></pre>
<h3 id="heading-kotlin-3">Kotlin</h3>
<pre><code class="lang-kotlin"><span class="hljs-comment">//Kotlin data class</span>
<span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span></span>(<span class="hljs-keyword">var</span> name: String = <span class="hljs-string">""</span>, <span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span> = <span class="hljs-number">0</span>)

<span class="hljs-comment">//Usage</span>
<span class="hljs-keyword">var</span> student: Student = Student(<span class="hljs-string">"John Doe"</span>, <span class="hljs-number">21</span>)
</code></pre>
<p>In Java, properties are declared as private, following the practice of encapsulation. When accessing these properties, Java uses Getters and Setters, along with the isEqual or toString methods when needed.</p>
<p>On the Kotlin side, <a target="_blank" href="https://kotlinlang.org/docs/reference/data-classes.html">data classes</a> are introduced for the special purpose of model classes. Data classes allow properties to be directly accessed. They also provide several in-built utility methods such as equals(), toString() and copy().</p>
<p>For me, data classes are one of the best things Kotlin offers. They aim to reduce the amount of the boilerplate code you need for regular model classes, and they do a really good job of that.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-164.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Random Pic because you are halfway there! Photo by [Unsplash](https://unsplash.com/@dinoreichmuth?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Dino Reichmuth / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit)</em></p>
<h2 id="heading-global-variables">Global Variables</h2>
<p>Sometimes your code might need a variable needs to be accessed everywhere in your code base. This is what global variables are used for. Kotlin and Java each have their own ways of handling this.</p>
<h3 id="heading-java-4">Java</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeClass</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> globalNumber = <span class="hljs-number">10</span>;
}

<span class="hljs-comment">//can be called without initializing the class</span>
SomeClass.globalNumber;
</code></pre>
<h3 id="heading-kotlin-4">Kotlin</h3>
<pre><code class="lang-kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeClass</span> </span>{
    <span class="hljs-keyword">companion</span> <span class="hljs-keyword">object</span> {
        <span class="hljs-keyword">val</span> globalNumber = <span class="hljs-number">10</span>
    }
}

<span class="hljs-comment">//called exactly the same like usual</span>
SomeClass.globalNumber
</code></pre>
<p>Some of you might already be familiar with the <a target="_blank" href="https://www.javatpoint.com/static-keyword-in-java">static</a> keyword here since it's also used in some other language like C++. It's initialized at the start of a program's execution, and is used by Java to provide global variables since it is not contained as an Object. This means it can be accessed anywhere without initializing the class as an object.</p>
<p>Kotlin is using quite a different approach here: it removes the static keyword and replaces it with a <a target="_blank" href="https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html">companion object</a> which is pretty similar to a singleton. It let's you implement fancy features such as extensions and interfacing.</p>
<p>The lack of the static keyword in Kotlin was actually quite surprising for me. You could argue that using the static keyword might not be a good practice because of its nature and because it's difficult to test. And sure, the Kotlin companion object can easily replace it.</p>
<p>Even then, using static for global variable should be simple enough. If we are careful with it and don't make it a habit of making every single thing global, we should be good.</p>
<p>The companion object might also give us some flexibility with interfacing and such, but how often will we ever be interfacing singleton classes?</p>
<p>I think static keywords help us keep things short and clean for global variables.</p>
<h2 id="heading-concurrency">Concurrency</h2>
<p>Nowadays, concurrency is a hot topic. Sometimes the ability of a programming language to run several jobs concurrently might help you decide if that will be your language of choice.</p>
<p>Let's take a look at how both languages approach this.</p>
<h3 id="heading-java-5">Java</h3>
<pre><code class="lang-java">
<span class="hljs-comment">// Java code for thread creation by extending </span>
<span class="hljs-comment">// the Thread class </span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MultithreadingDemo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> 
</span>{ 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> 
    </span>{ 
        <span class="hljs-keyword">try</span>
        { 
            <span class="hljs-comment">// Displaying the thread that is running </span>
            System.out.println (<span class="hljs-string">"Thread "</span> + 
                  Thread.currentThread().getId() + 
                  <span class="hljs-string">" is running"</span>); 

        } 
        <span class="hljs-keyword">catch</span> (Exception e) 
        { 
            <span class="hljs-comment">// Throwing an exception </span>
            System.out.println (<span class="hljs-string">"Exception is caught"</span>); 
        } 
    } 
} 

<span class="hljs-comment">// Main Class </span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Multithread</span> 
</span>{ 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> 
    </span>{ 
        <span class="hljs-keyword">int</span> n = <span class="hljs-number">8</span>; <span class="hljs-comment">// Number of threads </span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>; i&lt;n; i++) 
        { 
            MultithreadingDemo object = <span class="hljs-keyword">new</span> MultithreadingDemo(); 
            object.start(); 
        } 
    } 
}
</code></pre>
<h3 id="heading-kotlin-5">Kotlin</h3>
<pre><code class="lang-kotlin"><span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>..<span class="hljs-number">1000</span>)
    GlobalScope.launch {
        println(i)
    }
</code></pre>
<p>Java mostly uses <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html">threads</a> to support concurrency. In Java, making a thread requires you to make a class that extends to the in-built Java thread class. The rest of its usage should be pretty straightforward.</p>
<p>While threads are also available in Kotlin, you should instead use its <a target="_blank" href="https://kotlinlang.org/docs/reference/coroutines-overview.html">coroutines</a>. Coroutines are basically light-weight threads that excel in short non-blocking tasks.</p>
<p>Concurrency has always been a hard concept to grasp (and also, to test). Threading has been used for a long time and some people might already been comfortable with that.</p>
<p>Coroutines have become more popular lately with languages like Kotlin and Go (Go similarly has goroutines). The concept differs slightly from traditional threads – <a target="_blank" href="https://stackoverflow.com/a/1934718/6065825">coroutines are sequential while threads can work in parallel</a>.</p>
<p>Trying out coroutines, though, should be pretty easy since Kotlin does a very good job explaining them in their <a target="_blank" href="https://kotlinlang.org/docs/reference/coroutines-overview.html">docs</a>. And one bonus for Kotlin over Java is the amount of boilerplate code that can be removed in Kotlin.</p>
<h2 id="heading-extension-functions">Extension Functions</h2>
<p>You might be wondering why I'm bringing these up since Java itself doesn't even have this feature.</p>
<p>But I can't help but mention it, because extension functions are a very useful feature that was introduced in Kotlin.</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-built_in">Int</span>.<span class="hljs-title">plusOne</span><span class="hljs-params">()</span></span>: <span class="hljs-built_in">Int</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span> + <span class="hljs-number">1</span>
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">(args: <span class="hljs-type">Array</span>&lt;<span class="hljs-type">String</span>&gt;)</span></span> {
    <span class="hljs-keyword">var</span> number = <span class="hljs-number">1</span>
    <span class="hljs-keyword">var</span> result = number.plusOne()
    println(<span class="hljs-string">"Result is: <span class="hljs-variable">$result</span>"</span>)
}
</code></pre>
<p>They allow a class to have new functionality without extending it into the class or using any of the fancy Design Patterns. It even lets you to add functionality to Kotlin variable classes.</p>
<p>You can practically say goodbye to those lib method that need you to pass everything inside your parameters.</p>
<h2 id="heading-community">Community</h2>
<p>Last but not least, let's talk about something non-technical. First, let's take a look at this survey showing top commonly used programming languages in 2020.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/Screenshot-from-2020-07-24-23-05-40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>taken from</em> <a target="_blank" href="https://insights.stackoverflow.com/survey/2020#development-environments-and-tools"><em>stack overflow survey</em></a></p>
<p>We can see that Java is one of the most commonly used languages. And while Kotlin is still rising a lot in popularity, the Java community still remains several times larger than Kotlin and it will probably not change anytime soon.</p>
<p>So what does that matter then? Actually it does matter, a lot. With the amount of people in the Java community, it's much easier to find references and get help when you need it, both on the Internet and in the real world.</p>
<p>Many companies are also still using Java as their base and it might not change anytime soon even with Kotlin's interoperability with Java. And usually, doing a migration just doesn't serve any business purpose unless the company has really really important reasons for it.</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>For those just scrolling for the summary, here's what we discussed:</p>
<ul>
<li><p>Syntax: the patterns don't differ that much aside from slight syntax differences, but Kotlin is more flexible in several aspects.</p>
</li>
<li><p>Lambda Expressions: the syntax is almost the same, but Kotlin uses curly brackets to help readability.</p>
</li>
<li><p>Null Handling: Java uses a class to help with null handling while Kotlin uses in-built null safety variables.</p>
</li>
<li><p>Model Classes: Java uses classes with private variables and setter / getter while Kotlin supports it with data classes.</p>
</li>
<li><p>Global Variables: Java uses the static keyword while Kotlin uses something akin to sub-classes.</p>
</li>
<li><p>Concurrency: Java uses multi-threading whereas Kotlin uses coroutines (which are generally lighter).</p>
</li>
<li><p>Extension Functions: a new feature introduced by Kotlin to easily give functionality into classes without extending it.</p>
</li>
<li><p>Community: Java still reigns supreme in the community aspect which makes it easier to learn and get help.</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-165.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Photo by [Unsplash](https://unsplash.com/@glenncarstenspeters?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Glenn Carstens-Peters / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit)</em></p>
<p>There are many more features we could compare between Java and Kotlin. But what I've discussed here are, in my opinion, some of the most important.</p>
<p>I think Kotlin is well worth picking up at the moment. From the development side it helps you remove long boilerplate code and keep everything clean and short. If you are already a Java programmer, learning Kotlin shouldn't be too hard and it's okay to take your time at it.</p>
<p>Thanks for reading! I hope that this article will help you decide which programming language you should pick, Java or Kotlin. And for anything that I'm missing, feel free to leave feedback for me as it will be very much appreciated.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ TypeScript Types Explained – A Mental Model to Help You Think in Types ]]>
                </title>
                <description>
                    <![CDATA[ By TK One day I came across this tweet from Lari Mazza: As a software engineer who learned Python, Ruby, JavaScript, and Clojure first, when I tried C++ it was a horror movie. I couldn't do much, and it was so counterproductive and frustrating. Mayb... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-mental-model-to-think-in-typescript-2/</link>
                <guid isPermaLink="false">66d852a75732345ee5fa9335</guid>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 21 Jul 2020 11:05:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By TK</p>
<p>One day I came across this <a target="_blank" href="https://twitter.com/larimaza/status/1275747670989176833">tweet</a> from Lari Mazza:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/typescript.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As a software engineer who learned Python, Ruby, JavaScript, and Clojure first, when I tried C++ it was a horror movie. I couldn't do much, and it was so counterproductive and frustrating. Maybe because I was doing everything wrong and I didn't understand types the right way.</p>
<p>But even though I had so many problems, I could implement a bunch of <a target="_blank" href="https://github.com/leandrotk/algorithms">algorithms and data structures</a>.</p>
<p>Now that I'm using more and more TypeScript in my day-to-day job and <a target="_blank" href="https://github.com/leandrotk/laziness">my side projects</a>, I feel I'm more prepared to confront types. Actually, not confront, but use them in my favor.</p>
<p>This post is my attempt to help developers think more in types and understand this mental model.</p>
<h2 id="heading-thinking-in-javascript-types">Thinking in JavaScript types</h2>
<p>If you're here, you've probably heard that TypeScript is a superset of JavaScript. If not, great, you just learned something new today. YAY!</p>
<p>TypeScript is a superset because any JavaScript code is valid in TypeScript, syntactically speaking. It may or may not compile depending on the TypeScript compiler configuration. But in terms of syntax, it works just fine. </p>
<p>This is why you can migrate JavaScript to TypeScript progressively by just replacing the <code>.js</code> extension with the <code>.ts</code>. Everything will be without type declarations (the <code>any</code> type), but that's another story.</p>
<p>Also, if you code in JavaScript - or any other programming language - you probably think in types:</p>
<ul>
<li>"Hm, it is a list of integers, so I'll need to filter only the even numbers and return a new list"</li>
<li>"This is an object, but I just need to get this string value from the property X"</li>
<li>"This function receives two parameters. Both A and B are integers and I want to sum them"</li>
</ul>
<p>Yeah, you get the idea. We think in types. But they are just in our heads. We constantly think about them because we need to know how to handle, parse, or modify data. We need to know which methods we are allowed to use in this object type.</p>
<p>To give a more concrete example, imagine you want to sum the price of all products. A product object looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>But now with a list of products:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> products = [
  {
    title: <span class="hljs-string">'Product 1'</span>,
    price: <span class="hljs-number">100.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 2'</span>,
    price: <span class="hljs-number">25.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 3'</span>,
    price: <span class="hljs-number">300.00</span>,
  }
];
</code></pre>
<p>Ok! Now we want a function to sum all the products prices.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAllPrices</span>(<span class="hljs-params">products</span>) </span>{
  <span class="hljs-keyword">return</span> products.reduce(<span class="hljs-function">(<span class="hljs-params">sum, product</span>) =&gt;</span> sum + product.price, <span class="hljs-number">0</span>);
};

sumAllPrices(products); <span class="hljs-comment">// 425</span>
</code></pre>
<p>Just receive the products as the argument and reduce all product prices. JavaScript works just fine. But while building this function you start to think about the data and how to handle it properly.</p>
<p>The first part: products as an argument. Here you just think: "well, we're receiving a list of some objects". Yeah, in our heads the products are a list. This is why we can think of using the <code>reduce</code> method. It is a method from the <code>Array</code> prototype.</p>
<p>Then we can think about the object in detail. We know that the product object has a <code>price</code> property. And this property is a number. This is why we can do <code>product.price</code> and sum with the accumulator.</p>
<p>Recapping:</p>
<ul>
<li><code>products</code> is a list of objects.</li>
<li>As a list, we can use the <code>reduce</code> method, as this method is a member of the <code>Array</code> prototype.</li>
<li>The <code>produce</code> object has some properties. One of them is the <code>price</code>, which is a number.</li>
<li>As a number property, we can use it to sum with the reduce accumulator.</li>
<li>We wanted to return a number, the sum of all products prices.</li>
</ul>
<p>We are always thinking of data types, we just need to add the type annotations to make it more explicit and ask the compiler for help. Our memory is limited and the compilers are here to help us, humans.</p>
<p>The type system will not only make our data more consistent, but it can also provide autocompletion for data types. It knows the types, so it can show the members for the data. We will take a look at this idea later. Here I just wanted to show that we think in types in our heads.</p>
<h2 id="heading-simples-types-amp-simple-uses">Simples Types &amp; Simple Uses</h2>
<p>So we are ready to use some strongly typed programming languages like TypeScript. We simply need to explicitly add type annotations to our data structures. It's simple, right? </p>
<p>But sometimes it's not that easy (usually it's not easy when you come from dynamically typed languages. You feel unproductive. It feels like a battle against types). The idea here is to make this learning curve smoother and more fun.</p>
<p>Here we will see many examples of how to use types in TypeScript. We'll start with easy and silly examples and progressively make it more complex while designing the mental model to think in types.</p>
<p>As in JavaScript, TypeScript also has basic data types like <code>number</code>, <code>string</code>, <code>boolean</code>, <code>null</code>, etc. You can find all the basic data types in the <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/basic-types.html">TypeScript Docs</a>.</p>
<p>With these units of data, we can make our programs more useful. To be more practical, let's get a simple example. A <code>sum</code> function.</p>
<p>How does it work in JavaScript?</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>Everything ok? Good.</p>
<p>Now let's use it:</p>
<pre><code class="lang-typescript">sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
sum(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 4</span>
sum(<span class="hljs-number">0</span>, <span class="hljs-string">'string'</span>); <span class="hljs-comment">// '0string'   WTF!</span>
</code></pre>
<p>The first two calls are what we expect to happen in our system. But JavaScript is very flexible, it lets us provide any value to this function. </p>
<p>The last call is bizarre. We can call with a string, but it will return an unexpected result. It doesn't break in development, but it will result in strange behavior in runtime.</p>
<p>What do we want? We want to add some constraints to the function. It will only be able to receive numbers. That way, we narrow the possibility of having unexpected behaviors. And the function return type is also a number.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>Great! It was very simple. Let's call again.</p>
<pre><code class="lang-typescript">sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
sum(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 4</span>
sum(<span class="hljs-number">0</span>, <span class="hljs-string">'string'</span>); <span class="hljs-comment">// Argument of type '"string"' is not assignable to parameter of type 'number'.</span>
</code></pre>
<p>As we type annotate our function, we provide information to the compiler to see if everything is correct. It will follow the constraints we added to the function.</p>
<p>So the first two calls are the same as in JavaScript. It will return the correct calculation. But in the last one we have an error in compile time. This is important. The error now happens in compile time and prevents us from shipping incorrect code to production. It says that the <code>string</code> type is not part of the set of values in the <code>number</code> type universe.</p>
<p>For basic types, we just need to add a colon followed by the type definition.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> isTypescript: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> age: <span class="hljs-built_in">number</span> = <span class="hljs-number">24</span>;
<span class="hljs-keyword">const</span> username: <span class="hljs-built_in">string</span> = <span class="hljs-string">'tk'</span>;
</code></pre>
<p>Now let's increase the challenge. Remember the product object code we wrote in JavaScript? Let's implement it again, but now with the TypeScript mindset.</p>
<p>Just to remember what we are talking about:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>This is the product value. It has a <code>title</code> as <code>string</code> and the <code>price</code> as <code>number</code>. For now, this is what we need to know.</p>
<p>The object type would be something like this:</p>
<pre><code class="lang-typescript">{ title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> }
</code></pre>
<p>And we use this type to annotate our function:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> product: { title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> } = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>With this type, the compiler will know how to handle inconsistent data:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> wrongProduct: { title: <span class="hljs-built_in">string</span>, price: <span class="hljs-built_in">number</span> } = {
  title: <span class="hljs-number">100.00</span>, <span class="hljs-comment">// Type 'number' is not assignable to type 'string'.</span>
  price: <span class="hljs-string">'Some product'</span>, <span class="hljs-comment">// Type 'string' is not assignable to type 'number'.</span>
};
</code></pre>
<p>Here it breaks down into two different properties:</p>
<ul>
<li>The <code>title</code> is a <code>string</code> and should not receive a <code>number</code>.</li>
<li>The <code>price</code> is a <code>number</code> and should not receive a <code>string</code>.</li>
</ul>
<p>The compiler helps us to catch type errors like that.</p>
<p>We could improve this type annotation by using a concept called <code>Type Aliases</code>. It's a way to create a new name for a specific type.</p>
<p>In our case, the product type could be:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Product = {
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">const</span> product: Product = {
  title: <span class="hljs-string">'Some product'</span>,
  price: <span class="hljs-number">100.00</span>,
};
</code></pre>
<p>It's better to visualize the type, add semantics, and maybe reuse in our system.</p>
<p>Now that we have this product type, we can use it to type the products list. The syntax looks like this: <code>MyType[]</code>. In our case, <code>Product[]</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> products: Product[] = [
  {
    title: <span class="hljs-string">'Product 1'</span>,
    price: <span class="hljs-number">100.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 2'</span>,
    price: <span class="hljs-number">25.00</span>,
  },
  {
    title: <span class="hljs-string">'Product 3'</span>,
    price: <span class="hljs-number">300.00</span>,
  }
];
</code></pre>
<p>Now the function <code>sumAllPrices</code>. It will receive the product and return a number, the sum of all product prices.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAllPrices</span>(<span class="hljs-params">products: Product[]</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> products.reduce(<span class="hljs-function">(<span class="hljs-params">sum, product</span>) =&gt;</span> sum + product.price, <span class="hljs-number">0</span>);
};
</code></pre>
<p>This is very interesting. As we typed the product, when we write <code>product.</code>, it will show the possible properties we can use. In the product type case, it will show the properties <code>price</code> and <code>title</code>.</p>
<pre><code class="lang-typescript">sumAllPrices(products); <span class="hljs-comment">// 425</span>
sumAllPrices([]); <span class="hljs-comment">// 0</span>
sumAllPrices([{ title: <span class="hljs-string">'Test'</span>, willFail: <span class="hljs-literal">true</span> }]); <span class="hljs-comment">// Type '{ title: string; willFail: true; }' is not assignable to type 'Product'.</span>
</code></pre>
<p>Passing the <code>products</code> will result in the value <code>425</code>. An empty list will result in the value <code>0</code>. And if we pass an object with a different structure - TypeScript has a structural type system and we will dig deep into this topic later - the compiler will throw a type error telling that the structure is not part of the <code>Product</code> type.</p>
<h2 id="heading-structural-typing">Structural Typing</h2>
<p>Structural typing is a type of type compatibility. It's a way to understand the compatibility between types based on its structure: features, members, properties. Some languages have type compatibility based on the names of the types, and it's called nominal typing.</p>
<p>For example, in Java, even if different types have the same structure, it will throw a compile error because we are using a different type to instantiate and define a new instance.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Person {
  <span class="hljs-built_in">String</span> name;
}

<span class="hljs-keyword">class</span> Client {
  <span class="hljs-built_in">String</span> name;
}

Client c = <span class="hljs-keyword">new</span> Person();  <span class="hljs-comment">// compiler throws an error</span>
Client c = <span class="hljs-keyword">new</span> Client();  <span class="hljs-comment">// OK!</span>
</code></pre>
<p>In nominal type systems, the relevant part of a type is the name, not the structure.</p>
<p>TypeScript, on another hand, verifies the structural compatibility to allow or not specific data. Its type system is based on structural typing.</p>
<p>The same code implementation that crashes in Java, would work in TypeScript.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Person {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">class</span> Client {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> c1: Client = <span class="hljs-keyword">new</span> Person(); <span class="hljs-comment">// OK!</span>
<span class="hljs-keyword">const</span> c2: Client = <span class="hljs-keyword">new</span> Client(); <span class="hljs-comment">// OK!</span>
</code></pre>
<p>We want to use the <code>Client</code> type, and it has the property <code>name</code>, to point to the <code>Person</code> type. It also has the property type. So TypeScript will understand that both types have the same shape.</p>
<p>But it is not only about classes, but it works for any other "object".</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c3: Client = {
  name: <span class="hljs-string">'TK'</span>
};
</code></pre>
<p>This code compiles too because we have the same structure here. The TypeScript type system doesn't care about if it is a class, or an object literal if it has the same members, it will be flexible and compile.</p>
<p>But now we will add a third type: the <code>Customer</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">class</span> Customer {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
};
</code></pre>
<p>It not only has the <code>name</code> property, but also the <code>age</code>. What would happen if we instantiate a <code>Client</code> instance in a constant of type <code>Customer</code>?</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c4: Customer = <span class="hljs-keyword">new</span> Client();
</code></pre>
<p>The compiler will not accept that. We want to use the <code>Customer</code>, that has <code>name</code> and <code>age</code>. But we are instantiating the <code>Client</code> that has only the <code>name</code> property. So it doesn't have the same shape. It will cause an error:</p>
<pre><code class="lang-bash">Property <span class="hljs-string">'age'</span> is missing <span class="hljs-keyword">in</span> <span class="hljs-built_in">type</span> <span class="hljs-string">'Client'</span> but required <span class="hljs-keyword">in</span> <span class="hljs-built_in">type</span> <span class="hljs-string">'Customer'</span>.
</code></pre>
<p>The other way around would work because we want <code>Client</code>, and <code>Customer</code> has all the properties (<code>name</code>) from <code>Client</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> c5: Client = <span class="hljs-keyword">new</span> Customer();
</code></pre>
<p>It works fine!</p>
<p>We can go on for enums, object literals, and any other type, but the idea here is to understand that the structure of the type is the relevant part.</p>
<h2 id="heading-runtime-and-compile-time">Runtime and Compile time</h2>
<p>This is a much more complex topic in programming language theory, but I wanted to give some examples to distinguish runtime from compile time.</p>
<p>Basically, the runtime is the execution time of a program. Imagine your backend receiving data from a frontend form page, handling this data, and saving it. Or when your frontend is requesting data from a server to render a list of Pokemons products.</p>
<p>Compile time is basically when the compiler is executing operations in the source code to satisfy the programming language's requirements. It can include type checking as an operation, for example. </p>
<p>Compile time errors in TypeScript, for example, are very related to the code that we wrote before:</p>
<ul>
<li>When the type is missing property: <code>Property 'age' is missing in type 'Client' but required in type 'Customer'.</code></li>
<li>When the type doesn't match: <code>Type '{ title: string; willFail: true; }' is not assignable to type 'Product'.</code></li>
</ul>
<p>Let's see some examples to have a better understanding.</p>
<p>I want to write a function to get the index of a part of the passed programming language.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIndexOf</span>(<span class="hljs-params">language, part</span>) </span>{
  <span class="hljs-keyword">return</span> language.indexOf(part);
}
</code></pre>
<p>It receives the <code>language</code> and the <code>part</code> that we will look for to get the index.</p>
<pre><code class="lang-typescript">getIndexOf(<span class="hljs-string">'Typescript'</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// 4</span>
getIndexOf(<span class="hljs-number">42</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// Uncaught TypeError: language.indexOf is not a function at getIndexOf</span>
</code></pre>
<p>When passing a string, it works fine. But passing a number, we got a runtime error <code>Uncaught TypeError</code>. Because a number doesn't have an <code>indexOf</code> function, so we can't really use it.</p>
<p>But if we give type information to the compiler, in compile time, it will throw an error before running the code.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIndexOf</span>(<span class="hljs-params">language: <span class="hljs-built_in">string</span>, part: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> language.indexOf(part);
}
</code></pre>
<p>Now our program knows that it will need to receive two strings and return a number. The compiler can use this information to throw errors when we get a type error... before runtime.</p>
<pre><code class="lang-typescript">getIndexOf(<span class="hljs-string">'Typescript'</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// 4</span>
getIndexOf(<span class="hljs-number">42</span>, <span class="hljs-string">'script'</span>); <span class="hljs-comment">// Argument of type '42' is not assignable to parameter of type 'string'.</span>
</code></pre>
<p>Maybe, for small projects (or small functions like ours) we don't really see too much benefit. </p>
<p>In this case, we know that we need to pass a string, so we won't pass a number to the function. But when the codebase grows or you have many people adding code and more complexity, it's clear to me that a type system can help us a lot to get errors in compile time before shipping code to production.</p>
<p>At first, we need all the learning curve to understand types and all the mental models, but after a while, you'll be more used to type annotations and eventually become friends with the compiler. It would be a <em>helper</em>, not a <em>yeller</em>.</p>
<p>As we are learning about the basic difference between compile time and runtime, I think it's great to differentiate types from values.</p>
<p>All the examples I'll show here can be copied and run in the <a target="_blank" href="https://www.typescriptlang.org/play">TypeScript Playground</a> to understand the compiler and the result of the compilation process (aka the <em>"JavaScript"</em>).</p>
<p>In TypeScript, we have two different universes: the value and the type spaces. The type space is where types are defined and used to enable the compiler to do all the great magic. And the value space is the values in our programs like variables, constants, functions, value literals, and things that we have in runtime.</p>
<p>It's good to have an understanding of this concept because in TypeScript we can't use type checking in runtime. It has a very clear separation between type checking and the compilation process.</p>
<p>TypeScript has the process of type checking the source code types and sees if everything is correct and consistent. And then it can compile to JavaScript. </p>
<p>As these two parts are separate, we can't use type checking in runtime. Only in "compile time". If you try to use a type as a value, it will throw an error: <code>only refers to a type, but is being used as a value here</code>.</p>
<p>Let's see examples of this idea.</p>
<p>Imagine we want to write a function called <code>purchase</code> where we receive a payment method and based on this method, we want to do some action. We have a credit card and a debit card. Let's define them here:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> CreditCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-built_in">number</span>;
  cardholder: <span class="hljs-built_in">string</span>;
  expirationDate: <span class="hljs-built_in">Date</span>;
  secutiryCode: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> DebitCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-built_in">number</span>;
  cardholder: <span class="hljs-built_in">string</span>;
  expirationDate: <span class="hljs-built_in">Date</span>;
  secutiryCode: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> PaymentMethod = CreditCard | DebitCard;
</code></pre>
<p>These types are in the <em>Type space</em>, so it only works in compile time. After type checking this function, the compiler removes all the types.</p>
<p>If you add these types in the TypeScript Playground, the output will be only a strict definition <code>"use strict";</code>.</p>
<p>The idea here is to really understand that the types live in the <em>Type space</em> and will not be available in the runtime. So in our function, it won't be possible to do this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> purchase = <span class="hljs-function">(<span class="hljs-params">paymentMethod: PaymentMethod</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (paymentMethod <span class="hljs-keyword">instanceof</span> CreditCard) {
    <span class="hljs-comment">// purchase with credit card</span>
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// purchase with debit card</span>
  }
}
</code></pre>
<p>In the compiler it throws an error: <code>'CreditCard' only refers to a type, but is being used as a value here.</code>.</p>
<p>The compiler knows the difference between the two spaces and that the type <code>CreditCard</code> lives in the <em>Type space</em>.</p>
<p>The playground is a very cool tool to see the output of your TypeScript code. If you create a new credit card object like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> creditCard: CreditCard = {
  <span class="hljs-built_in">number</span>: <span class="hljs-number">2093</span>,
  cardholder: <span class="hljs-string">'TK'</span>,
  expirationDate: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(),
  secutiryCode: <span class="hljs-number">101</span>
};
</code></pre>
<p>The compiler will type check it and do all the magic and then it transpiles the TypeScript code to JavaScript. And we have this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> creditCard = {
    <span class="hljs-built_in">number</span>: <span class="hljs-number">2093</span>,
    cardholder: <span class="hljs-string">'TK'</span>,
    expirationDate: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(,
    secutiryCode: <span class="hljs-number">101</span>
};
</code></pre>
<p>The same object, but now only with the value and without the type.</p>
<h2 id="heading-constraints-amp-type-narrowing">Constraints &amp; Type Narrowing</h2>
<p>When we restrict what we can do, it’s easier to understand what we can do.</p>
<p>We use types as constraints to limit the bugs in your program. To understand this concept, I'm stealing an example from Lauren Tan's talk about Type Systems.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> half = <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x / <span class="hljs-number">2</span>;
</code></pre>
<p>How many ways does this function can fail? Imagine a number of possible inputs:</p>
<pre><code class="lang-typescript">[
  <span class="hljs-literal">null</span>,
  <span class="hljs-literal">undefined</span>,
  <span class="hljs-number">0</span>,
  <span class="hljs-string">'0'</span>,
  <span class="hljs-string">'TK'</span>,
  { username: <span class="hljs-string">'tk'</span> },
  [<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>],
  <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b,
]
</code></pre>
<p>And what are the results for input:</p>
<pre><code class="lang-typescript">half(<span class="hljs-literal">null</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// NaN</span>
half(<span class="hljs-number">0</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'0'</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'TK'</span>); <span class="hljs-comment">// NaN</span>
half({ username: <span class="hljs-string">'tk'</span> }); <span class="hljs-comment">// NaN</span>
half([<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>]); <span class="hljs-comment">// NaN</span>
half(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b); <span class="hljs-comment">// NaN</span>
</code></pre>
<p>We have different and unexpected results here. Here it's clear that we want a number as the <code>half</code> function, do the calculation, and great, it's done! But sometimes we don't control the input or the codebase is big, or new/unfamiliar, and we're able to make these little mistakes.</p>
<p>The idea of adding constraints to our code is to narrow the possibilities of a range of types. In this case, we want to limit the input type to a <code>number</code> type. It's the only type that we care about to do the half calculation. With type narrowing, we again give type information to the compiler.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> half = <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span></span>) =&gt;</span> x / <span class="hljs-number">2</span>;
</code></pre>
<p>And with this new information, if we call the function with the test cases again, we have different results:</p>
<pre><code class="lang-typescript">half(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Argument of type 'null' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// Argument of type 'undefined' is not assignable to parameter of type 'number'.(</span>
half(<span class="hljs-number">0</span>); <span class="hljs-comment">// 0</span>
half(<span class="hljs-string">'0'</span>); <span class="hljs-comment">// Argument of type '"0"' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-string">'TK'</span>); <span class="hljs-comment">// Argument of type '"TK"' is not assignable to parameter of type 'number'.</span>
half({ username: <span class="hljs-string">'tk'</span> }); <span class="hljs-comment">// Argument of type '{ username: string; }' is not assignable to parameter of type 'number'.</span>
half([<span class="hljs-number">42</span>, <span class="hljs-number">3.14</span>]); <span class="hljs-comment">// Argument of type 'number[]' is not assignable to parameter of type 'number'.</span>
half(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b); <span class="hljs-comment">// Argument of type '(a: any, b: any) =&gt; any' is not assignable to parameter of type 'number'.</span>
</code></pre>
<p>Basically the compiler will tell us that only the number type, in this case, the <code>0</code> value, is a valid input, it will compile, and allow to run the code. We narrow the input type and allow only the value we really want for this function.</p>
<p>But are other ways to narrow the types in TypeScript. Imagine we have a function that receives a parameter that can be either a string or a number.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> StringOrNumber = <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stringOrNumber</span>(<span class="hljs-params">value: StringOrNumber</span>) </span>{}
</code></pre>
<p>In the function body, the compiler won't know which methods or properties we can use for this type. Is it a string or number? We only know about the value in runtime. But we can narrow the type using the <code>typeof</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stringOrNumber</span>(<span class="hljs-params">value: StringOrNumber</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'string'</span>) {
    <span class="hljs-comment">// value.</span>
        <span class="hljs-comment">// your ide will show you the possible methods from the string type</span>
        <span class="hljs-comment">// (parameter) value: string</span>
    value
  }

  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'number'</span>) {
    <span class="hljs-comment">// value.</span>
        <span class="hljs-comment">// your ide will show you the possible methods from the number type</span>
        <span class="hljs-comment">// (parameter) value: number</span>
    value
  }
}
</code></pre>
<p>With an <code>if</code> statement and the <code>typeof</code>, we can give more information to the compiler. Now it will know the specific type for each <code>if</code> body.</p>
<p>The IDE knows what to show for the specific type. In runtime, when the value is a string, it will go to the first <code>if</code> statement, and the compiler will infer that the type is a string: <code>(parameter) value: string</code>.</p>
<p>When the value is a number, it will go to the second <code>if</code> statement and the compiler will infer that a type is a number: <code>(parameter) value: number</code>.</p>
<p>The <code>if</code> statement can be a helper to the compiler.</p>
<p>Another example is when we have an optional property in an object, but in a function, we need to return a value based on this optional value.</p>
<p>Imagine we have this type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
  name: <span class="hljs-built_in">string</span>;
  address: {
    street: <span class="hljs-built_in">string</span>;
    complement?: <span class="hljs-built_in">string</span>;
  }
};
</code></pre>
<p>It's a simple <code>User</code> type. Let's focus on the <code>complement</code> property. It's optional (take a closer look at the <code>?</code> symbol), which means that it can be a <code>string</code> or <code>undefined</code>.</p>
<p>Now we want to build a function to receive the user and get the length of the address complement. What about this?</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> user.address.complement.length;
    <span class="hljs-comment">// (property) complement?: string | undefined</span>
  <span class="hljs-comment">// Object is possibly 'undefined'.</span>
}
</code></pre>
<p>As we see earlier, the <code>complement</code> can be a <code>string</code> or <code>undefined</code>. <code>undefined</code> doesn't really have a property called <code>length</code>:</p>
<pre><code class="lang-typescript">Uncaught <span class="hljs-built_in">TypeError</span>: Cannot read property <span class="hljs-string">'length'</span> <span class="hljs-keyword">of</span> <span class="hljs-literal">undefined</span>
</code></pre>
<p>We could make something like:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>) </span>{
  <span class="hljs-keyword">return</span> user.address.complement?.length;
}
</code></pre>
<p>If the <code>complement</code> has a string value, we can call <code>length</code>, otherwise, it will return <code>undefined</code>. </p>
<p>So this function has two possible return types: <code>number | undefined</code>. But we want to ensure that we only return <code>number</code>. So we use a <code>if</code> or a ternary condition to narrow the type. It will only call <code>.length</code> when it has real value (or when it is not <code>undefined</code>).</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getComplementLength</span>(<span class="hljs-params">user: User</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> user.address.complement
    ? user.address.complement.length
    : <span class="hljs-number">0</span>;
}
</code></pre>
<p>If it is <code>undefined</code>, we return the minimum length: <code>0</code>. Now we can use the function with the right type design with and without the complement. Without compile and runtime errors.</p>
<pre><code class="lang-typescript">getComplementLength({
  name: <span class="hljs-string">'TK'</span>,
  address: {
    street: <span class="hljs-string">'Shinjuku Avenue'</span>
  }
}); <span class="hljs-comment">// 0</span>

getComplementLength({
  name: <span class="hljs-string">'TK'</span>,
  address: {
    street: <span class="hljs-string">'Shinjuku Avenue'</span>,
    complement: <span class="hljs-string">'A complement'</span>
  }
}); <span class="hljs-comment">// 12</span>
</code></pre>
<p>We'll get <code>0</code> from the first function call and <code>12</code> from the second call.</p>
<p>With this <code>if</code> concept, we can also use other helpers to do the same thing. We could use the <code>in</code> operator to verify a property from an object, a <code>Array.isArray</code> to verify an array, or the <code>instanceof</code> for any other class type.</p>
<p>We could also use more advanced concepts like assertion function or type guards, but I'll leave these concepts to future posts.</p>
<p>One thing that I want to dig deep in this <em>Constraints</em> topic is immutability.</p>
<p>In JavaScript and TypeScript, we have the idea of mutable objects. If you define value in a variable, we can reassign it with another value later.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> email = <span class="hljs-string">'harry.potter@mail.com'</span>;
email <span class="hljs-comment">// 'harry.potter@mail.com'</span>
email = <span class="hljs-string">'hermione.granger@mail.com'</span>;
email <span class="hljs-comment">// 'hermione.granger@mail.com'</span>
</code></pre>
<p>Now imagine you have a list of numbers. And you want to use a function to sum all of its numbers. The function looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumNumbers</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>) </span>{
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">let</span> num = numbers.pop();

  <span class="hljs-keyword">while</span> (num !== <span class="hljs-literal">undefined</span>) {
    sum += num;
    num = numbers.pop();
  }

  <span class="hljs-keyword">return</span> sum;
}
</code></pre>
<p>You call the function passing your list and get the result. It works just fine.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
sumNumbers(list); <span class="hljs-comment">// 10</span>
</code></pre>
<p>But what happened to your list? Did the function mutate it entirely?</p>
<pre><code class="lang-typescript">list; <span class="hljs-comment">// []</span>
</code></pre>
<p>If we use the list, it's empty now. The <code>pop</code> in the <code>sumNumbers</code> function is a "mutate" function. It gets the references and removes the item from them. It's not a copy, it's the real reference.</p>
<p>In runtime, we can use other functions or ways to do the same thing: using reduce, do a for loop without the need to <code>pop</code> items from the array.</p>
<p>But using TypeScript, we can provide immutability in compile time. If you are not using types, it's possible to use a type assertion <code>as const</code>. Imagine this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};

author.books.push({
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">10.00</span>
});
</code></pre>
<p>Just an author object and then we add a new book to this author. The <code>push</code> method updates the book's array reference. It's a "mutate" method. Let's see if you use the const assertion <code>as const</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
} <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>;

author.books.push({
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">10.00</span>
});
<span class="hljs-comment">// Property 'push' does not exist on type</span>
<span class="hljs-comment">// 'readonly [{ readonly title: "Leonardo Da Vinci"; readonly price: 50; }]'</span>
</code></pre>
<p>The compiler won't compile. It gets an error on the author's object. It's is now readonly, and as a readonly object, it has no method called <code>push</code> (or any "mutate" method). </p>
<p>We added a constraint to the author's object. Before it was a specific type (with all the "mutate" methods), and now we narrowed the type to be almost the same, but without the "mutate" methods. Type narrowing.</p>
<p>To continue, let's add types to this object. The <code>book</code> and the <code>author</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = {
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> Author = {
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Book[];
};
</code></pre>
<p>Add the type to the author object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author: Author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};
</code></pre>
<p>Add the type to a new book object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> book: Book = {
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">30</span>
};
</code></pre>
<p>And now we can add the new book to the author:</p>
<pre><code class="lang-typescript">author.name = <span class="hljs-string">'TK'</span>;
author.books.push(book);
</code></pre>
<p>It works just fine!</p>
<p>I want to show another way to add immutability in compile time. TypeScript has a utility type called <code>Readonly</code>.</p>
<p>You can add the <code>readonly</code> for each property in an object. Something like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = {
  <span class="hljs-keyword">readonly</span> title: <span class="hljs-built_in">string</span>;
  <span class="hljs-keyword">readonly</span> price: <span class="hljs-built_in">number</span>;
};
</code></pre>
<p>But it can be very repetitive. So we can use the <code>Readonly</code> utility to add the <code>readonly</code> to all properties of an object:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Book = Readonly&lt;{
  title: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
}&gt;;
</code></pre>
<p>One thing to keep in mind is that it doesn't add the readonly for nested properties. For example, if we add the <code>Readonly</code> to the <code>Author</code> type, it won't add the <code>readonly</code> to the <code>Book</code> type too.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Book[];
}&gt;;
</code></pre>
<p>All the properties from the author can't be reassigned, but you can mutate the <code>books</code> list here (<code>push</code>, <code>pop</code>, ...) because the <code>Book[]</code> is not readonly. Let's see it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> author: Author = {
  name: <span class="hljs-string">'Walter Isaacson'</span>,
  email: <span class="hljs-string">'walter.isaacson@mail.com'</span>,
  books: [
    {
      title: <span class="hljs-string">'Leonardo Da Vinci'</span>,
      price: <span class="hljs-number">50.00</span>,
    }
  ]
};

<span class="hljs-keyword">const</span> book: Book = {
  title: <span class="hljs-string">'Steve Jobs'</span>,
  price: <span class="hljs-number">30</span>
};

author.books.push(book);
author.books;
<span class="hljs-comment">/* =&gt;
 *
 * [
 *   {
 *     title: 'Leonardo Da Vinci',
 *     price: 50.00,
 *   },
 *   {
 *    title: 'Steve Jobs',
 *    price: 30
 *   }
 * ]
 *
 */</span>
</code></pre>
<p>The <code>push</code> will work just fine.</p>
<p>So, how do we enforce a readonly to the <code>books</code>? We need to make sure that the array is a readonly type. We can use the <code>Readonly</code>, or use another utility from TypeScript called <code>ReadonlyArray</code>. Let's see the two ways to do it.</p>
<p>With <code>Readonly</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: Readonly&lt;Book[]&gt;;
}&gt;;
</code></pre>
<p>With <code>ReadonlyArray</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Author = Readonly&lt;{
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  books: ReadonlyArray&lt;Book&gt;;
}&gt;;
</code></pre>
<p>For me, both work great! But in my opinion, <code>ReadonlyArray</code> is more semantic and I also feel it is less verbose (not that the <code>Readonly</code> with an array is).</p>
<p>What happened if we try to mutate the author object now?</p>
<pre><code class="lang-typescript">author.name = <span class="hljs-string">'TK'</span>; <span class="hljs-comment">// Cannot assign to 'name' because it is a read-only property.</span>
author.books.push(book); <span class="hljs-comment">// Property 'push' does not exist on type 'readonly [{ readonly title: "Leonardo Da Vinci"; readonly price: 50; }]'.</span>
</code></pre>
<p>Great! Now we can catch mutable operations in compile time. This is a way to use the concept of adding constraints to our types to make sure they only do what is really needed.</p>
<h2 id="heading-semantics-amp-readability">Semantics &amp; Readability</h2>
<p>At first, I felt that TypeScript could be very verbose because of the types and make the code much more complex than it should be. And it actually can. Strive for simplicity is the goal and it is difficult at the same time.</p>
<p>This idea is very related to clean code and how we can write code to be human-readable and maintainable. TypeScript is no different. Most of the cases, we don't need super complex types. Let the simple types do the work.</p>
<p>Another thing that I find very useful is semantic of types.</p>
<p>Imagine you need to add a string to the <code>sessionStorage</code> to save it in the browser. Your function looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveMyString</span>(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">any</span> </span>{
  sessionStorage.myString = value;
}
</code></pre>
<p>You add a type annotation to the string input and as you don't know about the returning type, you probably add a <code>any</code> type.</p>
<p>But what's the real meaning behind this returning type? Is it returning anything?</p>
<p>It just saves the string to the <code>sessionStorage</code>. It doesn't return anything. The <code>void</code> type was what you're looking for. As TypeScript docs says: <code>the absence of having any type at all</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveMyString</span>(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">void</span> </span>{
  sessionStorage.myString = value;
}
</code></pre>
<p>Great, the meaning of the type is correct now. The correctness is very important in a type system. It's a way to model our data, but also help maintain systems for future developers. Even if the developer is ... you!</p>
<p>Before we were talking about verbose code. And we can improve a lot of our code by using TypeScript type inference.</p>
<p>For some code, we don't need to explicitly add type annotation. The TypeScript compiler will understand and infer it implicitly. For example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> num: <span class="hljs-built_in">number</span> = <span class="hljs-number">1</span>;
</code></pre>
<p>This code is redundant. We can just let the compiler infers it like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> num = <span class="hljs-number">1</span>;
</code></pre>
<p>In our example earlier, we add the annotation <code>void</code> to the <code>saveMyString</code> function. But as the function doesn't return any value, the compiler will infer that the returning type is <code>void</code> implicitly.</p>
<p>When I learned this, I thought with myself. But one of the biggest advantages of using TypeScript (or any other type system / static type language) is types as documentation. If we let the compiler infer most of the types, we won't have the documentation we want.</p>
<p>But if you hover over the TypeScript code in your editor (at least VS Code works like that), you can see the type information and relevant documentation.</p>
<p>Let's see other examples of redundant code and make the code less verbose and let the compiler works for us.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>We don't need the returning type <code>number</code>, because the compiler knows that a <code>number</code> + another <code>number</code> is equal to a <code>number</code> type, and it is the returning type. It can be:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>Implicit code, but with documentation, and the compiler does the work.</p>
<p>Type inference works for methods too:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">squareAll</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>): <span class="hljs-title">number</span>[] </span>{
  <span class="hljs-keyword">return</span> numbers.map(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">number</span> * <span class="hljs-built_in">number</span>);
};
</code></pre>
<p>This function gets a list of numbers and makes every number a squared value. The returning type is <code>number[]</code>, even though the result of a map is always a list, and as we have a list of numbers, it will always be a list of numbers. So we let the compiler infers this too:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">squareAll</span>(<span class="hljs-params">numbers: <span class="hljs-built_in">number</span>[]</span>) </span>{
  <span class="hljs-keyword">return</span> numbers.map(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">number</span> * <span class="hljs-built_in">number</span>);
};
</code></pre>
<p>This works the same way for objects too.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person: { name: <span class="hljs-built_in">string</span>, age: <span class="hljs-built_in">number</span> } = {
  name: <span class="hljs-string">'TK'</span>,
  age: <span class="hljs-number">24</span>
};
</code></pre>
<p>A person object with a string name and a number age. But as we are assigning these values, the compiler can infer these types.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person = {
  name: <span class="hljs-string">'TK'</span>,
  age: <span class="hljs-number">24</span>
};
</code></pre>
<p>If you hover the <code>person</code>, you get this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> person: {
  name: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
}
</code></pre>
<p>The types are documented here.</p>
<p>Another benefit of type inference is that we can easily refactor our code. It's a simple example, but good to illustrate the refactoring process. Let's get the <code>sum</code> function again.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>Instead of returning the sum number, we want to return <code>"Sum: {a + b}"</code>. So for <code>a = 1</code> and <code>b = 2</code>, we have the resulting string as <code>"Sum: 3"</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">string</span> </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Sum: <span class="hljs-subst">${a + b}</span>`</span>;
};

sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// Sum: 3</span>
</code></pre>
<p>Great! But now letting the compiler infers this.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// function sum(a: number, b: number): number</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
};

<span class="hljs-comment">// function sum(a: number, b: number): string</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Sum: <span class="hljs-subst">${a + b}</span>`</span>;
};
</code></pre>
<p>We just need to modify the returning value and the type inference will work. No need to think about the returning type. This is a small example, but for more complex functions, it would work too.</p>
<p>Back to the readability part, we can use <code>Enum</code>. A utility that defines a set of named constants. It's a way to give more meaning to the data in your application.</p>
<p>In your node app or a frontend app, you possibly do some fetching to request data. You commonly use a fetch object to perform a request and sometimes you need to pass the accept headers.</p>
<pre><code class="lang-typescript">fetch(<span class="hljs-string">'/pokemons'</span>, {
  headers: {
    Accept: <span class="hljs-string">'application/json'</span>
  }
});

fetch(<span class="hljs-string">'/harry-potter/spells'</span>, {
  headers: {
    Accept: <span class="hljs-string">'application/json'</span>
  }
});
</code></pre>
<p>It's good, but we can also use an enum to separate this accept string in a constant and reuse.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> MediaTypes {
  <span class="hljs-built_in">JSON</span> = <span class="hljs-string">'application/json'</span>
}

fetch(<span class="hljs-string">'/pokemons'</span>, {
  headers: {
    Accept: MediaTypes.JSON
  }
});

fetch(<span class="hljs-string">'/harry-potter/spells'</span>, {
  headers: {
    Accept: MediaTypes.JSON
  }
});
</code></pre>
<p>And we are able to add more data related to the <code>MediaTypes</code> like <code>PDF</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> MediaTypes {
  <span class="hljs-built_in">JSON</span> = <span class="hljs-string">'application/json'</span>,
  PDF = <span class="hljs-string">'application/pdf'</span>
}
</code></pre>
<p>With <code>Enum</code>, we can encapsulate data into a meaningful block of code.</p>
<p>Recently, I was implementing a "state" React component. It's basically a component that renders an empty state or an error state based on the request response.</p>
<p>The UI for the empty and the error states were very similar. Only the title and the description text and the image icon were different. So I thought: "I have two ways in my mind to implement this: do the logic outside the component and pass all the information needed or pass a 'state type' and let the component render the correct icon and messages."</p>
<p>So I built an enum:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-built_in">enum</span> StateTypes {
  Empty = <span class="hljs-string">'Empty'</span>,
  <span class="hljs-built_in">Error</span> = <span class="hljs-string">'Error'</span>
};
</code></pre>
<p>And I could just pass this data to the component as the <code>type</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> ComponentState, { StateTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">'./ComponentState'</span>;

&lt;ComponentState <span class="hljs-keyword">type</span>={StateTypes.Empty} /&gt;
&lt;ComponentState <span class="hljs-keyword">type</span>={StateTypes.Error} /&gt;
</code></pre>
<p>In the component, it had a state object with all the information related to the <code>title</code>, <code>description</code>, and <code>icon</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> stateInfo = {
  Empty: {
    title: messages.emptyTitle,
    description: messages.emptyDescription,
    icon: EmptyIcon,
  },
  <span class="hljs-built_in">Error</span>: {
    title: messages.errorTitle,
    description: messages.errorDescription,
    icon: ErrorIcon,
  },
};
</code></pre>
<p>So I could just receive the type based on the enum and use this <code>stateInfo</code> object with the <code>State</code> component from our design system:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ComponentState = <span class="hljs-function">(<span class="hljs-params">{ <span class="hljs-keyword">type</span> }</span>) =&gt;</span> (
  &lt;State
    title={stateInfo[<span class="hljs-keyword">type</span>].title}
    subtitle={stateInfo[<span class="hljs-keyword">type</span>].subtitle}
    icon={stateInfo[<span class="hljs-keyword">type</span>].icon}
  /&gt;
);
</code></pre>
<p>This is a way to use an enum to encapsulate important data into a meaningful block of code in your application.</p>
<p>Another cool feature from TypeScript is optional properties. When we have properties from an object that can be a real value or undefined, we use an optional property to be explicitly that the property can be or not be there. The syntax for this is a simple <code>?</code> operator in the object property. Imagine this function:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>But now the <code>c</code> value is optional:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c?: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>We add the <code>?</code> after <code>c</code>. But now we have a compiler error saying:</p>
<pre><code class="lang-typescript">(parameter) c: <span class="hljs-built_in">number</span> | <span class="hljs-literal">undefined</span>
<span class="hljs-built_in">Object</span> is possibly <span class="hljs-string">'undefined'</span>.
</code></pre>
<p>We can't sum an <code>undefined</code> value (well, actually in JavaScript we can, but we receive a <code>NaN</code> value).</p>
<p>We need to ensure that the <code>c</code> exists. Type narrowing!</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c?: <span class="hljs-built_in">number</span></span>) </span>{
  <span class="hljs-keyword">if</span> (c) {
    <span class="hljs-keyword">return</span> a + b + c;
  }

  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>If the <code>c</code> exists, it will be a <code>number</code> and we can sum all. If not, sum only the <code>a</code> and <code>b</code> values.</p>
<p>An interesting part of this optional property is that it is a <code>undefined</code> not <code>null</code>. This is why we do this, we get a compile error:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> <span class="hljs-built_in">number</span> = <span class="hljs-literal">null</span>;
sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-built_in">number</span>);
<span class="hljs-comment">// Argument of type 'null' is not assignable to parameter of type 'number | undefined'.</span>
</code></pre>
<p>As the <code>?</code> operator doesn't handle the <code>null</code> value, choose to use the <code>undefined</code> type in your application and so you can still use the optional property and make the types consistent. We can use it like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> value: <span class="hljs-built_in">number</span> | <span class="hljs-literal">undefined</span>;
sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, value); <span class="hljs-comment">// 3</span>
</code></pre>
<p>If you add a default value to the parameter, you won't need the <code>?</code> operator. Actually, the compiler will say that the <code>Parameter cannot have question mark and initializer</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">a: <span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span>, c: <span class="hljs-built_in">number</span> = 3</span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
</code></pre>
<p>Optional properties not only works on variables and parameters, but also in objects.</p>
<p>An API response is a good example of type definition and optional property together. In API responses, data can be optional. Sometimes the API sends, sometimes it has no value.</p>
<p>How we model our types is really important for an application. If an optional property is defined as a required type, we can make our application breaks in runtime. But if we design the types correctly, we have the possible errors in compile time.</p>
<p>Imagine we are fetching a user data and this is the way we modeled the response type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> UserResponse = {
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
  username: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
  isActive: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>But in reality, the email is optional for the user. The API endpoint could return or not. But the <code>UserResponse</code> type we built treat it as a required property.</p>
<p>After fetching the user data, we want to see if the user email matches with a specific domain.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">return</span> email.endsWith(domain);
}
</code></pre>
<p>As the <code>email</code> property is required in the <code>UserResponse</code> type, the <code>email</code> parameter will also be required in the <code>matchDomain</code> function.</p>
<p>This is the runtime we can get if the <code>email</code> is <code>undefined</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Uncaught TypeError: Cannot read property 'endsWith' of undefined</span>
</code></pre>
<p>But what would happen if we modeled the <code>UserResponse</code> correctly?</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> UserResponse = {
  name: <span class="hljs-built_in">string</span>;
  email?: <span class="hljs-built_in">string</span>;
  username: <span class="hljs-built_in">string</span>;
  age: <span class="hljs-built_in">number</span>;
  isActive: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>Now the <code>email</code> is possibly <code>undefined</code> and it is explicit.</p>
<p>But if we still keep the function <code>matchDomain</code> the same way, we get a compile error:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Argument of type 'undefined' is not assignable to parameter of type 'string'.</span>
</code></pre>
<p>And this is great! Now we can fix the <code>email</code> parameter in this function using the <code>?</code> operator:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email?: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">return</span> email.endsWith(<span class="hljs-string">'email.com'</span>);
}
</code></pre>
<p>But now we get a compile error when running <code>email.endsWith</code>, because it could be <code>undefined</code> too:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// (parameter) email: string | undefined</span>
<span class="hljs-comment">// Object is possibly 'undefined'.</span>
</code></pre>
<p>Type narrowing! We use an if block to return a <code>false</code> when the <code>email</code> is <code>undefined</code>. And run <code>endsWith</code> method only if the <code>email</code> is really a string:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchDomain</span>(<span class="hljs-params">email?: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">if</span> (!email) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  <span class="hljs-keyword">return</span> email.endsWith(<span class="hljs-string">'email.com'</span>);
}
</code></pre>
<p>It's pretty nice when we can get runtime errors in compile time. Better to code than debugging after we ship in production, isn't it?</p>
<h2 id="heading-type-composition">Type composition</h2>
<p>Type composition is very useful when trying to reuse existing types for new places of the codebase. We don't need to rewrite new types, we can create a new type by composing existing ones.</p>
<p>One example of composition I always have to handle using Redux or the <code>useReducer</code> hook from React is the idea of "reducers". A reducer can always receive a number of different actions.</p>
<p>In this context, actions are objects with at least a <code>type</code> property. It looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> ActionTypes {
  FETCH = <span class="hljs-string">'FETCH'</span>
}

<span class="hljs-keyword">type</span> FetchAction = {
  <span class="hljs-keyword">type</span>: <span class="hljs-keyword">typeof</span> ActionTypes.FETCH;
};

<span class="hljs-keyword">const</span> fetchAction: FetchAction = {
  <span class="hljs-keyword">type</span>: ActionTypes.FETCH
};
</code></pre>
<p>A <code>fetchAction</code> has a type <code>FetchAction</code> that has a property type that is a typeof <code>FETCH</code>.</p>
<p>But a reducer can receive other actions too. For example a submit action:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">enum</span> ActionTypes {
  FETCH = <span class="hljs-string">'FETCH'</span>,
  SUBMIT = <span class="hljs-string">'SUBMIT'</span>
}

<span class="hljs-keyword">type</span> SubmitAction = {
  <span class="hljs-keyword">type</span>: <span class="hljs-keyword">typeof</span> ActionTypes.SUBMIT;
};

<span class="hljs-keyword">const</span> submitAction: SubmitAction = {
  <span class="hljs-keyword">type</span>: ActionTypes.SUBMIT
};
</code></pre>
<p>For a specific container, we can compose all these actions into just one type and use it for the reducer parameter type.</p>
<p>It would look like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Actions = FetchAction | SubmitAction;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action: Actions</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ActionTypes.FETCH:
    <span class="hljs-comment">// fetching action</span>
    <span class="hljs-keyword">case</span> ActionTypes.SUBMIT:
    <span class="hljs-comment">// submiting action</span>
  }
}
</code></pre>
<p>All the possible actions are the <code>Actions</code> type. And we use a union type to "join" all action types. The action in the reducer can have the <code>FetchAction</code> or the <code>SubmitAction</code>.</p>
<p>As a Potterhead, I couldn't miss a Harry Potter example. I want to build a simple function to choose a Hogwarts House based on the person trait. Let's start with the houses first.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> House = {
  name: <span class="hljs-built_in">string</span>;
  traits: <span class="hljs-built_in">string</span>[];
}

<span class="hljs-keyword">const</span> gryffindor: House = {
  name: <span class="hljs-string">'Gryffindor'</span>,
  traits: [<span class="hljs-string">'courage'</span>, <span class="hljs-string">'bravery'</span>]
};

<span class="hljs-keyword">const</span> slytherin: House = {
  name: <span class="hljs-string">'Slytherin'</span>,
  traits: [<span class="hljs-string">'ambition'</span>, <span class="hljs-string">'leadership'</span>]
};

<span class="hljs-keyword">const</span> ravenclaw: House = {
  name: <span class="hljs-string">'Ravenclaw'</span>,
  traits: [<span class="hljs-string">'intelligence'</span>, <span class="hljs-string">'learning'</span>]
};

<span class="hljs-keyword">const</span> hufflepuff: House = {
  name: <span class="hljs-string">'Hufflepuff'</span>,
  traits: [<span class="hljs-string">'hard work'</span>, <span class="hljs-string">'patience'</span>]
};

<span class="hljs-keyword">const</span> houses: House[] = [
  gryffindor,
  slytherin,
  ravenclaw,
  hufflepuff
];
</code></pre>
<p>I want to keep it simple, so the <code>House</code> type has only the <code>name</code> and the <code>traits</code>, a list of possible traits from people related to the house.</p>
<p>And then, I create each house and added all of them to the <code>houses</code> list.</p>
<p>Great! Now I'll build the <code>Person</code> type. A person can be a witch or a muggle.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Witch = {
  name: <span class="hljs-built_in">string</span>;
  trait: <span class="hljs-built_in">string</span>;
    magicFamily: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">type</span> Muggle = {
  name: <span class="hljs-built_in">string</span>;
    trait: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
}
</code></pre>
<p>And this is the part we combine these two different types using the union type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Person = Muggle | Witch;
</code></pre>
<p>Using the intersection type, the <code>Person</code> type has all properties from <code>Muggle</code> or all from  <code>Witch</code>.</p>
<p>So now, if I create a <code>Muggle</code>, I need just the name, the trait, and the email:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> hermione: Muggle = {
  name: <span class="hljs-string">'Hermione Granger'</span>,
    trait: <span class="hljs-string">'bravery'</span>,
  email: <span class="hljs-string">'hermione@mail.com'</span>
};
</code></pre>
<p>If I create a <code>Witch</code>, I need the name, the trait, and the magic family name:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> harry: Witch = {
  name: <span class="hljs-string">'Harry Potter'</span>,
  trait: <span class="hljs-string">'courage'</span>,
  magicFamily: <span class="hljs-string">'Potter'</span>
};
</code></pre>
<p>And if I create a <code>Person</code>, I need at least the <code>name</code> and the <code>trait</code> properties from <code>Muggle</code> and <code>Witch</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> tk: Person = {
  name: <span class="hljs-string">'TK'</span>,
  email: <span class="hljs-string">'tk@mail.com'</span>,
  trait: <span class="hljs-string">'learning'</span>,
  magicFamily: <span class="hljs-string">'Kinoshita'</span>
};
</code></pre>
<p>The <code>chooseHouse</code> is very simple. We just pas the houses and the person. Based on the person trait, the function will return the chosen house:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">chooseHouse</span>(<span class="hljs-params">houses: House[], person: Person</span>) </span>{
  <span class="hljs-keyword">return</span> houses.find(<span class="hljs-function">(<span class="hljs-params">house</span>) =&gt;</span> house.traits.includes(person.trait))
}
</code></pre>
<p>And applying all the people we created:</p>
<pre><code class="lang-typescript">chooseHouse(houses, harry); <span class="hljs-comment">// { name: 'Gryffindor', traits: ['courage', 'bravery'] }</span>
chooseHouse(houses, hermione); <span class="hljs-comment">// { name: 'Gryffindor', traits: ['courage', 'bravery'] }</span>
chooseHouse(houses, tk); <span class="hljs-comment">// { name: 'Ravenclaw', traits: ['intelligence', 'learning'] }</span>
</code></pre>
<p>Nice!</p>
<p>The intersection type is a bit different, but it can also be used to combine existing types.</p>
<p>When I was implementing a web app to <a target="_blank" href="https://github.com/leandrotk/ux-studies">apply my studies on UX</a>, I needed to create a prop type for the Image component.</p>
<p>I had the type <code>ImageUrl</code> from the product type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageUrl = {
  imageUrl: <span class="hljs-built_in">string</span>;
};
</code></pre>
<p>And the <code>ImageAttr</code> to represent all the attributes for the image:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageAttr = {
  imageAlt: <span class="hljs-built_in">string</span>;
  width?: <span class="hljs-built_in">string</span>
};
</code></pre>
<p>But the props expected all this information in the component. Intersection type for the rescue!</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageProps = ImageUrl &amp; ImageAttr;
</code></pre>
<p>Simple as that. So now, the component needs all these properties. The type looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ImageProps = {
  imageUrl: <span class="hljs-built_in">string</span>;
  imageAlt: <span class="hljs-built_in">string</span>;
  width?: <span class="hljs-built_in">string</span>
};
</code></pre>
<p>And we can use this type this way:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> imageProps: ImageProps = {
  imageUrl: <span class="hljs-string">'www.image.com'</span>,
  imageAlt: <span class="hljs-string">'an image'</span>,
};

<span class="hljs-keyword">const</span> imagePropsWithWidth: ImageProps = {
  imageUrl: <span class="hljs-string">'www.image.com'</span>,
  imageAlt: <span class="hljs-string">'an image'</span>,
  width: <span class="hljs-string">'100%'</span>
};
</code></pre>
<p>Nice! One more concept to reuse and compose types.</p>
<p>I also find the <code>Pick</code> type very interesting and useful. We have other <a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">interesting types</a> that we could write here, but the idea here is to understand that we can compose type and there is no limit to reuse types. If you're interested in study other types, take a look at this post I wrote: <a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">TypeScript Learnings: Interesting Types</a>.</p>
<h2 id="heading-tooling">Tooling</h2>
<p>When you <code>npm install typescript</code>, you don't just get the compiler, you get the language service API, a standalone server called tsserver that editors can run to provide autocompletion, go-to, and other cool features.</p>
<p>These features are what some people from the TypeScript team call developer productivity tools like smart errors when type checking and IntelliSense (code completion, hover info, signature information). We look at these features throughout the whole article, but I want to make a special topic to talk about it.</p>
<p>The TypeScript type checker is powerful in the sense that it can infer types and provide information to some possible issues. Example: It inferred that the city is a string. And the <code>uppercase</code> is used the wrong way. As it knows it is a string, it also tries to find a possible method that the engineer is looking for.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> city = <span class="hljs-string">'Tokyo'</span>;
city.toUppercase();
<span class="hljs-comment">// Property 'toUppercase' does not exist on type</span>
<span class="hljs-comment">// 'string'. Did you mean 'toUpperCase'?</span>
</code></pre>
<p>In this case, the compiler is really smart, because it finds exatcly what we wanted.</p>
<p>It also works for objects:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> people = [
  { name: <span class="hljs-string">'TK'</span>, age: <span class="hljs-number">24</span> },
  { name: <span class="hljs-string">'Kaio'</span>, age: <span class="hljs-number">12</span> },
  { name: <span class="hljs-string">'Kazumi'</span>, age: <span class="hljs-number">31</span> },
];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> person <span class="hljs-keyword">of</span> people) {
  <span class="hljs-built_in">console</span>.log(person.agi);
  <span class="hljs-comment">// Property 'agi' does not exist on type '{ name: string; age: number; }'</span>
}
</code></pre>
<p>With the static types, the tooling can provide a great developer experience with code completion, hover info to show defined types, and signature information for methods and other data.</p>
<p>If you type: <code>'TK'.</code>, the editor will show all the possible methods for the string object. The compiler knows it is a string. And it knows the methods from the <code>String</code> prototype. But it also provides the method signature. This is very interesting because we don't necessarily need to go to the docs. The "docs" is already in our code editor.</p>
<p>It's an awesome experience while coding.</p>
<p>The type definition "on hover" is another thing that we saw earlier in this article. Let the compiler infer the types implicitly and you won't lose the type documentation. Using the hover in the object, the IDE or editor will always be able to show the type definition.</p>
<p>Another interesting thing is that TypeScript will not only flag what could go wrong on runtime, but it also helps to find code that doesn't do what you intend.</p>
<p>Imagine we have a function to open a snackbar if it is still closed. It would verify the status of the snackbar. If it is closed, just call another function to open it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> buildSnackbar = <span class="hljs-function">(<span class="hljs-params">status: SnackbarStatus</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (status.isClosed) {
    openSnackbar();
  }
};
</code></pre>
<p>And the type information for this snackbar is:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> SnackbarStatus = {
  isClosed: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<p>What happens if I call this function like this:</p>
<pre><code class="lang-typescript">buildSnackbar({ isclosed: <span class="hljs-literal">true</span> });
</code></pre>
<p>It won't break in runtime, because the <code>status</code> object has no <code>isClosed</code> attribute and the <code>undefined</code> object is a <code>falsy</code> value, so it will skip the if condition and not call the <code>openSnackbar</code> function. No runtime error. But probably it will behavior different than the expected.</p>
<p>In TypeScript, the compiler will give some hints to make it works properly. First it will show this error:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Argument of type '{ isclosed: boolean; }' is not assignable to</span>
<span class="hljs-comment">// parameter of type 'SnackbarStatus'.</span>
</code></pre>
<p><code>isclosed</code> with downcased <code>C</code> is not assignable to the type. It's not defined there. This is the first hint to make you correct your code.</p>
<p>The second is even better:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Object literal may only specify known properties,</span>
<span class="hljs-comment">// but 'isclosed' does not exist in type 'SnackbarStatus'.</span>
<span class="hljs-comment">// Did you mean to write 'isClosed'?</span>
</code></pre>
<p>It tells exactly what you probably need to do: rename the <code>isclosed</code> to <code>isClosed</code>.</p>
<p>We can talk a lot of things about the tooling about I think this is the main part.</p>
<p>My suggestion to learn more about this is to just code in TypeScript and "have a conversation" with the compiler. Read the errors. Play with the hover. See the autocompletion. Understand the method signatures. It's really a productive way to code.</p>
<h2 id="heading-tips-amp-learnings">Tips &amp; Learnings</h2>
<p>As the article is coming to an end, I want to just add some final thoughts, learnings, and tips to help you in your journey learning TypeScript or just applying it in your projects.</p>
<ul>
<li>Really read the type error: this will help you better understand the issue and the types.</li>
<li><code>strictNullChecks</code> and <code>noImplicitAny</code> can be very helpful in finding bugs. Enable this as soon as possible in your project. Use <code>strictNullChecks</code> to prevent “undefined is not an object”-style runtime errors. Use <code>noImplicitAny</code> to type the source code to give more type information for the compiler.</li>
<li>Together with the compiler's configurations, I always recommend being very precise about your types. Mainly with the values that occur only in runtime like an API response. Correctness is important to catch as many bugs as possible in compile time.</li>
<li>Understand the difference between runtime and compile time: types only affect in compile type. It runs the type checker and then compiles to JavaScript. The JavaScript source code doesn't use any type of references or type operations.</li>
<li>Learn about utility types. We talked more specifically about the <code>Readonly</code> in the immutability in compile time, but TypeScript has a box of helpers like <code>Required</code>, <code>Pick</code>, and many more.</li>
<li>If possible, prefer letting the compiler infers the types for you. Most of the types and returning types are redundant. The TypeScript compiler is very smart in this area. If not possible, you can always add type annotations. And leave the type assertions as the last option.</li>
<li>As you're writing code, take a look at the tooling. The design of the tooling provided in an IDE is amazing. The IntelliSense and type checking provide a really good experience.</li>
</ul>
<p>This post was originally published at <a target="_blank" href="https://leandrotk.github.io/tk/2020/07/a-mental-model-to-think-in-typescript/index.html">TK's blog</a>. And you can find more content like this in my blog at <a target="_blank" href="https://leandrotk.github.io/tk/">https://leandrotk.github.io/tk</a>.</p>
<p>You can also follow me on <a target="_blank" href="https://twitter.com/leandrotk_">Twitter</a> and <a target="_blank" href="https://github.com/leandrotk">GitHub</a>.</p>
<h1 id="heading-resources">Resources</h1>
<p>I compiled (pun very much intended!) a bunch of resources to help you learn more about programming languages, type systems, and the type mental model.</p>
<p>Also, if you found the examples on this post useful, I added all of them this repository: <a target="_blank" href="https://github.com/leandrotk/thinking-in-types">Thinking in Types</a>. So you can fork and play with it.</p>
<h3 id="heading-type-systems">Type Systems</h3>
<ul>
<li><a target="_blank" href="https://www.typescriptlang.org/docs/handbook/type-compatibility.html">Type Compatibility</a></li>
<li><a target="_blank" href="https://medium.com/@thejameskyle/type-systems-structural-vs-nominal-typing-explained-56511dd969f4">Type Systems: Structural vs. Nominal typing explained</a></li>
<li><a target="_blank" href="https://yakovfain.com/2018/07/11/learning-typescript-structural-vs-nominal-typing-system/">Learning TypeScript: Structural vs nominal typing systems</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=GqmsQeSzMdw&amp;feature=youtu.be">Constraints Liberate, Liberties Constrain — Runar Bjarnason</a></li>
<li><a target="_blank" href="https://www.no.lol/2019-12-27-type-narrowing/">Type Narrowing in TypeScript</a></li>
<li><a target="_blank" href="https://2ality.com/2020/06/type-guards-assertion-functions-typescript.html">TypeScript: narrowing types via type guards and assertion functions</a></li>
<li><a target="_blank" href="https://leandrotk.github.io/tk/2020/05/typescript-learnings-interesting-types/index.html">TypeScript Learnings: Interesting Types</a></li>
</ul>
<h3 id="heading-tooling-amp-developer-experience">Tooling &amp; Developer Experience</h3>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=fnTEZk-oECM">Advanced TypeScript tooling at scale</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=4C4wCGcsiT0">Type Systems &amp; Props Design</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=wSdV1M7n4gQ">Anders Hejlsberg on Modern Compiler Construction</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=f6TCB61fDwY">TypeScript Compiler explained by the Author Anders Hejlsberg</a></li>
</ul>
<h3 id="heading-compile-time-vs-runtime">Compile time vs Runtime</h3>
<ul>
<li><a target="_blank" href="https://stackoverflow.com/questions/846103/runtime-vs-compile-time">Compile time vs Runtime</a></li>
<li><a target="_blank" href="https://stackoverflow.com/questions/9471837/what-is-the-difference-between-run-time-error-and-compiler-error">Compile error vs Runtime error</a></li>
<li><a target="_blank" href="https://stackoverflow.com/a/51132333/3159162">Value space and Type space</a></li>
<li><a target="_blank" href="https://www.typescriptlang.org/play">A playground tool to play with TypeScript and see the JavaScript output</a></li>
</ul>
<h3 id="heading-best-practices">Best Practices</h3>
<ul>
<li><a target="_blank" href="https://engineering.zalando.com/posts/2019/02/typescript-best-practices.html">TypeScript Best Practices</a></li>
<li><a target="_blank" href="https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html">Do's and Don'ts for General Types</a></li>
</ul>
<h3 id="heading-books">Books</h3>
<ul>
<li><a target="_blank" href="https://www.goodreads.com/book/show/48920810-programming-with-types">Programming with Types Book</a></li>
<li><a target="_blank" href="https://www.goodreads.com/book/show/48570456-effective-typescript">Effective TypeScript: 62 Specific Ways to Improve Your TypeScript Book</a></li>
<li><a target="_blank" href="https://thinkingwithtypes.com/">Thinking with Types</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
