<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jimmy Jiang on Medium]]></title>
        <description><![CDATA[Stories by Jimmy Jiang on Medium]]></description>
        <link>https://medium.com/@jj810?source=rss-ea5aea48d7eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H9xO1CwfCwcyXuvqLPAAMg.png</url>
            <title>Stories by Jimmy Jiang on Medium</title>
            <link>https://medium.com/@jj810?source=rss-ea5aea48d7eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:14:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jj810/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Object-Oriented vs Functional Programming with Typescript]]></title>
            <link>https://blog.devgenius.io/object-oriented-vs-functional-programming-with-typescript-6b2243bb8c4b?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b2243bb8c4b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 11:01:09 GMT</pubDate>
            <atom:updated>2020-10-20T11:01:09.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*0rh5T6BnPa6KkncF5UtibQ.png" /></figure><p>Object-orient or functional programming?</p><p>How about object-oriented vs functional programming?<br>If you guessed object-oriented is better you’re completely wrong :)<br>And if you guessed functional programming you’re way off base ;)</p><p>Debating programming paradigms at this level is like debating art.<br>There is always more than one way to solve a problem especially in Javascript and it’s great to debate these things but there are no absolutes.</p><p>There is going to be a trade-off for every decision that you make.<br>Let’s start by taking a look at some functional typescript code.</p><h3>Pure Functions</h3><p>The most important concept in functional programming is the concept of pure functions. This means that the output of your function should only depend on its inputs. For example:</p><pre>let num = 123;<br>function toString(val) {<br>    return val.toString();<br>}</pre><p>Here we have a function called toString() which takes a value as its argument and then returns that value formatted as a string. We can make this an impure function by mutating the number variable directly.</p><pre>let num = 123;<br>function toString(val) {<br>    num = val;<br>    ...<br>}</pre><p>This would be considered a side-effect and functional code should produce no side-effects. In addition they should not rely on any outside value to produce a return value. Pure functions are easier to test and also easier to reason about because you don’t have to think about anything happening outside of the function itself.</p><h3>Immutable Data</h3><p>Another core principle of functional programming is immutable data. Functional code is stateless meaning that when data is created it is never mutated. For example, we have:</p><pre>const data = [1,2,3,4,5,6];</pre><p>We can simulate this in Javascript by using Object.freeze on this array of numbers.</p><pre>const data = Object.freeze([1,2,3,4,5]);</pre><p>We could hack around this but it prevents us from doing things like array push which you wouldn’t do in a functional program. So obviously our data has to change somehow if we have a dynamic software application so you’ll often be passing functions as arguments to other functions.</p><pre>const addEmoji = (val) =&gt; toString(val) + &#39; 😃&#39;;</pre><p>So here, we have a typical first-order function which takes a value and returns a different value. In this case, just appending an emoji to a string.</p><p>Now a higher-order function is one that either takes a function as an argument or it returns a function itself. Javascript has some really nice built-in higher-order functions for arrays such as map. So instead of using a for loop, we can just pass in our function to map which will run our add emoji function on every element in the array and transform the value. So that gives us a very concise and elegant way to transform the values in an array.</p><pre>const emojiData = data.map(addEmoji);<br>console.log(emojiData);  // [&#39;1 😃&#39;, &#39;2 😃&#39;, &#39;3 😃&#39;, &#39;4 😃&#39;, &#39;5 😃&#39;]</pre><p>Another cool thing we can do is create functions that return functions.<br>This is very useful when you want to start with some base functionality and then extend it with some dynamic data.</p><p>Let’s imagine we are building a weather app and we need to append strings with certain emojis. We will start with a base function called appendEmoji and then use it to compose more complex functions.</p><pre>const appendEmoji = (fixed) =&gt; (dynamic) =&gt; fixed + dynamic;</pre><p>So in this case, the inner function takes both of the arguments and adds them together. We can use this to create more specialized functions that point to a specific emoji. For example:</p><pre>const rain = appendEmoji(&#39;🌧️&#39;);<br>const sun = appendEmoji(&#39;️🌞&#39;);</pre><pre>console.log(rain(&#39; today&#39;))  // ️🌧️ ️️today<br>console.log(sun(&#39; tomorrow&#39;))  // ️🌞 tomorrow</pre><p>Here, we have a rain function and a sun function then we can call this function with the string that we want the emoji appended to. The end result is some concise and readable code that doesn’t rely on any shared state that would make it difficult to test. That’s about as basic as it gets for functional programming and things get a lot more interesting when you have asynchronous data and side-effects and things like that.</p><p>So now let’s go ahead and compare this to object-oriented programming.</p><p>The first thing we will do is define a class which itself doesn’t really do anything but rather it serves as a blue print for instantiating objects so an instance of this emoji class will be an object with an icon property. Then the constructor method is special because it runs once when the object is instantiated. It will pass an argument to the constructor with the actual emoji icon and then we will set that equal to the property on this object. Like this:</p><pre>class Emoji {<br>    icon: string;<br>    <br>    constructor(icon) {<br>        this.icon = icon;<br>    }<br>}</pre><pre>const sun = new Emoji(&#39;️🌞&#39;)</pre><pre>console.log(sun) // Emoji { icon: &#39;️🌞&#39; }</pre><p>The emoji class works similar to a function but we use the new keyword in front of it. And as you can see when we do that it creates an emoji object with an icon property of sun. In typescript there’s an easier way to do this because we have the concept of public and private members. So if we use the public keyword in front of the argument in the constructor, typescript will automatically know to set that as a public property on each object. When you declare a property or method public, it means it’s available to the class itself and any instances of the class.</p><pre>class Emoji {<br>    constructor(public icon) {}<br>}</pre><p>That can be both a good and a bad thing. For example, we can simply change the icon by just mutating the value on its object.</p><pre>const sun = new Emoji(&#39;️🌞&#39;)<br>sun.icon = &#39;🌧️&#39;<br>console.log(sun) // Emoji { icon: &#39;🌧️&#39; }</pre><p>On one hand it’s very convenient but on the other hand if you have a lot of code doing this it can be hard to keep track of and hard to test effectively.</p><p>Typescript also provides some tools for us to improve the tone that we have when writing object-oriented code. For example, we can mark members as private so that they can only be used inside of this class definition. This means that we can separate our public API from internal logic for this class. For example if we want to make this icon value mutable, we can make it private and we will define a getter so the user can read the value but not change the value.</p><pre>class Emoji {<br>    constructor(private _icon) {}</pre><pre>    get icon() {<br>        return this._icon;<br>    }<br>}</pre><p>Another important thing to point out here is that class instances can have their own internal state. Let’s imagine we have a button where the user can toggle the emoji and maybe go back and forth between different states. This is a really simple thing to implement an object-oriented programming.</p><p>We will add another private property to this class called previous and then use a getter to retrieve that value then we will define a change method which will mutate the actual icon value on this instance.</p><pre>class Emoji {</pre><pre>    private _prev;</pre><pre>    constructor(private _icon) {}</pre><pre>    get icon() {<br>        return this._icon;<br>    }</pre><pre>    get prev() {<br>        return this._prev;<br>    }</pre><pre>    change(val) {<br>        this._prev = this._icon;<br>    }<br>}</pre><p>When this happens we will first change the previous value to the current icon and then update the current icon to the new value.</p><pre>const emoji = new Emoji(&#39;️🌞&#39;)</pre><pre>console.log(emoji.icon, emoji.prev) // ️🌞 undefined</pre><p>On this first console log, we get the sun icon and undefined and</p><pre>emoji.change(&#39;🌧️&#39;);<br>emoji.change(&#39;🌪️&#39;);</pre><pre>console.log(emoji.icon, emoji.prev) // &#39;🌪️&#39;, &#39;🌧️&#39;</pre><p>If we mutate the state a couple times like above, you can see that our internal values on this class instance have changed.</p><h3>Static Methods</h3><p>The another cool thing you can do with classes is define static methods.</p><p>The unique thing about a method is that it’s on the class itself and not an instance of a class. So we will define a static method here which itself is actually a pure function and its job is simply to add one to the input argument.</p><pre>class Emoji {<br>    static addOneTo(val) {<br>        return 1 + val;<br>    }<br>}</pre><p>Now we can use the Emoji class as a namespace to run this function.</p><pre>Emoji.addOneTo(3);</pre><p>Now we are going to switch gears and talk about composition versus inheritance for code reusability. This is an area where people tend to get very strong opinions and the actual definition of composition tends to be a little convoluted. Let’s go ahead and take a look at an example of inheritance.</p><pre>class Human {</pre><pre>    constructor(public name) {}</pre><pre>    sayHi() {<br>        return `Hello, ${this.name}`;<br>    }<br>}</pre><pre>const patrick = new Human(&#39;Patrick Mullot&#39;)</pre><pre>console.log(patrick.sayHi()); // Hello, Patrick Mullot</pre><p>If we have a lot of other objects in our program that are similar but implement slightly different features based on what they’re designed to do. For example in a video game, you might have a human character and then a super human character that has all the human abilities but with a little something extra.<br>In typescript we can simply inherit all the functionality from the human class by saying SuperHuman extends human like this:</p><pre>class SuperHuman extends Human {<br>    <br>    heroName;</pre><pre>    constructor(name) {<br>        super(name);<br>    }<br>}</pre><p>Here we call super which will execute the code in the constructor of the parent class which in our case is just initializing this name property.</p><p>At this point we can go ahead and define an additional method called superpower().</p><pre>class SuperHuman extends Human {<br>    <br>    heroName;</pre><pre>    constructor(name) {<br>        super(name);<br>        this.heroName = `HERO ${name}`;</pre><pre>    superpower() {<br>        return `${this.heroName} pops treys 🔥🔥🔥`<br>    }<br>}</pre><pre>const steph = new SuperHuman(&#39;Steph Curry&#39;);</pre><pre>console.log(steph.superpower()) // HERO Steph Curry pops treys 🔥🔥🔥</pre><p>In this case the SuperHuman can still call all the methods that were defined in the parent class. For example:</p><pre>console.log(steph.sayHi()) // Hello, Steph Curry</pre><p>Inheritance can be great in the right situation but you want to avoid creating really deeply nested classes because it becomes very hard to debug when things go wrong somewhere in the middle. As an alternative we can use composition and there are actually multiple different ways we can apply this pattern. Another alternative is to concatenate objects together.</p><pre>const hasName = (name) =&gt; {<br>    return { name }<br>}</pre><pre>const canSayHi = (name) =&gt; {<br>    return {<br>        sayHi: () =&gt; `Hello, ${name}`<br>    }<br>}</pre><p>The idea here is that you decouple your properties or behaviors into objects or functions that return objects. We can then merge all these objects together into a final function that does everything that we need it to. This is usually referred to as a mixin patter and it’s just a certain type of multiple inheritance.</p><pre>const Person = function(name) {<br>    return {<br>        ...hasName(name),<br>        ...canSayHi(name)<br>    }<br>}</pre><pre>const person = Person(&#39;Jeff&#39;)<br>console.log(person.sayHi()) // Hello, Jeff</pre><p>This mixin pattern can be very powerful but in its current form we lose all of the ergonomics of class-based object-oriented programming. This might be a good or bad thing depending on who you ask but typescript actually gives us the flexibility to use mixins in a class-based format.</p><pre>class CanSayHi {<br>    name;</pre><pre>    sayHi() {<br>        return `Hello, ${this.name}`;<br>    }<br>}</pre><pre>class HasSuperPower {<br>    heroName;<br>    <br>    superpower() {<br>        return `${this.heroName} 🔥🔥🔥`;<br>    }<br>}</pre><pre>class SuperHero implements CanSayHi, HasSuperPower {<br>    <br>    heroName;</pre><pre>    constructor(public name) {<br>        this.heroName = `SUPER ${name}`;<br>    }<br>   <br>    sayHi: () =&gt; string;<br>    superpower: () =&gt; string;<br>}</pre><p>Here instead of extending the class, we implemented multiple classes. When you implement something you are only concerned about its interface and not its underlying code. It’s the apply mixins function that we defined at the very beginning that will actually take these interfaces and apply their code to this class. Final step is the requirement to call that apply mixins function with the base classes the first argument and the mixed in classes as the second argument.</p><pre>applyMixins(SuperHero, [CanSayHi, HasSuperPower]);</pre><pre>const ts = new SuperHero(&#39;TypeScript&#39;)</pre><pre>console.log(ts.superpower()) // SUPER TypeScript 🔥🔥🔥</pre><p>Now we can finally answer the question!</p><p>What’s your answer?</p><h3>Conclusion</h3><p>It is always up to the programmers or developers to choose the right programming language concept that makes their development productive and easy. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b2243bb8c4b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/object-oriented-vs-functional-programming-with-typescript-6b2243bb8c4b">Object-Oriented vs Functional Programming with Typescript</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Pro Tips]]></title>
            <link>https://blog.devgenius.io/javascript-pro-tips-159029088776?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/159029088776</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 09:15:38 GMT</pubDate>
            <atom:updated>2020-09-27T09:15:38.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FT29kFS90c_arTUmGEMoGQ.png" /></figure><p>In this article, I am going to talk about Javascript Pro Tips. Please learn how to write solid modern Javascript and avoid bad code from the olden days.</p><h3>Debugging</h3><p>Actually it’s about console logging stuff.</p><p>How do you use console log? There are good ways and bad ways to console log. Imagine you have three different objects. Each one assigned to its own variable like this.</p><pre>const foo = { name: &#39;tom&#39;, age: 30, nervous: false } <br>const bar = { name: &#39;dick&#39;, age: 40, nervous: false }<br>const baz = { name: &#39;harry&#39;, age:50, nervous: false }</pre><p>The obvious way to log these is just one after the other.</p><p>For example:</p><pre>console.log(foo);<br>console.log(bar);<br>console.log(baz);</pre><p>But the main problem is we don’t know the name of the variable when this gets logged but there’s a trick we can use here called computed property names where we add the variables to an object.</p><p>So you can do like this:</p><pre>console.log({ foo, bar, baz });</pre><p>This does not only reduce the code footprint but it also tells us exactly which variable define this data. One line of code, one console log and all the information we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*sjvItLYRTGAxgMuPkNKt3w.png" /></figure><p>But maybe this data is extra important so we want to make it stand out with some custom CSS styling. You can substitute data and also CSS styles by using % sign. So we’ll add %c and then have the second argument be our actual CSS style.</p><p>For example:</p><pre>console.log(&#39;%c My Friends&#39;, &#39;color: orange;&#39;)<br>console.log({ foo, bar, baz });</pre><p>Here we go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*qSUF-n5diXSrnUexgU79FA.png" /></figure><p>One thing you might have noticed is that the objects all share common properties so maybe we should display those as a table.</p><pre>console.table([foo, bar, baz]);</pre><p>This is really useful when you have an array of objects. You just do console table with the array.</p><p>If you are benchmarking performance you can actually keep track of time in. the console.</p><pre>console.time(&#39;looper&#39;);</pre><pre>let i = 0;<br>while (i &lt; 1000000) { i ++ }</pre><pre>console.timeEnd(&#39;looper&#39;)</pre><p>Keeping track of time is great but what if you need to know where a console.log originated from.</p><p>Let’s imagine that we have a really important function that deletes items from our database and we want to make sure that we don’t accidentally call this method twice. In this case you can add console trace to your function and it will give you a stack trace for where it was called and what defined it if we run this code, we’ll get a console log that tells us the function was defined on which number of line.</p><p>For example, if we write:</p><pre>const deleteMe = () =&gt; console.trace(&#39;bye bye database&#39;)</pre><p>You can get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*-dX4dKG0dla4QCDu_q9rPA.png" /></figure><h3>Destructuring</h3><p>Here, I am going to show you a few different ways you can make your code as concise and efficient as possible. Let’s imagine we have an object with some animal data and we need a function that will tell us how to feed the animal.</p><p>For example:</p><pre>function feed(animal) {<br>    return `Feed ${animal.name} ${animal.meal} kilos of ${animal.diet}`<br>}</pre><p>This doesn’t look too bad but you’ll notice that we’re repeating the word animal over and over again. There’s a technique called object destructuring that we can use to eliminate most of the repetition here.</p><p>If we have a function that takes an object but we only need to use a handful of its properties. We can destrcture those in the argument itself. We just wrap it in brackets and then pass in the names of the object properties that we want to use.</p><pre>function feed({ name, meal, diet }) {<br>    return `Feed ${name} ${meal} kilos of ${diet}`<br>}</pre><p>So now we can format the same string but we never actually have to use the word animal directly. this might seem like a modest gain on this simple function but when you have a big object with a lot of properties this can make a huge difference.</p><p>If you don’t like this bracket syntax in the object argument, there is actually another way we can do this which is just as good.</p><pre>function feed(animal) {<br>    const { name, meal, diet } = animal;<br>    return `Feed ${name} ${meal} kilos of ${diet}`<br>}</pre><p>Now you can use properties like variables throughout the function and this tends to be the better way to go if you have multiple objects 2d structure and a single function.</p><h3>Template Literals</h3><p>In this part, I am going to talk about template literals which we’ve already been using in the code. But actually there’s more to talk about here.</p><p>For example if we have:</p><pre>const horse = {<br>   name: &#39;Topher&#39;,<br>   size: &#39;large&#39;,<br>   skills: [&#39;jousting&#39;, &#39;racing&#39;],<br>   age: 7<br>}</pre><pre>let bio = horse.name + &#39; is a &#39; + horse.size + &#39; horse skilled in &#39; + horse.skills.join(&#39; &amp; &#39;)</pre><p>You would see a lot of string concatenation that looks like above where you have a variable plus string and you have to manage the spaces in between plus an expression plus a whole bunch of other stuff. This type of code is incredibly annoying to deal with but template literals in modern Javascript solve this problem completely.</p><p>Instead of concatenating values together, we can actually interpolate them directly into the string. You can do this by defining your string with backticks and then use dollar sign brackets and then whatever variable or expression you want inside up there. Like this:</p><pre>const horse = {<br>   name: &#39;Topher&#39;,<br>   size: &#39;large&#39;,<br>   skills: [&#39;jousting&#39;, &#39;racing&#39;],<br>   age: 7<br>}</pre><pre>bio = `${name} is a ${size} skilled in ${skills.join(&#39; &amp; &#39;)}`</pre><p>This will look a lot more readable and a lot easier to maintain.</p><p>But you can actually take things a step further and build strings in a purely functional way. So we’ll write a function here called horse age that takes in array of strings as the first argument and then it can take whatever other arguments that wants after that. Imagine we have this function:</p><pre>function horseAge(str, age) {<br>   const ageStr = age &gt; 5 ? &#39;old&#39; : &#39;young&#39;;<br>   return `${str[0]}${ageStr} at ${age} years`;<br>}</pre><p>But the interesting thing here is that instead of passing a regular argument to this function we can actually just attach it to a template literal and it will parse the arguments in it. For example:</p><pre>const bio2 = horseAge`This horse is ${horse.age}`;</pre><p>Then it will handle all the other arguments in the order in which they appear inside of the dollar sign brackets. In other words you can take a single argument and use it to compose multiple values in the return string. This can be a very powerful concept for templating.</p><h3>Spread Syntax</h3><p>Let’s image we have one object for a Pokemon and the other one for the stats that define its various attributes.</p><pre>const pikachu = { name: &#39;Pikachu&#39; }<br>const stats = { hp: 40, attack: 60, defense: 45 }</pre><p>Let’s say we want to assign the properties from the stats object to the Pikach object. One way to do that is to just redefine them one by one on the original Pikachu object.</p><pre>pikachu[&#39;hp] = stats.hp<br>pikachu[&#39;attack&#39;] = stats.attack<br>pikachu[&#39;defense&#39;] = stats.defense</pre><p>For one, this is just really ugly and verbose but we’re also mutating the original object when we most likely want to create a new immutable object because let’s say that our Pokemon levels up over time, we want to represent each level up as its own object.</p><p>We could use Object.assign() here and take the original object and merge it in with the stats and this will merge them together from left to right.</p><pre>const lv10 = Object.assign(pikachu, stats)<br>const lvl1 = Object.assign(pikachu, { hp: 45 })</pre><p>This isn’t too bad but there’s a more concise way to do this with the spread syntax. By creating a new object and placing our existing objects in it with three dots in front of them. For example:</p><pre>const lvl0 = { ...pikachu, ...stats }<br>const lvl1 = { ...pikachu, hp: 45 }</pre><p>This will compose a new object from left to right. So the property is farthest to the right will have the priority. Again this is mostly just syntactic sugar and it just makes your code more readable and easier to maintain.</p><p>And it’s also possible to use the spread syntax on arrays. Let’s imagine we have an array of strings and we need to push additional items to this array.</p><pre>let pokemon = [&#39;Arbok&#39;, &#39;Raichu&#39;, &#39;Sandshrew&#39;]</pre><p>The old school way to do this would be to just push new items to the array one by one. For example:</p><pre>pokemon.push(&#39;Bulbasaur&#39;)<br>pokemon.push(&#39;Metapod&#39;)<br>pokemon.push(&#39;Weedle&#39;)</pre><p>But in today’s world, we can reduce these three lines of code to just one by defining an array with the new items and in the spread syntax on the original array. Like this:</p><pre>pokemon = [...pokemon, &#39;Bulbasaur&#39;, &#39;Metapod&#39;, &#39;Weedle&#39;]</pre><pre>pokemon = [&#39;Bulbasaur&#39;, ...pokemon, &#39;Metapod&#39;, &#39;Weedle&#39;]</pre><h3>Loops</h3><p>Let’s imagine that we have an array of numbers here that represent the other totals.</p><pre>const orders = [500, 30, 99, 15, 223]</pre><p>Now we need to compute some values based on this array such as the order total. Maybe we need to add some tax to each one and filter out the high value orders to be reviewed by a manager. One option is to just use a classic for loop like you’ll find in pretty much every programming language. For example:</p><pre>const total = 0;<br>const withTax = [];<br>const highValue = [];<br>for(i = 0; i &lt; orders.length; i ++) {</pre><pre>  // Reduce<br>  total += orders[i];</pre><pre>  // Map<br>  withTax.push(orders[i] * 1.1);</pre><pre>  // Filter<br>  if (orders[i] &gt; 100) {<br>    highValue.push(orders[i])<br>  }</pre><pre>}</pre><p>This code is very ugly and it’s mutating values might make our code a little more unpredictable. Luckily we can reduce this down to just three lines of code by using modern Javascript array methods. Like this:</p><pre>// Reduce<br>const total = orders.reduce((acc, cur) =&gt; acc + cur)</pre><pre>// Map<br>const withTax = orders.map(v =&gt; v * 1.1)</pre><pre>// Filter<br>const highValue = orders.filter(v =&gt; v &gt; 100)</pre><h3>async / await</h3><p>Let’s create a method called random that returns a promise that resolves to a random number asynchronously.</p><pre>const random = () =&gt; {<br>  return Promise.resolve(Math.random())<br>}</pre><p>Now we want to retrieve three different asynchronous numbers one after the other and then add them all together at the end. That might seem like a silly example but that’s actually how things work a lot of times in the real world when you have to retrieve one item from the database get some data retrieving another item from an API and so on.</p><p>With promises you wait for an asynchronous value to resolve and then you handle it with a callback function inside of then. For example:</p><pre>const sumRandomAsyncNums = () =&gt; {<br>  let first;<br>  let second;<br>  let third;</pre><pre>return random()<br>       .then(v =&gt; {<br>           first = v;<br>           return random();<br>       })<br>       .then(v =&gt; {<br>           second = v;<br>           return random();<br>       })<br>       .then(v =&gt; {<br>           third = v;<br>           return first + second + third;<br>       })<br>}</pre><p>We can rewrite our promise chain. The only difference is adding async in front of the function which will force it to return a promise. Like this:</p><pre>const sumRandomAsyncNums = async () =&gt; {<br>  <br>    const first = await random();<br>    const second = await random();<br>    const third = await random();</pre><pre>    return first + second + third;<br>}</pre><p>The real benefit here is that we can use a await in front of our promises and have them resolve to an actual variable value. So instead of using those then callbacks we can just say const first = await random(); and do the same thing for the second and third number. Now it’s much easier to read and understand this code because we can just go line by line and see that we’re waiting one number awaiting another number and so on.</p><p>This async/await concept is one of the most awesome things to ever happen to Javascript!</p><p>That’s it for today.</p><p>Thanks for you reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=159029088776" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/javascript-pro-tips-159029088776">Javascript Pro Tips</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Best Practices]]></title>
            <link>https://blog.devgenius.io/typescript-best-practices-e658600e9d9?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e658600e9d9</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[script]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 15:10:43 GMT</pubDate>
            <atom:updated>2020-09-25T15:10:43.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*t3BlGIviD5_Zlq3-jRaDKg.jpeg" /></figure><p>To make code easy to read and maintain, you should follow some best practices.</p><p>In this article, I am going to talk about some best practices you should follow to make everyone’s lives easier.</p><h3>Group Function Overloads Together</h3><p>You can overload functions.</p><p>This means you can have multiple function signatures for a function, which TypeScript can check for.</p><p>To make your lives easier, you should group them together so that it’s easier to read:</p><pre>function foo(a: string, b: string): string;<br><br>function foo(a: number, b: number): number;<br><br>function foo(a: any, b: any): any {<br>  console.log(a, b);<br>}</pre><h3>Ordering Class Members</h3><p>You may consider ordering class members to make the members easier to read.</p><p>You can order them by access modifiers, alphabetical order, etc.</p><p>It’s good to stick with one.</p><p>For example, instead of writing:</p><pre>class Employee {<br>  private id: string;<br>  private empCode: number;<br>  private empName: string;<br>}</pre><p>you write:</p><pre>class Employee {<br>  private empCode: number;<br>  private empName: string;<br>  private id: string;<br>}</pre><p>to sort them by alphabetical order.</p><h3>Don’t Use module Keyword for Namespaces</h3><p>If you declare namespaces, then you should use the namespace keyword.</p><p>Instead of writing:</p><pre>module Math {<br>  function add(a: number, b: number): number {<br>    return a + b;<br>  }<br>}</pre><p>You write:</p><pre>namespace Math {<br>  function add(a: number, b: number): number {<br>    return a + b;<br>  }<br>}</pre><p>This way, you won’t confuse what you have with ES modules.</p><h3>Visibility Declarations for Class Members</h3><p>To take advantage of the access control capabilities of TypeScript, you can add the visibility declarations or class members.</p><p>For example, you write:</p><pre>class Employee {<br>  private getSalary(): number {<br>    return 90000;<br>  }<br>}</pre><p>You added the private access modifier so that getSalary can only be called by other methods in the class.</p><p>There’s also the public modifier to make the member available to outside code.</p><p>protected makes the member available to subclasses and the current class.</p><p>public is the default.</p><p>You can also do the same for instance variables:</p><pre>class Employee {<br>  private empCode: number;<br>}</pre><h3>Eliminate the Use of any Types</h3><p>You can eliminate the use of any types in your code to take advantage of TypeScript’s type-checking capabilities.</p><p>If you need something more flexible than static types, there are many ways to define them.</p><p>You can use literal types to restrict values to only some literals.</p><p>There’re union types to let you check for members for multiple types.</p><p>The intersection type makes sure that the variable has members that are in both types.</p><p>Index signatures let you check for dynamic properties.</p><p>There’re many ways to avoid any.</p><p>For example, instead of writing:</p><pre>let bar: any;</pre><p>you write:</p><pre>let foo: string;</pre><h3>No Empty Interface</h3><p>You shouldn’t have empty interfaces in your code since they’re useless.</p><p>So instead of writing:</p><pre>interface I {}</pre><p>You write:</p><pre>interface I {<br>  bar: number;<br>}</pre><h3>No for-in Loops</h3><p>for-in loops are legacy JavaScript syntax which has better modern alternatives.</p><p>It’s bad since you need to use the hasOwnProperty to check for non-inherited properties with it.</p><p>Better alternatives include Object.keys to get the non-inherited keys of an object.</p><p>Object.values to get the values and Object.entries to get all entries.</p><p>So instead of writing:</p><pre>for (const key in obj) {<br>  if (obj.hasOwnProperty(key)) {<br>    console.log(obj[key]);<br>  }<br>}</pre><p>you write:</p><pre>for (const key in Oject.keys(obj)) {<br>  console.log(obj[key]);<br>}</pre><h3>No Import Side Effects</h3><p>import should be used for import module members and using them.</p><p>If they perform side effects, then it’s not good because it’s hard to statically analyze the code.</p><p>So instead of writing:</p><pre>import &#39;foo&#39;;</pre><p>you write:</p><pre>import { bar } from &#39;foo&#39;;</pre><p>Some exceptions may be importing CSS with Webpack as modules.</p><p>So you may still write:</p><pre>import &#39;styles.css&#39;;</pre><h3>No Explicit Type Declarations for Variable or Parameters with Literal Values</h3><p>It’s redundant to have type declarations for variables or parameters that are assigned with numbers strings or boolean.</p><p>TypeScript can check these without an explicit type.</p><p>Therefore, instead of writing:</p><pre>const foo: number = 10;</pre><p>You write:</p><pre>const foo = 10;</pre><h3>Conclusion</h3><p>Grouping things together make them easier to read.</p><p>Visibility modifiers are a useful TypeScript feature.</p><p>any types can be replaced with many things.</p><p>Use namespace to declare namespace code.</p><p>That’s it for today!</p><p>Thanks for your reading and stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e658600e9d9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/typescript-best-practices-e658600e9d9">TypeScript Best Practices</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Piping and Functors in Javascript]]></title>
            <link>https://blog.devgenius.io/piping-and-functors-in-javascript-f7ca276703c?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7ca276703c</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functor]]></category>
            <category><![CDATA[piping]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 15:09:01 GMT</pubDate>
            <atom:updated>2020-09-25T15:09:01.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvV7YIERDylqMqM48-iqTw.png" /></figure><p>JavaScript is partly a functional language.</p><p>To learn JavaScript, you have to learn the functional parts of JavaScript.</p><p>In this article, I am going to talk about pipe functions and functors with JavaScript.</p><h3>Pipe</h3><p>You can create a pipe function by creating a function that takes an array of functions as arguments.</p><p>It returns a function that takes a value and you call reduce on it with that calls fn with acc.</p><p>For example, you can write:</p><pre>const compose = (...fns) =&gt;<br>  (value) =&gt;<br>  fns.reduceRight((acc, fn) =&gt; fn(acc), value)</pre><p>The only difference is that you used reduceRight instead of reduce so that you don’t need to call reverse to apply all the functions.</p><h3>Composition is Associative</h3><p>Composition is associative, this means you can rearrange the parentheses of your operations</p><p>For example:</p><pre>compose(f, compose(g, h)) == compose(compose(f, g), h)</pre><p>returns true.</p><h3>Functors</h3><p>Functor is a plain object that implements the function map while running River each value to produce a new object.</p><p>A functor is a container that holds some value in it.</p><p>For example, you can write:</p><pre>const Container = function(val) {<br>  this.value = val;<br>}</pre><p>to create your container.</p><p>Then you can use new to invoke the Container constructor:</p><pre>let foo = new Container(3);</pre><p>You can create a Container.of property to add a container to let us return a Container instance:</p><pre>const Container = function(val) {<br>  this.value = val;<br>}</pre><pre>Container.of = function(value) {<br>  return new Container(value);<br>}</pre><p>You added the of static method to return a Container instance.</p><p>The of method just gives you an alternative to using the new operator to create the Container instance.</p><p>Then you can create a Container instance with the of method:</p><pre>const nested = Container.of(Container.of(1));</pre><p>Then you’ll see the nested Container instances.</p><h3>Functor Implements Method Called map</h3><p>Functors implement the map method.</p><p>You can add it as an instance method by adding it to the prototype property:</p><pre>const Container = function(val) {<br>  this.value = val;<br>}</pre><pre>Container.of = function(value) {<br>  return new Container(value);<br>}</pre><pre>Container.prototype.map = function(fn) {<br>  return Container.of(fn(this.value));<br>}</pre><p>Then you can use the map method after you create a Container instance.</p><p>For instance, you can use it by writing:</p><pre>const squared = Container.of(3).map(a =&gt; a ** 2);</pre><p>Then squared is a Container instance with value being 9.</p><p>You can call map repeatedly to repeat an operation.</p><p>Which means you can write:</p><pre>const squared = Container.of(3)<br>  .map(square)<br>  .map(square)<br>  .map(square);</pre><p>Then squared is a Container instance with value being 6561.</p><p>Functor is just an object that implements a map method.</p><h3>Conclusion</h3><p>Functors are plain objects that have value.</p><p>The object has a map method.</p><p>You can pipe functions to call multiple functions and get the returned value.</p><p>Composition is associative, so you can rearrange the parentheses of our operations.</p><p>That’s it for today and thanks for your attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7ca276703c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/piping-and-functors-in-javascript-f7ca276703c">Piping and Functors in Javascript</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Styled Vue Components With vue-styled-components]]></title>
            <link>https://blog.devgenius.io/creating-styled-vue-components-with-vue-styled-components-aa1ebab0684d?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa1ebab0684d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 16:04:22 GMT</pubDate>
            <atom:updated>2020-09-24T16:04:22.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPpes-voAI8rM-GhcZqeQg.jpeg" /></figure><p>To created component with built-in styles with a few lines of code, you can use the vue-styled-components to create them.</p><h3>Getting Started</h3><p>First, install the package by running:</p><pre>npm i vue-styled-components</pre><p>Then you can create some basic components, for example:</p><pre>import styled from &quot;vue-styled-components&quot;;<br><br>export const StyledTitle = styled.h1`<br>  font-size: 1.5em;<br>  text-align: center;<br>  color: palevioletred;<br>`;<br><br>export const StyledHeader = styled.header`<br>  padding: 4em;<br>  background: yellow;<br>`;</pre><p>You just need to import the package then use the template tags that came with the code to create new styled elements.</p><p>You can change the font size, text alignment, and other things with the tags.</p><p>The h1 tag makes an h1 element.</p><p>header makes a styled header element.</p><p>Then you can use it by registering the component and use it:</p><pre>&lt;template&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;styled-header&gt;<br>      &lt;b&gt;header&lt;/b&gt;<br>    &lt;/styled-header&gt;<br>    &lt;styled-title&gt;hello&lt;/styled-title&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import { StyledTitle, StyledHeader } from &quot;./components&quot;;<br><br>export default {<br>  name: &quot;App&quot;,<br>  components: {<br>    &quot;styled-title&quot;: StyledTitle,<br>    &quot;styled-header&quot;: StyledHeader<br>  }<br>};<br>&lt;/script&gt;</pre><p>You just register them in components and reference it in our templates.</p><p>The styles in the string are applied automatically.</p><h3>Props</h3><p>Like any other component, you can pass props to them.</p><p>For example:</p><pre>import styled from &quot;vue-styled-components&quot;;<br><br>export const StyledInput = styled.input`<br>  font-size: 1.25em;<br>  padding: 0.5em;<br>  margin: 0.5em;<br>  color: palevioletred;<br><br>  &amp;:hover {<br>    box-shadow: inset 1px 1px 2px red;<br>  }<br>`;</pre><p>Then you can write:</p><pre>&lt;template&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;styled-input v-model=&quot;val&quot; placeholder=&quot;val&quot;/&gt;<br>    &lt;p&gt;{{val}}&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import { StyledInput } from &quot;./components&quot;;<br><br>export default {<br>  name: &quot;App&quot;,<br>  data() {<br>    return {<br>      val: &quot;&quot;<br>    };<br>  },<br>  components: {<br>    &quot;styled-input&quot;: StyledInput<br>  }<br>};<br>&lt;/script&gt;</pre><p>Whatever you entered is displayed below it.</p><p>This is because it takes the value prop and emits the input event like any other component.</p><p>The styles you specified are also applied.</p><p>The placeholder prop also works and the placeholder is applied.</p><h3>Adapting Based on Props</h3><p>You can change styling based on props that you passed in.</p><p>For example:</p><pre>import styled from &quot;vue-styled-components&quot;;<br><br>const btnProps = { primary: Boolean };<br><br>export const StyledButton = styled(&quot;button&quot;, btnProps)`<br>  font-size: 1em;<br>  border: 2px solid palevioletred;<br>  border-radius: 3px;<br>  background: ${props =&gt; (props.primary ? &quot;green&quot; : &quot;white&quot;)};<br>  color: ${props =&gt; (props.primary ? &quot;white&quot; : &quot;red&quot;)};<br>`;</pre><p>to let your component takes props.</p><p>You can specify the btnProps object to let your StyledButton takes props.</p><p>btnProps specifies the props that our component takes. You specified that your component takes the primary prop.</p><p>Then you can use it by writing:</p><pre>&lt;template&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    &lt;styled-button primary&gt;button&lt;/styled-button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import { StyledButton } from &quot;./components&quot;;<br><br>export default {<br>  name: &quot;App&quot;,<br>  data() {<br>    return {<br>      val: &quot;&quot;<br>    };<br>  },<br>  components: {<br>    &quot;styled-button&quot;: StyledButton<br>  }<br>};<br>&lt;/script&gt;</pre><p>You set the primary prop to true, so you get a green background and white text.</p><h3>Conclusion</h3><p>You can create styled-components with vue-styled-components.</p><p>This package lets you create elements with styles applied to them so you can use them as Vue components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa1ebab0684d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/creating-styled-vue-components-with-vue-styled-components-aa1ebab0684d">Creating Styled Vue Components With vue-styled-components</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling User Interactions with Vue 3]]></title>
            <link>https://blog.devgenius.io/handling-user-interactions-with-vue-3-94cc628bcb5f?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/94cc628bcb5f</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue-3]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 19:10:43 GMT</pubDate>
            <atom:updated>2020-09-23T19:10:43.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0w60FPfqbm5zpRdeDCiOA.jpeg" /></figure><p>Vue 3 is the up and coming version of Vue front end framework.</p><p>It builds on the popularity and ease of use of Vue 2.</p><p>Today we’ll look at how to handle user interactions with Vue 3.</p><h3>Handling User Input</h3><p>The v-model directive lets you bind your input value to a model property.</p><p>For instance, you can write:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;App&lt;/title&gt;<br>    &lt;script src=&quot;https://unpkg.com/vue@next&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;<br>      &lt;input v-model=&quot;name&quot; /&gt;<br>      &lt;p&gt;{{ name }}&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;script&gt;<br>      const app = {<br>        data() {<br>          return {<br>            name: &quot;&quot;<br>          };<br>        }<br>      };<br><br>      Vue.createApp(app).mount(&quot;#app&quot;);<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>You added the name property to the object you return in the data method in app.</p><p>Now you can use the name variable as the value in v-model .</p><p>Also, you added interpolation of the name value to your template.</p><p>Now when you type in something into the input box, you will get the same value displayed below it.</p><p>This is because v-model does the hard work getting the input value, setting it as the value name and vice versa.</p><h3>Conditionals and Loops</h3><p>You can render something conditionally with the v-if directive.</p><p>For instance, you can write:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;App&lt;/title&gt;<br>    &lt;script src=&quot;https://unpkg.com/vue@next&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;<br>      &lt;button v-on:click=&quot;toggle&quot;&gt;toggle&lt;/button&gt;<br>      &lt;p v-if=&quot;seen&quot;&gt;Now you see me&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;script&gt;<br>      const app = {<br>        data() {<br>          return {<br>            seen: true<br>          };<br>        },<br>        methods: {<br>          toggle() {<br>            this.seen = !this.seen;<br>          }<br>        }<br>      };<br><br>      Vue.createApp(app).mount(&quot;#app&quot;);<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>You have the button which calls toggle.</p><p>The toggle method toggles the this.seen state to its opposite value.</p><p>Since you used that with v-if , it’ll render the p element if seen is true and not rendering it if it’s false .</p><p>You can also use it with transition effects.</p><h3>Loops</h3><p>You can display items in an array with the v-for directive.</p><p>For example, you can use it by writing:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;App&lt;/title&gt;<br>    &lt;script src=&quot;https://unpkg.com/vue@next&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;<br>      &lt;ol&gt;<br>        &lt;li v-for=&quot;p in people&quot;&gt;<br>          {{ p.name }}<br>        &lt;/li&gt;<br>      &lt;/ol&gt;<br>    &lt;/div&gt;<br>    &lt;script&gt;<br>      const app = {<br>        data() {<br>          return {<br>            people: [{ name: &quot;mary&quot; }, { name: &quot;jane&quot; }, { name: &quot;bob&quot; }]<br>          };<br>        },<br>        methods: {<br>          toggle() {<br>            this.seen = !this.seen;<br>          }<br>        }<br>      };<br><br>      Vue.createApp(app).mount(&quot;#app&quot;);<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>You have the people array in the data method.</p><p>This is used with the v-for directive to loop through the array and display the items.</p><p>p is the loop variable, you use to display the array items.</p><h3>Components</h3><p>Components let us component multiple parts of a Vue 3 app.</p><p>Each component is a small part of the app.</p><p>You can create components by writing:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;App&lt;/title&gt;<br>    &lt;script src=&quot;https://unpkg.com/vue@next&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;<br>      &lt;Hello /&gt;<br>    &lt;/div&gt;<br>    &lt;script&gt;<br>      const root = {};<br><br>      const app = Vue.createApp(root);<br><br>      app.component(&quot;Hello&quot;, {<br>        template: `&lt;p&gt;Hello&lt;/p&gt;`<br>      });<br><br>      app.mount(&quot;#app&quot;);<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>You have the root object.</p><p>Then you pass in root to Vue.createApp to create your Vue 3 app.</p><p>And then you create your Hello component by calling the app.component method with the component and the component object.</p><p>template has the template content you want to display.</p><p>Then we call mount with the selector string to mount our app to that component.</p><h3>Conclusion</h3><p>You can add Vue components with the app.component method.</p><p>The v-model directive binds input values to variables.</p><p>v-for lets you loop through arrays and render its entries’ data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94cc628bcb5f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/handling-user-interactions-with-vue-3-94cc628bcb5f">Handling User Interactions with Vue 3</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s New In Typescript 4.0?]]></title>
            <link>https://blog.devgenius.io/whats-new-in-typescript-4-0-4a8e2182cea7?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a8e2182cea7</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typescript-4]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 19:58:46 GMT</pubDate>
            <atom:updated>2020-09-22T19:58:46.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*qhejO1lJW4ukEH1Zi_4H9g.jpeg" /></figure><p>Today I am going to talk about new features in Typescript 4.0.</p><p>TypeScript 4.0 comes with lots of new features to make JavaScript development easier.</p><h3>Labeled Tuple Elements</h3><p>You can label tuple elements.</p><p>You can write:</p><pre>type Range = [start: number, end: number];</pre><p>to restrict args to have a string and a number.</p><p>you can also write:</p><pre>type Foo = [first: number, second?: string, ...rest: any[]];</pre><p>to have rest entries in your tuple.</p><p>If your tuple has type Foo, then the tuple starts with a number and a string.</p><p>Then the rest of the entries can be anything.</p><p>Labels don’t require you to name your variables differently when destructuring.</p><p>For example, if you have:</p><pre>function foo(x: [first: string, second: number]) {<br>  const [a, b] = x;<br>}</pre><p>then you can name the destructured variables anything you want.</p><h3>Class Property Inference from Constructors</h3><p>TypeScript 4.0 can infer class properties’ types from the constructor.</p><p>For example, if you have:</p><pre>class Square {<br>  area;<br>  length;<br><br>  constructor(length: number) {<br>    this.length = length;<br>    this.area = length ** 2;<br>  }<br>}</pre><p>then TypeScript 4.0 knows that this.length and this.area are numbers automatically.</p><p>If there’s a chance that the value of them are undefined , then the TypeScript compiler will notify you of that.</p><p>So if you have:</p><pre>class Square {<br>  length;<br><br>  constructor(length: number) {<br>    if (Math.random()) {<br>      this.length = length;<br>    }<br>  }<br><br>  get area() {<br>    return this.length  ** 2;<br>  }<br>}</pre><p>then you’ll know that this.length may be undefined.</p><p>You would need a type assertion even if you know that it’s always defined.</p><p>For example, you can write:</p><pre>class Square {<br>  length!: number;<br><br>  constructor(length: number) {<br>    this.initialize(length);<br>  }<br><br>  initialize(length: number) {<br>    this.length = length;<br>  }<br><br>  get area() {<br>    return this.length ** 2;<br>  }<br>}</pre><p>You set length to be non-null with the ! symbol and set its type explicitly to number to make sure this.length is always a number.</p><h3>Variadic Tuples</h3><p>TypeScript 4.0 comes with data types for tuples with a variable number of elements.</p><p>You can use the spread operator to create a type with the elements you want in your tuple.</p><p>For example, if you write:</p><pre>type Strings = [string, string];<br>type Numbers = number[];<br><br>type Unbounded = [...Strings, ...Numbers, boolean];</pre><p>to create an Unbounded data type to add a tuple type with strings, numbers, and booleans.</p><p>The inference process is also automatic so that if you have 2 strings, numbers, and a boolean in the same order, TypeScript will infer the tuple as having the Unbounded type.</p><h3>unknown on catch Clause Bindings</h3><p>You can specify the binding variable of the catch clause to have an unknown type instead of an any type.</p><p>With the unknown type, you have to cast the exception object explicitly before you can do things with it.</p><p>For example, you can write:</p><pre>try {<br>  // ...<br>} catch (e: unknown) {<br>  if (typeof e === &quot;string&quot;) {<br>    console.log(e.toUpperCase());<br>  }<br>}</pre><p>Then you check if e is a string before you call toUpperCase on it.</p><h3>Short-Circuiting Assignment Operators</h3><p>TypeScript 4.0 has new assignment operator shorthands.</p><p>Now you write the logical AND, logical OR, and bullish coalescing operators with shorthands.</p><p>For example, instead of writing:</p><pre>a = a &amp;&amp; b;<br>a = a || b;<br>a = a ?? b;</pre><p>You can write:</p><pre>a &amp;&amp;= b;<br>a ||= b;<br>a ??= b;</pre><h3>Conclusion</h3><p>TypeScript 4.0 comes with many new features that you can use to check for types.</p><p>Type inference is also improved.</p><p>That’s it for today.</p><p>Thank you for your reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a8e2182cea7" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/whats-new-in-typescript-4-0-4a8e2182cea7">What’s New In Typescript 4.0?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Mistakes You May Be Making]]></title>
            <link>https://blog.devgenius.io/javascript-mistakes-you-may-be-making-b316a0352c37?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b316a0352c37</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Sat, 19 Sep 2020 21:22:53 GMT</pubDate>
            <atom:updated>2020-09-19T21:22:53.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*rE3mUWHSHhZE8GVPVgvzqA.jpeg" /></figure><p>Today I am going to talk about common mistakes you may be making in your Javascript project.</p><p>Javascript is one of the most popular language in the world but it’s still very easy to make mistakes when writing code through misunderstanding or overlooking stuff that we already know.</p><h3><strong>Undefined and Null</strong></h3><p>Javascript has both undefined and null for non-values. However, there are quite a few differences between the two. undefined means that the variable may have been declared, but nothing is set to it. A variable can also be explicitly set as undefined. The type of an undefined variable, when checking the type with the typeof operator, will show you the type undefined. Functions that don’t return anything returns undefined. On the other hand, null values have to be explicitly set by functions that return null or just set directly to a variable. When you check an object that has the null value set, you will see that the type of it is object if a variable has the null value.</p><p>For this reason, it will be easier to stick to undefined whenever you can when you’re setting variable values to non-values. It reduces confusion and we only have to check that the type of a variable is undefined to see whether it’s undefined. It’s less painful than having two checks, for both null and undefined.</p><p>To write functions that return undefined, you don’t have to do anything like this:</p><pre>const f = () =&gt; {}</pre><p>To set a variable that was assigned some other value to undefined:</p><pre>x = undefined;</pre><p>To check if a property value is undefined:</p><pre>typeof obj.prop === &#39;undefined&#39;</pre><p>or</p><pre>obj.prop === undefined</pre><p>To check if a variable is undefined:</p><pre>typeof x === &#39;undefined&#39;</pre><p>A declared variable that hasn’t been assigned anything automatically has the value undefined.</p><p>If you need to check null:</p><pre>obj.prop === null</pre><p>or</p><pre>x === null</pre><p>for variables. You cannot use the typeof operator for checking null because the data type of null is object.</p><h3>Addition and Concatenation</h3><p>In Javascript, the + operator is used for both adding two numbers and concatenating strings together. Because Javascript is a dynamic language, so the operands will be automatically converted to the same type before the operation will be applied. For example:</p><pre>let x = 1 + 1;</pre><p>then you get 2 because they both have same type. The + operation was used for addition as you expected. However, if you have the following expression:</p><pre>let x = 1 + &#39;1&#39;;</pre><p>then you will get &#39;11&#39; because the first operand will be coerced into a string before the + operation will be applied. The +operation will be used for concatenation instead of addition. When you use the + operator on multiple variables, this makes knowing the type even harder. In this case:</p><pre>let x = 1;  <br>let y = 2;  <br>let z = x + y;</pre><p>you will get 3 because x and y are both numbers.</p><p>Instead, if we have:</p><pre>let x = 1;  <br>let y = &#39;2&#39;;  <br>let z = x + y;</pre><p>then you will get &#39;12&#39; because y is string, so the + operator will be used for concatenation instead. For solving this problem, we should convert all the operands to numbers before using. Which means we should rewrite the above code into the following:</p><pre>let x = 1;  <br>let y = &#39;2&#39;;  <br>let z = Number(x) + Number(y);</pre><p>This variable z will have 3 since we converted both operands to numbers with Number factory function. The Number function takes in any object and returns a number if it can be parsed into a number, or NaN otherwise. An alternative way to do this is to use the new Number(...).valueof() function, like this:</p><pre>let x = 1;  <br>let y = &#39;2&#39;;  <br>let z = new Number(x).valueOf() + new Number(y).valueOf();</pre><p>Since new Number(...)is constructor that creates an object type, you want to use the the valueof function to convert it back to a primitive type to make sure that what we get is a number type. A simple way to do this is:</p><pre>let x = 1;  <br>let y = &#39;2&#39;;  <br>let z = +x + +y;</pre><p>The + sign in front of a single operand will try to convert the single operand into a number or toNaN if it can’t be converted into a number. It does the same thing as the Number function. You also can convert a variable to a particular type of number. The Number object has a parseInt function to convert a string or object into an integer and a parseFloat function to convert a string or object into a floating-point number. parseInt takes the object you want to convert to a number as the first argument. It also takes a radix as an optional second argument, which is the base of the mathematical numeral systems. If the string starts with 0x, then the radix will be set to 16. If the string starts with anything else, then the radix will be set to 10.</p><p>You can use them like this:</p><pre>let x = 1;  <br>let y = &#39;2&#39;;  <br>let z = Number.parseInt(x) + Number.parseInt(y)</pre><p>Also you can use parseFloat instead of parseInt as following:</p><pre>let x = 1;  <br>let y = &#39;2&#39;;  <br>let z = Number.parseFloat(x) + Number.parseFloat(y)</pre><h3>Return Statements Into Multiple Lines</h3><p>JavaScript closes a statement at the end, so one line code is considered distinct from the other. For example, if you have:</p><pre>const add = (a, b) =&gt; {  <br>  return  <br>  a + b;  <br>}</pre><p>You will get undefined if you run console.log(add(1, 2)); since you ran the return statement, which ended the function execution, before a + b is run. Therefore, a + b will never be run in this function. To fix this, you either have to put the return statement all in one line or use parentheses to surround what you want to return. For example:</p><pre>const add = (a, b) =&gt; {  <br>  return a + b;  <br>}</pre><p>This will log 3 if you run console.log(add(1, 2)); since you are actually returning the computed result in the function. You can also write:</p><pre>const add = (a, b) =&gt; {  <br>  return (  <br>    a + b  <br>  );  <br>}</pre><p>This is handy for returning expressions that might be longer than one line. This will also log 3 if we run console.log(add(1, 2));. For arrow functions, you can also write:</p><pre>const add = (a, b) =&gt; (a + b)</pre><p>to get the same result. This also works for single-line arrow functions.</p><p>In JavaScript, if a statement is incomplete, like the first line of:</p><pre>const power = (a) =&gt; {  <br>  const  <br>    power = 10;  <br>  return a ** 10;  <br>}</pre><p>inside the function then the JavaScript interpreter will run the first line together with the second line to get the full statement. So:</p><pre>const  <br>  power = 10;</pre><p>However, for complete statements like return statements, the JavaScript interpreter will treat them as separate lines. So:</p><pre>return   <br>  a ** 10;</pre><p>is not the same as:</p><pre>return a ** 10;</pre><h3>Conclusion</h3><p>Even though JavaScript is a friendly language, it’s still very easy to make mistakes when writing JavaScript code. It’s easy to confuse undefined and null when you aren’t familiar with JavaScript. Because of the dynamic typing nature of JavaScript, operators like the + operator that can do multiple things can easily be converted to a type we don’t expect and produce the wrong result. Also, if statements can be complete on their own, then they shouldn’t be written in their own lines if you want both lines to be together.</p><p>That’s it for today.</p><p>Thanks for your attention and stay tuned.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b316a0352c37" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/javascript-mistakes-you-may-be-making-b316a0352c37">Javascript Mistakes You May Be Making</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Developer Tooling]]></title>
            <link>https://blog.devgenius.io/react-developer-tooling-6ee4efae9b2a?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ee4efae9b2a</guid>
            <category><![CDATA[react-tool]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-development]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 18:58:50 GMT</pubDate>
            <atom:updated>2020-09-15T18:58:50.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mf6hodU_tDPNYWSvVueVCw.jpeg" /></figure><p><strong>Today I am going to talk about developer tooling to improve these 3 areas.</strong></p><ul><li>Write code quickly</li><li>Debug code effectively</li><li>Update code easily</li></ul><h3>1. Fast Refresh (write code quickly)</h3><blockquote>Fast refresh makes your React app reloads slick and painless on code changes and Re-renders only the required React components if a code change is made instead of reloading the entire app.</blockquote><p><strong>Is it the same as <em>hot reloading</em>?</strong></p><p>The answer is NO. The hot reloading has some limitations.</p><ul><li>No function component support (React hook)</li><li>No error recovery</li><li>Often did not reload after changes</li><li>Required brittle code transforms</li></ul><p><strong>How is <em>Fast Refresh</em> different?</strong></p><ul><li>First class feature for React core team</li><li>Built for all renderers</li><li>Supports function components and Hooks</li><li>Recovers after errors</li></ul><p><strong>How does <em>Fast Refresh</em> work?</strong></p><ul><li>Decides when to ‘update’ or ‘remount’</li><li>Computes a component ‘signature’</li></ul><p><strong>What are limitations of <em>Fast Refresh</em>?</strong></p><ul><li>Resets class component state</li><li>Mixed React and non-React exports</li><li>Memoization</li></ul><p><strong>When can you use <em>Fast Refresh</em>?</strong></p><ul><li>React Native v61+</li><li>React DOM (soon)</li></ul><h3><strong>2. Developer Tools (d</strong>ebug code effectively)</h3><p><strong>Why rewrite React <em>DevTools</em>?</strong></p><ul><li>Better performance</li><li>Support new APIs</li><li>Add new UX features</li></ul><p><strong>What can you do with <em>React DevTools</em>?</strong></p><ul><li>Navigate Unfamiliar Projects</li><li>Iterate and Test</li><li>Profile and Measure Performance</li></ul><h3><strong>3. Codemods (u</strong>pdate code easily)</h3><p><strong>What is a <em>codemod</em>?</strong></p><ul><li>Tool for refactoring large codebase</li><li>Like a really smart field find-and-replace</li></ul><p><strong>How do <em>codemods</em> work?</strong></p><p>It starts by reading Javascript source code from the file. The source code is parsed and converted into an abstract syntax tree or AST for short.</p><p>An AST is a tree representation of the structure of a program.</p><p>Each node in the tree corresponds to an element in the source code.</p><p>The codemod itself is a small Javascript program that modifies this tree. And it can do more complicated edits than find and replace code.</p><p><strong>What are <em>codemods</em> good for?</strong></p><ul><li>Renaming things</li><li>Reordering things</li><li>Replacing things(under certain conditions)</li></ul><p><strong>What are <em>codemods</em> not good for?</strong></p><ul><li>Complex behavioral changes</li><li>Fixing bugs</li></ul><p>Check React codemods <a href="https://github.com/reactjs/react-codemod"><em>here</em></a>!</p><p>And you can also check the <a href="https://bit.ly/2N03WPP">Demo</a>!</p><p>That’s it for today.</p><p>Stay tuned! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ee4efae9b2a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/react-developer-tooling-6ee4efae9b2a">React Developer Tooling</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python vs Javascript]]></title>
            <link>https://blog.devgenius.io/python-vs-javascript-4c2a03fe8a17?source=rss-ea5aea48d7eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2a03fe8a17</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jimmy Jiang]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 07:15:30 GMT</pubDate>
            <atom:updated>2020-07-13T15:21:00.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*j42blhC6_tCaDU76JZ1kaQ.jpeg" /></figure><p>If you’re serious about <a href="https://realpython.com/learning-paths/become-python-web-developer/"><strong>web development</strong></a>, then you’ll need to learn about <strong>JavaScript</strong> at some point. Year after year, numerous <a href="https://insights.stackoverflow.com/survey">surveys</a> have shown that JavaScript is one of the most <a href="https://octoverse.github.com/#top-languages">popular programming languages</a> in the world, with a large and growing community of developers. Just like Python, modern JavaScript can be used almost anywhere, including the front end, back end, desktop, mobile, and the <a href="https://en.wikipedia.org/wiki/Internet_of_things">Internet of Things</a> (IoT). Sometimes it might not be an obvious choice between Python vs JavaScript.</p><p>If you’ve never used JavaScript before or have felt overwhelmed by the quick pace of its evolution in recent years, then this article will set you on the right path.</p><h3>What is JavaScript?</h3><p>Many people, notably some IT recruiters, believe that JavaScript and <strong>Java</strong> are the same language. It’s hard to blame them, though, because inventing such a familiar-sounding name was a marketing trick.</p><p>JavaScript was originally called <strong>Mocha</strong> before it was renamed to <strong>LiveScript</strong> and finally rebranded as <strong>JavaScript</strong> shortly before its release. To add to the confusion, Microsoft developed its own version of the language, which it called <strong>JScript</strong> due to a lack of licensing rights, for use with Internet Explorer 3.0. Today, people often refer to JavaScript as <strong>JS</strong>.</p><p>While Java and JavaScript share a few similarities in their <strong>C-like syntax</strong> as well as in their standard libraries, they’re used for different purposes. Java diverged from the client side into a more general-purpose language. JavaScript, despite its simplicity, was sufficient for validating HTML forms and adding little animations.</p><p>There have been — and continue to be — many attempts to replace or supplant JavaScript with other technologies, including:</p><ul><li><strong>Rich Internet Applications:</strong> Flash, Silverlight, JavaFX</li><li><strong>Transpilers:</strong> Haxe, Google Web Toolkit, pyjs</li><li><strong>JavaScript dialects:</strong> CoffeeScript, TypeScript</li></ul><p>These attempts were driven not only by personal preference but also by web browsers’ limitations before <strong>HTML5</strong> came onto the scene. In those days, you couldn’t use JavaScript for computationally intensive tasks such as drawing vector graphics or processing audio.</p><p>To write Python code for the browser, you can use one of the available transpilers, such as <a href="https://www.transcrypt.org/">Transcrypt</a> or <a href="http://pyjs.org/">pyjs</a>. The latter is a port of Google Web Toolkit (GWT), which was a wildly popular Java-to-JavaScript transpiler. Another option is to use a tool like <a href="https://brython.info/">Brython</a>, which runs a streamlined version of the Python interpreter in pure JavaScript. However, the benefits might be offset by poor performance and lack of compatibility.</p><p>One glaring exception is Microsoft’s <a href="https://www.typescriptlang.org/">TypeScript</a>, which has gained much popularity in recent years. It’s a fully compatible superset of JavaScript that adds optional <strong>static type checking</strong>. If that sounds familiar to you, that’s because Python’s type hinting was inspired by TypeScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ZrAuNeoqAL2FO82qnPTvA.png" /><figcaption>Search Interest in TypeScript from Google Trends</figcaption></figure><p>While modern JavaScript is mature and actively developed, transpiling is still a common approach to ensure backward compatibility with older browsers. Even if you’re not using TypeScript, which seems to be the language of choice for many new projects, you’re still going to need to transpile your shiny new JavaScript into an older version of the language. Otherwise, you run the risk of getting a <strong>runtime error</strong>.</p><p>It seems that, after all these years, JavaScript isn’t going away anytime soon.</p><h3>What is Python?</h3><p>Python was created by Guido van Rossum, and released in 1991.</p><p>Python is used for:</p><ul><li>web development (server-side),</li><li>software development,</li><li>mathematics,</li><li>system scripting.</li></ul><p>Python is often described as a “glue language,” meaning it can let disparate code (typically libraries with C language interfaces) interoperate. Its use in data science and machine learning is in this vein, but that’s just one incarnation of the general idea. If you have applications or program domains that you would like to hitch up, but cannot talk to each other directly, you can use Python to connect them.</p><p>Startup companies need to run lean to survive, and that means when they are building their digital products (whether those are websites, mobile apps, or software programs) those products need to be completed under budget and ahead of schedule. Because of its ability to help deliver on both these goals, <a href="https://www.freecodecamp.org/news/why-i-think-python-is-the-best-programming-language-for-startups-9c8f7d748b3e/">Python is a favored programming language in the startup world.</a></p><p>Python’s efficiency and ease of use mean less development time, a streamlined QA and debugging process, and an overall greater return on investment than harder to navigate coding alternatives. Startups are a great place to land a first job and start gaining industry experience, and knowing your way around Python will make you that much more of an attractive hire.</p><p>For as powerful and versatile a language as Python is, you might think it takes years to learn Python. Not so! <a href="https://medium.com/@meenakshi052003/how-many-days-will-it-take-to-master-python-programming-503f26ac3140">Industry professionals say</a> that Python basics (things like Python’s syntax, keywords, and data types) can be learned in as little as 6–8 weeks if you have previous experience with coding languages.</p><p>Learning Python code does more than future-proof you for internet development — it will prepare you for the future of tech jobs, PERIOD.</p><p>Why? Because Python is used for more than “just” traditional development. In fact, Python is a top language for emerging data science fields, including:</p><ul><li><a href="http://www.data-analysis-in-python.org/">Data Analysis</a></li><li><a href="https://djangostars.com/blog/why-python-is-good-for-artificial-intelligence-and-machine-learning/">Artificial Intelligence</a></li><li><a href="https://realpython.com/tutorials/machine-learning/">Machine Learning</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPcPalwDksBCN6TPGFgMbQ.png" /><figcaption>Search Interest in Python from Google Trends</figcaption></figure><p>Does this make sense? Now let’s compare!</p><h3>JavaScript vs Python</h3><h4>Use Cases</h4><p>Python is a <strong>general-purpose</strong>, multi-paradigm, high-level, cross-platform, interpreted programming language with a rich standard library and an approachable syntax.</p><p>As such, it’s used across a wide range of disciplines, including computer science education, scripting and automation, prototyping, <a href="https://realpython.com/python-testing/">s</a>oftware testing, <a href="https://realpython.com/learning-paths/become-python-web-developer/">w</a>eb development, programming embedded devices, and scientific computing. Although it’s doable, you probably wouldn’t choose Python as the primary technology for video game or mobile app development.</p><p>JavaScript, on the other hand, originated solely as a <strong>client-side</strong> scripting language for making HTML documents a little more interactive. It’s intentionally simple and has a singular focus: adding behavior to user interfaces. This is still true today despite its improved capabilities. With Javascript, you can build not only web applications but also desktop programs and mobile apps. Tailor-made runtime environments let you execute JavaScript on the server or even on IoT devices.</p><h4>Philosophy</h4><p>Python emphasizes code <strong>readability</strong> and <strong>maintainability</strong> at the price of its expressiveness. After all, you can’t even format your code too much without breaking it. You also won’t find esoteric operators like you would in C++ or Perl since most of the Python <a href="https://realpython.com/python-operators-expressions/">o</a>perators are English words. Some people joke that Python is executable pseudocode thanks to its straightforward syntax.</p><p>As you’ll find out later, JavaScript offers much more <strong>flexibility</strong> but also more ways to cause trouble. For example, there’s no one right way of creating custom data types in JavaScript. Besides, the language needs to remain backward compatible with older browsers even when new syntax fixes a problem.</p><h4>Runtime</h4><p>To run a Python program, you first need to download, install, and possibly configure its <strong>interpreter</strong> for your platform. Some operating systems provide an interpreter out of the box, but it may not be the version that you’re looking to use. There are alternative Python implementations, including <a href="https://realpython.com/cpython-source-code-guide/">CPython</a>, <a href="https://www.pypy.org/">PyPy</a>, <a href="https://www.jython.org/">Jython</a>, <a href="https://ironpython.net/">IronPython</a>, or <a href="https://github.com/stackless-dev/stackless/wiki">Stackless Python</a>. You can also choose from multiple Python <strong>distributions</strong>, such as <a href="https://www.anaconda.com/">Anaconda</a>, that come with preinstalled third-party packages.</p><p>JavaScript is different. There’s no stand-alone program to download. Instead, every major web browser ships with some kind of <strong>JavaScript engine</strong> and an API, which together make the runtime environment. In the previous section, you learned about Node.js, which allows for running JavaScript code outside of the browser. You also know about the possibility to embed JavaScript in other programming languages.</p><h4>Memory Model</h4><p>Both languages take advantage of automatic heap memory management to eliminate human error and to reduce cognitive load. Nevertheless, this doesn’t completely free you from the risk of getting a <strong>memory leak</strong>, and it adds some performance overhead.</p><p>The orthodox CPython implementation uses <strong>reference counting</strong> as well as non-deterministic <strong>garbage collection</strong> (GC) to deal with reference cycles. Occasionally, you may be forced to manually allocate and reclaim the memory when you venture into writing a custom C extension module.</p><p>In JavaScript, the actual implementation of memory management is also left to your particular engine and version since it’s not a part of the language specification. The basic strategy for garbage collection is usually the <strong>mark-and-sweep</strong> algorithm, but various optimization techniques exist.</p><p>For example, the heap can be organized into generations that separate short-lived objects from long-lived ones. Garbage collection can run concurrently to offload the main thread of execution. Taking an incremental approach can help avoid bringing the program to a complete stop while the memory is cleaned up.</p><h3>Conclusion</h3><p>If you’re JUST learning a language, then there is none better than Python. It’s an easy language to pick up. It’s well documented. It’s associated with a large, active, and friendly community. Since it’s a scripting language, you can easily try stuff out and immediately see the results. You can also build up from programming basics, starting by learning functions and then moving into classes.</p><p>BUT JavaScript has become a vital need for web development in 2017.</p><p>Which one is better? Which one will you choose?</p><p>It depends on your choice!</p><p>Thanks for your attention and stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2a03fe8a17" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/python-vs-javascript-4c2a03fe8a17">Python vs Javascript</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>