<?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 Marcus Osterberg on Medium]]></title>
        <description><![CDATA[Stories by Marcus Osterberg on Medium]]></description>
        <link>https://medium.com/@Osterberg?source=rss-8f34ae37cef5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K66e0deRLmMOw22YvIy9ew.jpeg</url>
            <title>Stories by Marcus Osterberg on Medium</title>
            <link>https://medium.com/@Osterberg?source=rss-8f34ae37cef5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:17:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Osterberg/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[Guide To Hire A React Developer]]></title>
            <link>https://medium.com/@Osterberg/guide-to-hire-a-react-developer-170b19f320f6?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/170b19f320f6</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[recruiting]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 14:37:34 GMT</pubDate>
            <atom:updated>2020-09-18T14:37:34.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohhwUz3Zh9pRBvWEEXJiiw.jpeg" /></figure><p>Finding the right developer for a specific job can be time consuming and expensive. Managing code assignments and asking the right questions is difficult. This is my guide on how to to asses the technical skills of a candidate.</p><p>After using different formats and services I narrowed it down to two essential steps. <strong>Technical interview</strong> followed by a take home <strong>code assignment. </strong>What I’ve learn is to focus on React specific topics. You can check surrounding web technology skills e.g. HTML and CSS while reviewing the code.</p><p>Use the checklist below during technical interview or when evaluating candidates code assignments 👨‍💻👩🏻‍💻📝</p><h4>What to ask</h4><p><em>React has a large API surface and many concepts due to years of iterations. Depending on the roll and experience of the candidate the questions may vary, the questions are designed to be conversation starters.</em></p><p><strong>foundation:</strong></p><ul><li>What’s the difference between a <a href="https://reactjs.org/docs/components-and-props.html#function-and-class-components"><em>class component </em>and <em>functional component</em></a><em> </em>and when to use one over another?</li><li>How is <a href="https://reactjs.org/docs/composition-vs-inheritance.html"><em>composition</em> of components achieved and what is <em>children</em></a>?</li><li>Why does a component <a href="https://medium.com/@Osterberg/react-component-renders-too-often-2917daabcf5">re-render</a> and how do you <a href="https://reactjs.org/docs/conditional-rendering.html#preventing-component-from-rendering">prevent</a> it?</li><li>What does <a href="https://reactjs.org/docs/state-and-lifecycle.html#the-data-flows-down"><em>unidirectional data flow</em></a> mean in React? How is it different from two-way data binding found in other UI libraries or frontend frameworks?</li><li>Give an example of component <a href="https://reactpatterns.com/">design patterns</a>? e.g. <em>HOC, Render prop, or Function as children</em></li></ul><p><strong>API:</strong></p><ul><li>What is <a href="https://reactjs.org/docs/state-and-lifecycle.html"><em>state</em></a> and how to/not trigger a state change?</li><li>Explain the concept of <a href="https://reactjs.org/docs/reconciliation.html"><em>reconciliation</em></a> e.g when to/not use a list index vs unique value as <em>key prop</em> when rendering a <a href="https://reactjs.org/docs/lists-and-keys.html#keys">list of items</a>?</li><li>When to use <a href="https://reactjs.org/docs/context.html"><em>context</em></a><em> and does it have performance drawbacks?</em></li><li>Why is <a href="https://reactjs.org/docs/hooks-reference.html#basic-hooks"><em>hooks</em></a> a big thing in React (and for the frontend community)?</li><li>What’s the purpose of <a href="https://reactjs.org/docs/hooks-reference.html#useeffect"><em>useEffect</em></a><em> </em>and how does it work<em>?</em></li></ul><p><strong>application:</strong></p><ul><li>How to structure and bundle a React project using <a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app"><em>create-react-app</em></a><em> </em>vs JavaScript bundler e.g. <a href="https://webpack.js.org/"><em>webpack</em></a><em> </em>or<em> </em><a href="https://parceljs.org/"><em>parcel</em></a></li><li>How to do <a href="https://reactjs.org/docs/code-splitting.html#code-splitting"><em>code splitting</em></a> or <a href="https://reactjs.org/docs/code-splitting.html#reactlazy"><em>lazy load</em></a><em> </em>components?</li><li>Handling of errors and <a href="https://reactjs.org/docs/error-boundaries.html">exceptions</a>?</li><li><a href="https://reactrouter.com/web/guides/quick-start">Routing</a> solutions?</li><li>How to manage and display user feedback on <a href="https://reactjs.org/docs/react-api.html#reactsuspense">data loading/fetching</a></li><li><a href="https://reactjs.org/docs/optimizing-performance.html#profiling-components-with-the-chrome-performance-tab">Performance profiling</a> e.g. how and what to benchmark in a React application?</li><li>Application security e.g. preventing XSS attacks when working with <a href="https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml">innerHTML</a></li><li>Experience with <a href="https://reactjs.org/docs/testing.html#tools">testing</a>? e.g. unit, integration, and automated E2E tests.</li><li><a href="https://storybook.js.org/">How to document components and patterns</a>?</li></ul><p><strong>Out of curiosity:</strong></p><ul><li>How does React compare to other libraries or frameworks?</li><li>Example of design patterns for managing side effects and business logic in a large React application?</li><li>Experience rendering UI with React on other platforms/environments? e.g. server side rendering or React Native</li><li>What’s going on in the community and what new features are you looking forward to?</li><li>Have you contributed to the React open-source project?</li></ul><h4>What to avoid</h4><p>Topics that I try not to focus on:</p><ul><li><a href="https://redux.js.org/">Redux</a> since you don’t need to know it when building React applications (yet it’s an industry standard and therefor recommended to know)</li><li><a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a> since I’m assuming that the developer knows most of it already if they have experience in writing modern React applications</li><li><a href="https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class"><em>Lifecycles method</em></a> of class components. Function components and the hooks API is the future of React application development</li><li><a href="https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom">VDOM</a> I don’t think it matters on how you build React applications if you know the technical implementation details of the virtual DOM</li></ul><h4>Code assignments</h4><p>I’m a big fan of <a href="https://codesubmit.io/library/react">CodeSubmit</a> when it comes to managing code assignments. You can choose between different applications for the candidate to build. The code review happens on the same platform with full transparency. This makes it easy to communicate and follow the process.</p><p><strong>I hope you will feel more confident recruiting your next React developer.</strong></p><p>I would be happy to answer questions or to discuss any of the topics mentioned here. Drop a comment below or find me on <a href="https://twitter.com/osterbergmarcus">twitter</a>. 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=170b19f320f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Native vs React Native — The Similarities And Differences]]></title>
            <link>https://medium.com/@Osterberg/native-vs-react-native-8854abbee0b5?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8854abbee0b5</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Wed, 05 Feb 2020 23:34:34 GMT</pubDate>
            <atom:updated>2020-02-06T09:10:00.094Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/8854abbee0b5?source=post_stats_page---------------------------">Native vs React Native — The Similarities And Differences</a></h3><p><em>I gave a talk at </em><a href="https://youtu.be/eor_4s2iZnU"><em>code.talks</em></a><em> about building mobile applications with JavaScript.<br>Here are some of the slides from my talk.</em></p><p>Should I build a native app or use cross platform frameworks? There is no absolute answer to this question. The thing is that native development is fun and I personally prefer languages like <a href="https://developer.apple.com/swift/"><em>Swift</em></a><em> </em>over JavaScript. The idea of writing my application once and being able to distribute it cross platform is still more interesting to me. I hope and bet that we will see web<em> </em>and mobile becoming unified in the future.</p><h4>What is React Native</h4><p>React Native is an open-source mobile application framework created by <a href="https://www.facebook.com/">Facebook</a>. It enables developers to write native mobile applications using JavaScript or TypeScript. Facebook is using the technology for products like <a href="https://www.instagram.com/">Instagram</a>, <a href="https://www.facebook.com/marketplace/">Facebook Marketplace</a> and <a href="https://www.facebook.com/business/">Facebook Ads Manager</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKJ965bOS8IHfllHaEANSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2v6McW5FCqgnqgoYh1Dig.png" /></figure><p>It’s a common misconception that React Native compiles JavaScript to native code. What it does is to provide a bridge abstraction for communication between JavaScript and native side. The native side consists of platform APIs, native core modules and custom modules.</p><p>JavaScript code executes on the <strong>JS thread</strong> and UI is being computed on the <strong>Main thread</strong>. This keeps the UI responsive to user interactions even when JavaScript is busy(most of the time). In extreme cases the Main thread could be occupied serializing the payload on the bridge. If the payload is large or has too high of a frequency then the UI can start to stutter.</p><p>There is an ongoing re-architecting of React Native known as <a href="https://github.com/react-native-community/discussions-and-proposals/issues/4">Fabric</a>. The new architecture will bring new features and performance improvements e.g.</p><ul><li>Expose native objects to the JavaScript runtime using JSI instead of passing JSON data over the bridge</li><li>Fabric will allow user side effects e.g. touch events to be synchronous instead of asynchronous for faster response time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FD5PH9Ucb-dwa5JLktG1xw.png" /></figure><p>The native side is exposed using the bridge interface that sends and receives JSON data. Here we are creating two UI elements. The invocation of these two components will send a message over the bridge to the native side.</p><p>The payload of the message contains a <em>type 1</em> that indicates if the message are sent from JavaScript or <em>type 0</em> if the message are sent from native. <em>UIManager</em> is the native module that is is responsible for creating and managing UI, the result of these requests will be to create the corresponding native element on the targeted platform e.g. <em>UIView/UIText </em>on iOS.</p><h4>Product Development Experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*op6iLQblcOCtl8IHXUCEsw.png" /></figure><p>React Native targets both <em>Android</em> and <em>iOS</em> with one single codebase.</p><p>This allows teams to:</p><ul><li>Cut down on developer costs and time by building for both platforms simultaneously</li><li>Increase consistency of the look and feel of UI</li><li>Sync releases of new features for both platforms</li></ul><p>Product owners will thank you for not having to navigate between engineering departments(depending on how your organization is setup).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6F96HLo2HKG9FogruanMw.png" /></figure><p>When you don’t have the need of native developers you can start bridging the gap between web and mobile. Sharing knowledge between web and mobile becomes easier. Leverage your organisations resources instead of hiring new engineers. I’ve seen engineers coming from a web background getting up to speed with React Native within a couple of days.</p><p>Since the cost of context switching between web and mobile becomes lower, you can start to build cross-functional teams where engineering and product are responsible for both web and mobile applications.</p><p>I would like to add that sharing code between web and mobile is also possible. I generally recommend to not share the UI part of the application since web and mobile have different primitives. I would rather focus on sharing the business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY3Dd8fuudaP-bVWQvXUiw.png" /></figure><p>The React Native eco system is mature. Combining the largest package repositories in the industry. Use popular JavaScript State management libraries or test runners of your choice like in any other React project. It’s a high chance that the UI your are indenting to build already exist as a component.</p><p>Many <a href="https://www.npmjs.com/">NPM</a> libraries are anyways wrappers around native packages from <a href="https://cocoapods.org/">CocoaPods</a> or <a href="https://gradle.org/">Gradle</a>. If you don’t find what you are looking for and have some previous native developer experience. Then you can expose your own custom native module and wrap the library that you want to use. I’ve had to bridge two native module so far during my three years of experience using React Native.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyxTW0bHhGCFCYBBuTPx7g.png" /></figure><p>With over 2k+ contributors the community is active and on top of issue handling. The project follows a monthly release cycle. Lately certain packages where moved out of the core of React native. This enables smaller initial bundle app size and invites the community to lead future improvements of core features.</p><p>The popularity of React Native is increasing. The fact that Facebook is dogfooding their own product makes us engineers have to worry less about future stabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34efrzar35U9kXolh9nHjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUKe8hYerihQCqGeNFb0oA.gif" /></figure><p>When developing you will have to initially compile your project to launch the app. If you have native changes you will have to recompile. Most of the time you will be developing on the JavaScript side and any changes will immediately be reflected. Instant feedback is a huge time saver that lets your developers iterate fast on building UI.</p><p>There is tricks to speed up development when building native apps. On iOS you can prototype your UI in <em>storyboard</em> for instant feedback or use the <a href="https://developer.apple.com/xcode/swiftui/">SwiftUI </a>live preview feature. Still you will be re-compiling way more often when doing native development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZXkcbZ0OQgpiJnjDTSPAQ.png" /></figure><p>The React Native framework has a very low file size out of the box(depending on configurations). Because the framework is lightweight it can <a href="https://facebook.github.io/react-native/docs/integration-with-existing-apps">integrate</a> with existing native application. One example would be to have “feature A” native and “feature B” as React Native.</p><p>To launch React Native from a native app is straight forward, you need to provide two things</p><ul><li>Define the location for your JavaScript bundle(when developing locally, the JavaScript bundle is served on a localhost and on production the bundle is stored on the filesystem)</li><li>Render the React Native application in a <em>view</em> element. For iOS instantiate the <em>RCTRootView</em> <em>class</em> and assign the instance to the view of your view controller. On Android create an activity that extends from the <em>ReactActivity class</em> and then you can launch that activity as a new intent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUNBRfwGuEDCZkGn6cFHXQ.png" /></figure><p>Releasing new versions of your app can be frustrating. You need to wait for the app to be approved and released onto the store(especially true for iOS) and then you need to wait for users to actually update to the latest version.</p><p>Wire updates is a great feature and lets your team move fast. Since JavaScript can be served on the fly, you can use services such as <a href="https://microsoft.github.io/code-push/">CodePush</a> and upload your JavaScript bundle to the Microsoft cloud and then distribute the bundle to all of your users devices. This lets you fix bugs or deploy features without releasing a new version through the stores. It brings “hot fixing” from web to mobile. If your app has native code changes you would still need to release as usual.</p><h4>UI Paradigm</h4><p>The first thing I tried to build natively on iOS and Android was something like a button and when the user pressed on it some text would change. It turned out to be quite different from how I usually reason and build my UI.</p><p><strong>Imperative approach (iOS)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*sMOV4DKc2CPCON8R-75itw.png" /></figure><p><em>Disclaimer: This battle seems to have settled with </em><a href="https://developer.apple.com/xcode/swiftui/"><em>SwiftUI</em></a><em> coming to iOS and other “React” like libraries for Android.</em></p><p>These new UI paradigms is not yet an industry standard for native app development. If it becomes the standard then the transition from native to React would be even faster. Without using any third party libraries, out of the box for iOS it would look something like the example above. Android is a little bit different since you would declare your UI elements as XML and then bind the elements to your View class. The point I’m trying to make is that in React land, you never instantiate or bind objects and then mutate them.</p><p><strong>Declarative approach (React)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*El1vbMjIqmEpVF8vR3kquA.png" /></figure><p>This reads much better in my opinion. The render call might not look like JavaScript, React uses <a href="https://reactjs.org/docs/introducing-jsx.html">JSX</a> to syntactically sugar function calls, It’s still JavaScript under the hood. It would be unfair to say that declarative API’s are better than imperative based on this comparison. With the concept of “children” in React and the declarative way of describing UI, composition do play very well.</p><p>React forces developers to build components that describes your UI. Part of designing components is to think about reusability and compose-ability. That is a superior paradigm in my experience of building UI. I’m happy to see other platforms adapting.</p><p>Reactivity<br>Here is two examples of how to update UI based on a user touch event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*4es6LM-Yyxi0IJ2pZyfr1Q.png" /><figcaption>iOS</figcaption></figure><p>iOS and Android achieves <em>data binding</em> via e.g. callbacks, delegation, notification, observables patterns to emit or observe UI changes. In the above example I’m directly mutating the <em>“label”</em> object to change the UI state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*XD_h5ys7qHuvyQFJkJHz4A.png" /><figcaption>React</figcaption></figure><p>React gives you a powerful reactivity model. The <em>handleButton</em> method when invoked will call the <em>setState</em> api and return a new copy of the state which will then re-render all child nodes in the UI tree(building a real application you will guard components for unnecessary re-renders). Data flows <em>unidirectional</em>(top to bottom). I used a <em>class component</em> in this example to demonstrate the analogy between native iOS and React components. React also lets you represent UI as plain <em>functions</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MaydlgYgXdm39q7mtedY0g.png" /></figure><p>React Native uses <a href="https://github.com/facebook/yoga">yoga</a> engine which lets you use a subset of CSS, primarily the <em>flex box</em> model to position and style elements using JavaScript. Flex box gives you an API to specify a stack of elements on a x/y axis and how much space the elements should take up. You can specify the space between or around elements. It’s similar to <em>stack view</em> on iOS or <em>linear layout </em>on Android. The terminology differ, same principles.</p><p>Above example is trivial and proves the very basic of flex box and how it’s used to draw UI. The <em>VeryNiceComponent</em> is a function that takes <em>children</em> as argument and returns a view that positions the child elements in either row or a column. The <em>Screen</em> component invokes <em>VeryNiceComponent </em>with an array of children. Building UI with flex box on mobile is a very good fit. I never missed any other CSS properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQTkRS5HLRf2rO4mdEYznQ.png" /></figure><p>No technology is perfect. There is always a tradeoff. Here’s a list of React Native the bad parts:</p><p><strong>Not 100% JavaScript:</strong></p><ul><li>React Native requires native knowledge. The more native knowledge you have before starting out the better. You need to use <em>Xcode</em> and <em>Android studio</em> for configuring and building your project.</li><li>Version upgrades it’s not as simple as bumping NPM packages. It may involve updating the native environments as well as the node environment. If you need to bridge custom native modules you would have to learn the native SDK.</li></ul><p><strong>Platform inconsistency:</strong></p><ul><li>Since React Native is calling native platform modules to render UI, the application will look and behave consistent to the platform it runs on. However this also means that sometimes you find identical styling on certain UI elements that is treated differently since the styling attributes have different meanings(<em>I’ve never had an issue that could not be worked around by branching styles depending on targeted platform</em>).</li></ul><p><strong>Single threaded:</strong></p><ul><li>React Native is not entirely single threaded, as developers we lack fine granular control over the threads. This forces developers to learn performant single threaded programming. In order to see more performant applications built in React Native e.g. games we would need to have support for multithreading. Performance is still very good, so far most performance issues I’ve experienced has been from not writing careful JavaScript.</li></ul><p><strong>Native SDK:</strong></p><ul><li>If it’s important that your business has access and control over the latest SDK features. Then React Native would not be the best choice since you will depend on 3rd party libraries to be updated or you would have to maintain custom native modules.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4EIe0kWyfEXQA4k1zYaRQ.png" /></figure><p>Where to go from here. If you think that you would benefit with React Native in your organisation or for a product then give it a go. If you are partially interested, perhaps other tools using JavaScript to build mobile applications would share some of the traits with React Native and could be a good choice e.g. <em>PWA, Ionic, or Hybird (Native shell rendering web views).</em></p><p>JavaScript is widely used, web technologies are advanced and mobile devices are fast. Don’t build a native app if you don’t really have too.</p><p>Learn about how to <a href="https://itnext.io/react-native-performance-optimization-and-profiling-5b586e9018f8">optimize and profile your React Native application</a></p><p>If you are interested in how to integrate React Native into an existing native application, then check out my friend Adam’s talk: <a href="https://youtu.be/sBbRQK58Fg8">Strangling Legacy With React Native</a></p><p><strong>Hope you enjoyed this article, I would be happy to answer your questions regarding mobile or web development.</strong></p><p>Drop a comment below or write me on <a href="https://twitter.com/osterbergmarcus">twitter</a> and follow me on <a href="https://medium.com/@Osterberg">medium</a> to not miss out on future articles 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8854abbee0b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Does React Components Re-Render]]></title>
            <link>https://medium.com/@Osterberg/react-component-renders-too-often-2917daabcf5?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2917daabcf5</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Tue, 05 Feb 2019 19:24:20 GMT</pubDate>
            <atom:updated>2020-09-24T22:17:24.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbQf_c4S4tApLZYeT32WKA.jpeg" /></figure><p><em>This article is meant to be an easy to digest note to myself and fellow developers on good practices for how to avoid pointless re-renders.</em></p><p>Before we look into different APIs and techniques one needs to have a brief understanding about what re-renders are and how they can be problematic.</p><p>React achieves a fast and responsive UI by re-rendering components on every state change (using <em>setState) </em>or<em> </em>from<em> </em>changes of props, followed by React’s <a href="https://reactjs.org/docs/reconciliation.html">reconciliation</a><strong><em> </em></strong>diffing algorithm that diffs previous renders with current render output to determine if React should commit changes to the component tree (e.g. <em>DOM</em>) with the new updates.</p><p>However, unnecessary component re-renders will happen and can be expensive, It’s been a common performance pitfall in every single React project that I’ve been working on.</p><p>Alright, let’s move on.</p><h4>Pure Components</h4><p><a href="https://reactjs.org/docs/react-api.html#reactpurecomponent"><em>Pure Component</em></a><em>s </em>shallowly compares the old state &amp; props with the new state &amp; props. Always extend<em> class components </em>from <em>React.PureComponent.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fembed%2Fpreview%2FKZbjxb%3Fheight%3D600%26slug-hash%3DKZbjxb%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fpen%2FKZbjxb&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F396845.KZbjxb.small.d308b556-e39f-4e6e-86db-4d9758f90d1a.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/94d86829508d6f0c6fdf12165df0758b/href">https://medium.com/media/94d86829508d6f0c6fdf12165df0758b/href</a></iframe><p>If you are like me and prefer the functional paradigm of React then use the <a href="https://reactjs.org/docs/react-api.html#reactmemo">memo</a> wrapper to protect <a href="https://codepen.io/osterbergmarcus/pen/pyprzm">functional components</a> from re-rendering given the same input.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fembed%2Fpreview%2FrPdwey%3Fheight%3D600%26slug-hash%3DrPdwey%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fpen%2FrPdwey&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F396845.rPdwey.small.9241826b-ce8b-43c2-8077-77474ceeee51.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a6b715d0309ab2acc10ae295469af4c/href">https://medium.com/media/3a6b715d0309ab2acc10ae295469af4c/href</a></iframe><h4>Should Component Update</h4><p>Most likely<em> Pure Components</em> will be sufficient enough. However in cases of props or state structures with deeply nested objects, values won’t be compared and you are better off using the <a href="https://reactjs.org/docs/react-component.html#shouldcomponentupdate"><em>shouldComponentUpdate</em></a> life-cycle method which is invoked on state or prop changes before <em>render</em> is called. Use this mechanism for granular control over when a component should re-render.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fembed%2Fpreview%2FomXWdx%3Fheight%3D600%26slug-hash%3DomXWdx%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fpen%2FomXWdx&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F396845.omXWdx.small.9b4ddc1c-7637-4732-887a-a22942f438be.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/246c5f54276565ba67c9684dab3ef6c7/href">https://medium.com/media/246c5f54276565ba67c9684dab3ef6c7/href</a></iframe><h4>Inline Functions</h4><p>Passing anonymous functions as props will cause the receiving component to re-render every time its parent re-renders because anonymous functions are re-initialized on every state or props change. Even if the function is still the same it will create a new memory reference since the function has to be re-allocated. Try lifting inline functions one level up from <em>render</em> if possible. Alternatively use the <a href="https://reactjs.org/docs/hooks-reference.html#usecallback"><em>callback</em></a><em> </em>wrapper for the anonymous function<em>.</em></p><pre>class App extends React.Component {<br>  nameHandler = () =&gt; &quot;foo&quot;</pre><pre>  render() {<br>    &lt;Incorrect name={() =&gt; &quot;foo&quot;} /&gt;<br>    &lt;Correct name={this.nameHandler} /&gt;<br>  }<br>}</pre><p>Same principles applies to using <em>bind</em> in render. Remember to always <em>bind</em> your handlers in the constructor since<em> Function.prototype.bind</em> will create a new function on every invocation.</p><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props)<br>      this.correctHandler = this.correctHandler.bind(this)<br>  }</pre><pre>  correctHandler() {<br>    return &quot;foo&quot;<br>  }</pre><pre>  incorrectHandler() {<br>    return &quot;foo&quot;<br>  }</pre><pre>  render() {<br>    &lt;Incorrect name={this.incorrectHandler.bind(this)} /&gt;<br>    &lt;Correct name={this.correctHandler} /&gt;<br>  }<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fembed%2Fpreview%2FLqpjNQ%3Fheight%3D600%26slug-hash%3DLqpjNQ%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fpen%2FLqpjNQ&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F396845.LqpjNQ.small.aba8c8ff-8b21-4986-bc72-d32c7ae5c77a.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e77ee1516b56742cb1e953e68fd3d44e/href">https://medium.com/media/e77ee1516b56742cb1e953e68fd3d44e/href</a></iframe><h4>Context Provider</h4><p>When a <a href="https://reactjs.org/docs/context.html"><em>Context Provider</em></a><em> </em>re-renders, all of the child components in the tree are also being re-rendered. Even if a component is not consuming props from the context provider. Again, using the memo API can prevent the re-renders.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fembed%2Fpreview%2FJjXxmZz%3Fheight%3D600%26slug-hash%3DJjXxmZz%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fosterbergmarcus%2Fpen%2FJjXxmZz&amp;image=https%3A%2F%2Fassets.codepen.io%2F396845%2Finternal%2Fscreenshots%2Fpens%2FJjXxmZz.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1600984678%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e36c9e84ae87fd210f3eb3c0cacc132/href">https://medium.com/media/9e36c9e84ae87fd210f3eb3c0cacc132/href</a></iframe><h4>How Do I Even Track Rendering Of Components?</h4><p>You can measure the rendering of a specific component simply by putting a <em>console.log</em> or <em>console.count</em> statement in the render method. If you have no clue where to start looking for potential unnecessary re-renders in your application then use the <em>highlight updates</em> feature in <a href="https://reactjs.org/docs/optimizing-performance.html#avoid-reconciliation">React DevTools</a><em>. </em>More on how to profile a React application can be found <a href="/service/shttps://reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html">here</a> and if you want to learn how to check the exact reason behind a certain re-render then it’s highlighted <a href="https://reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html#flame-chart">here</a>.</p><p>I hope this article offered something whether you are a beginner or experienced React developer. I would be happy to answer questions or to discuss any React concepts or performance topics. Drop a comment below or find me on <a href="https://twitter.com/osterbergmarcus">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2917daabcf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Performance Optimization and Profiling]]></title>
            <link>https://itnext.io/react-native-performance-optimization-and-profiling-5b586e9018f8?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b586e9018f8</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Sat, 24 Mar 2018 23:15:28 GMT</pubDate>
            <atom:updated>2020-01-16T14:51:09.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VaZlfSMNumzopToUZfGN_Q.jpeg" /></figure><p>React Native is a popular technology for engineers who are looking for building mobile applications in a productive way without compromising on native performance.</p><p>Devices today comes with multi core CPU’s and large amount of RAM. This is great for processing large data sets, computation intensive tasks, rich interactive UI’s, AND our apps will forgive us for not even consider performance optimizations. <strong>This does not mean that you should not keep performance in mind when developing a mobile application.</strong></p><p>I will share my experience on performance issues in React Native that one should be aware about. This is all based on experience from building large performing mobile applications at <a href="https://www.internations.org/">InterNations</a> using React Native. I will highlight common pitfalls and give a general understanding of what can go wrong and how to solve issues. 🖥 +🕵️‍♀️ +🔧 = 🚀.</p><p><em>In case of building a small React Native app the likelihood for running into performance issues is of course rather low and I would not recommend prematurely optimizations.</em></p><h4>State of React Native performance</h4><p>React per default re-renders a component every time its parent receives new props or updates its state, that’s one of many reasons why the React paradigm for building UI’s is superior. This is also the cause for wasteful re-renders.</p><p>In React Native we can update the frames 60 times per second. This provides the user with a smooth native experience. As the complexity of an app grows so does computation. To achieve a constant 60 FPS we would need to make sure that our UI is never blocked. Unfortunately JavaScript runs in a <em>single-threaded</em> enviroment in comparision to <em>Swift/Objective-C</em> for <em>iOS</em> or <em>Java</em>/<em>Kotlin</em> for <em>Android</em> which all supports <em>multiple threads</em>. Luckily many of the standard React Native components executes on a separate thread known as the <em>main thread</em>. This is really good because when the JavaScript thread is busy, the UI will still feel responsive.</p><p>One expensive user interaction can be navigation. Imagine a user is switching between multiple screens. Every screen is preforming network requests, computing data, screen transitions and navigation animations. All of it taking place on the JavaScript thread, then the apps frame rate would drop significantly (depending on complexity). I highly recommend to fully outsource navigation to the main thread, it will dramatically improved the overall performance. Look for a native navigation <a href="https://github.com/wix/react-native-navigation">library</a> solution.</p><p>In React Native there is the concept of a <em>bridge, </em>it’s what connects the native world and the JavaScript side. The two of them communicates by sending and receiving data in a<em> JSON</em> format. Sending data back and fourth over the bridge can be very expensive because the data needs to be <em>serialized</em> and <em>deserialized</em> every single time.</p><h4>Testing performance issues</h4><p>Current frame rates for both threads can be monitored using the<em> perf monitor </em>which can be located under the <a href="https://facebook.github.io/react-native/docs/debugging.html#accessing-the-in-app-developer-menu">developer menu</a>.</p><p>Measuring how many times your components are rendering is absolutely key. An easy way is to simply add a <em>console.count</em> call in your <em>render</em> method.</p><pre>render() {<br>  console.count(&#39;component&#39;)<br>  return &lt;Component /&gt;<br>}</pre><p>If you are running RN version 0.57 or later you can make use of React Profiler.<br>See <a href="https://github.com/facebook/react-devtools/blob/master/packages/react-devtools/README.md">docs</a> for how to setup react-devtools and read this <a href="https://reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html">post</a> on how to profile rendering of components.</p><p>Both latest <em>Android Studio</em> and <em>Xcode </em>versions offers profiling tooling<em>. </em>Try to diagnose your memory consumption and CPU load during runtime. Navigate or run certain activities in the app to verify that memory is being allocated to the heap and removed again (hopefully) once no longer in use. Also keep an eye on CPU spikes to identify computation heavy tasks. See official documentation for more in depth explanations about the platform specific profiling tools <a href="https://developer.android.com/studio/profile/memory-profiler.html">Android</a> or <a href="https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/MonitoringMemoryUsage.html">iOS</a>.</p><blockquote>Building software without looking out for memory leaks will result in software with memory leaks</blockquote><p>For Android apps running low on memory you might want to request a larger heap size by adding the <em>largeHeap</em> attribute in the android manifest file. See more details <a href="https://developer.android.com/guide/topics/manifest/application-element.html#largeHeap">here</a>.</p><p>If you are offloading work from JavaScript to the native side prevent the bridge from becoming overloaded by monitoring how many times messages are sent and received over the wire or how large the payloads are. The <a href="https://github.com/facebook/react-native/blob/master/Libraries/BatchedBridge/MessageQueue.js"><em>MessageQueue</em></a> lets you invoke a spy method to observe the traffic on the <em>bridge</em>. A good starting point is to identify messages sent over the bridge containing little to zero sized payloads and see if you can remove or replace the source of the message. E.g. empty views used to wrap multiple elements could be replaced with <a href="https://reactjs.org/docs/fragments.html">React Fragments</a>.</p><pre>import MessageQueue from &#39;react-native/Libraries/BatchedBridge/MessageQueue&#39;</pre><pre>MessageQueue.spy(message =&gt; console.log(&#39;Message&#39;, message))</pre><h4>Solving performance issues</h4><p>Keep the unnecessary re-renders down with <a href="https://reactjs.org/docs/react-api.html#reactpurecomponent"><em>React.PureComponent </em></a><em>or </em><a href="https://reactjs.org/docs/react-api.html#reactmemo"><em>memo</em></a><em>. </em>A pure component (not to be confused with stateless function components) will shallow compare its props to determine if a re-render is necessary. For more fine-grained control you should use the <a href="https://reactjs.org/docs/react-component.html#shouldcomponentupdate"><em>shouldComponentUpdate</em></a><em> </em>method.</p><p>Sometimes we want to re-render more frequently e.g. imagine you have a component that renders a list of items and the list receives new <em>props</em> from different user inputs like pagination or pulling down the list to refresh its data. Avoid inline functions in the <em>render</em> method, they will be re-created on every render and leads to components re-rendering because of prop changes, to reduce this cost name the function and store it outside of the <em>render</em>.</p><pre>class Component extends React.Component {<br>  renderSectionHeader = () =&gt; &lt;View style={...} /&gt;</pre><pre>render() {<br>    return (<br>      &lt;FlatList <br>        renderSectionHeader={this.renderSectionHeader}<br>        {...this.props}<br>      /&gt;<br>    )<br>  }<br>}</pre><p><a href="https://medium.com/@Osterberg/react-component-renders-too-often-2917daabcf5">Learn more about different techniques and concepts on how to avoid pointless re-renders in this article.</a></p><p>If you are lifting up your state to a global level, then the side effects for a state change is potentially larger. For us any many others that are using <a href="https://redux.js.org/">Redux</a> and <a href="https://redux.js.org/basics/usage-with-react">React Connect</a> as a state management tool, should watch out for <em>selector</em>s re-running on every time a state change occur. A great way to protect <em>selectors</em> against expensive computations is by caching them so that they return the previous result of a state change if its references to state has not changed. This can be easily achieved with a handy library called <a href="https://github.com/reactjs/reselect">Reselect</a>.</p><p>If you still consider to handle navigation on the JavaScript side or you are struggling with frame drops during animations. Consider to give <a href="https://facebook.github.io/react-native/docs/interactionmanager.html">InteractionManager</a> API a chance e.g. defer the render of a component until all user interactions or animations has ended.</p><pre>class AfterInteractions extends React.Component {</pre><pre>state = { interactions: true }<br>  <br>  componentDidMount() {<br>    InteractionManager.runAfterInteractions(() =&gt; {<br>      this.setState({ interactions: false })<br>  }</pre><pre>render() {<br>    if (interactions) {<br>      return null<br>    }<br>    return this.props.children<br>  }<br>}</pre><p>Animations in React Native looks good and are easy to create. Using the<em> Animated</em> library lets you enable <em>native driver, </em>this will send the animations over the bridge to the native side before the animation starts. Your animations will now execute on the main thread independently of a blocked JavaScript thread, this will result in less frame drops and a smoother experience. Set <a href="https://facebook.github.io/react-native/blog/2017/02/14/using-native-driver-for-animated.html">useNativeDriver</a> to the animation configuration.</p><pre>Animated.timing(<br>  this.state.fadeAnim, {<br>    toValue: 1,<br>    useNativeDriver: true,<br>  }<br>).start()</pre><p>Last but not least, images. Reduce file size of images makes sense to save users data plan, speed up network requests and reduce memory footprint. <a href="https://developers.google.com/speed/webp/">Webp</a> is a great compression format to consider using. Moving static images to the native side will reduce the JavaScript bundle size which is a good thing 👍 (however you won’t be able to serve clients your images on the fly any longer). More details on this topic can be found <a href="https://facebook.github.io/react-native/docs/images#images-from-hybrid-app-s-resources">here</a>.</p><p>Developing in React Native gives you the benefit of cross targeting platform developing. Building for Android and iOS simultaneously. In our experience the re-usage of code between both platforms has been astonishing. The memory layout on iOS is different compare to Android (automatic reference counting instead of garbage collection) this helps iOS apps to have a smaller memory footprint. We have noticed that iOS runs majority of the times faster then Android and consumes less memory. I recommend that if your goal is to release on both platforms then prioritize Android. I wish this was not a thing but based on our experience if Android runs smooth so will iOS.</p><p><strong>Regardless of platform one should always be testing on a real device constantly during development. </strong>When using a simulator, make sure that on Android to activate <a href="https://developer.android.com/studio/run/emulator-acceleration.html#avd-gpu">hardware accelarator</a><em> </em>it<em> </em>will drastically improve the performance of your simulator.</p><p>Overall experience so far with React Native regards to performance and optimization tooling has been positive. You learn as you go and there will always be areas of your app to improve upon. I’m looking forward to continue developing in React Native and to see how the community continues to improve the this great piece of technology. One improvement I would like to see in React Native soon would be support for<em> multi threading</em> without the need of bridging data. I could imagine something like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"><em>workers</em></a> for JavaScript that we have on the web.</p><p><strong>I hope you’ve now learned something new that will help speeding up your native app</strong>!</p><p>I would be happy to answer questions or to discuss any of the topics mentioned here. Drop a comment below or find me on <a href="https://twitter.com/osterbergmarcus">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b586e9018f8" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/react-native-performance-optimization-and-profiling-5b586e9018f8">React Native Performance Optimization and Profiling</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Concepts For Beginners]]></title>
            <link>https://medium.com/@Osterberg/oneyearwithjavascript-d55ffcf89d3d?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55ffcf89d3d</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Tue, 13 Sep 2016 15:50:07 GMT</pubDate>
            <atom:updated>2020-01-15T21:19:14.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*635UmR-7_jU19J9dTW48tg.jpeg" /></figure><p>This article is a collection of JavaScript fundamentals and gotchas. I also share some of my thoughts about the language and eco system based on my personal experience.</p><h3>What I Learned About JavaScript</h3><p>JavaScript is the language of <em>www</em><strong>, </strong>created in 10 days and is not the same thing as <em>Java.</em></p><p>ECMAScript is the standard for the language e.g. ES6 (ECMAScript 6) is the version name, while JavaScript is based on <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a>.</p><p>It’s accessible and easy to start out typing JavaScript. Your browser has a JavaScript interpreter, open the browsers console and start playing around. Write <em>1 + 1 </em>or<em> function add(a,b){return a+b} add(1,1) </em>and you have written your first calculating program. No need for setting up an environment or learn how the compiler works. The sandbox is right there in the browser.</p><blockquote>“JavaScript is not a real programming language”</blockquote><p>Yep, that’s what they say. I would say that it’s not like any other language. It’s dynamic, untyped and pretty random. However people are creating a lot of awesome stuff like complex <em>UI</em>, <em>web apps</em>, <em>mobile apps</em>, <em>desktop apps</em>, data visualisation, <em>IoT</em> and so on. There is game engines that support JavaScript. There is runtimes for JavaScript to build databases, read and write to the file system, enabling server sided operations or to instruct robots. The ecosystem is huge, it seems like there is a module for everything.</p><p>JavaScript is nowadays so called <em>universal. </em>It runs on the client side and can be executed on the server side. Not only can you handle a click event in the browser from a user, but also serve a user content or data over <em>HTTP</em> from your web server written in JavaScript. Frontend → ← Backend with one language. Not bad for a language designed to run on the client side.</p><h3>Random quirkiness you will run into</h3><p>The weird parts of JavaScript will be one of the reasons why you will love the language.</p><p>semicolons are optional because of <strong>A</strong>utomatic <strong>S</strong>emicolon <strong>I</strong>nsertion. I prefer to write without.</p><p>No <em>Int</em>(integers) in JavaScript. Numbers are floating numbers. Numbers can be assigned as decimals.</p><pre>let x = 12<br>x // 12</pre><pre>let x = 12.00<br>x // 12</pre><pre>0.1 + 0.2 // 0.30000000000000004<br>0.1 + 0.2 === 0.3 // false</pre><pre>let x = 9999999999999999<br>x // 10000000000000000</pre><p>JavaScript is not alone with this behaviour. Probably not the most suitable language for mathematical operations.</p><p>Actually you can do math with strings. Almost.</p><pre>&#39;2&#39; - &#39;1&#39; // 1<br>&#39;4&#39; / &#39;2&#39; // 2<br>&#39;2&#39; * &#39;2&#39; // 4<br>&#39;1&#39; + &#39;1&#39; // &#39;11&#39; using plus will concatenate your strings</pre><p><em>Truthy </em>and <em>Falsy </em>values is a weird thing. Booleans represent a binary digit. JavaScript has <em>boolean</em> data types but also treat all values as either “true” or “false”. An empty object in JavaScript is considered to be <em>Truthy, </em>an<em> </em>empty string or number zero is considered to be <em>Falsy</em>.</p><pre>isNaN(true) // false<br>{} // true<br>!{} // false<br>0 // false<br>&quot;&quot; // false</pre><p>Learning about which values are “true” or “false” in JavaScript is a interesting journey and in some cases important.</p><p>Which leads us onto how we compare values and types in JavaScript. Using the <em>equality operators double == </em>or <em>triple</em> <em>===. </em>Starting out learning JavaScript can be kind of tricky and this is one of the reasons.</p><pre>0 == &quot;&quot; // true<br>0 === &quot;&quot; // false<br>0 == &#39;0&#39; // true<br>0 === &#39;0&#39; // false<br>&#39;0&#39; === &#39;0&#39; // true</pre><p>Comparing zero to an empty string would give “true” because both values are <em>falsy. </em>Comparing zero to an empty string would give “false” because a number and string are not the same <em>data type. </em>Basically<em> == </em>compares values and === compares the type and value of an object.</p><p>So now we know which characters are either <em>truthy </em>or <em>falsy </em>and the notation of how to compare values, what can then go wrong?</p><pre>Boolean() // returns true if the value equates true otherwise false<br>Boolean([]) // true<br>Boolean({}) // true</pre><pre>[] == {} // false</pre><pre>[] + {} // &quot;[object Object]&quot;<br>{} + [] // 0</pre><p>Surprise!</p><p>There is a lot of reserved keywords in JavaScript, you might think that <em>undefined </em>is one of them but it’s not. All tough modern browsers don’t let you reassign <em>undefined</em>.</p><p><em>Null</em> and <em>Undefined</em>. A declared variable that has not been assigned any value is undefined. Variables assigned to a non value is null. Makes sense. But it’s not that easy:</p><pre>let foo<br>typeof foo // &quot;undefined&quot;<br>foo === undefined // true</pre><pre>let bar = null<br>typeof bar // &quot;object&quot;<br>bar === null // true</pre><p>Everything is an object in JavaScript, at least everything appears to be an object. Confusing. Regex is an object, types like <em>string</em>, <em>number</em>, <em>boolean</em> will be wrapped in an object and treated as an object, so we can call methods on them like:</p><pre>&#39;some string&#39;.toUpperCase() // &quot;SOME STRING&quot;<br>new String(&#39;some string&#39;).toUpperCase() // &quot;SOME STRING&quot;</pre><p>Refer to a variable or call a function before its declaration is fine in JavaScript due to a behaviour called <em>Hoisting. </em>Seems spooky at first.</p><pre>// Function invocation<br>foo(&#39;bar&#39;)</pre><pre>// Function declaration<br>function foo(p) {return p}</pre><pre>-&gt; &quot;bar&quot;</pre><p>Self invoking functions are a thing. More semantically correct called IIFE (Immediately Invoked Function Expression). It’s an anonymous function that invokes itself. It’s encapsulated and will there for not pollute the global name space. You will find IIFE’s in some of the popular design patterns. ES6 introduced the <em>let</em> keyword for block-scoped variables which could replace IIFE in some cases.</p><pre>(function() { return &#39;Hello&#39; }()) // Hello</pre><pre>// You can also pass an argument<br>(function(a) { return `Hello ${a}` }(&#39;World&#39;)) // Hello World</pre><p>Variables in functions are local scoped and variables outside of functions are global scoped. It’s almost that simple. Learning how scopes and the context of the keyword <em>this </em>works is essential.</p><pre>var x = &#39;Hello from global&#39;<br>function foo() { return this.x }<br>foo() // &quot;Hello from global&quot;</pre><pre>const obj = {}<br>obj.x = &#39;Hello from local&#39;<br>obj.foo = foo<br>obj.foo() // &quot;Hello from local&quot;</pre><p>I wrote a couple of lines on how scope and context works and behaves, read <a href="https://medium.com/@Osterberg/which-context-is-this-47fdb20650d2#.k5kh09cxm">here</a>.</p><p>There is a <em>garbage collector</em> in JavaScript. That’s a friendly fella that cleans up your unused references from the memory. Still watch out for memory leaks.</p><blockquote>“Don’t block the event loop”</blockquote><p>JavaScript runs on a single thread and does not allow for parallel executions. <em>Callbacks </em>is a technique used to achieve concurrent code. Callbacks allows our program to run asynchronously and prevents blocking the <em>event loop. </em>The <em>event loop</em> queues up calls so that the program can continue to run and gets notified when a call has been executed and finished its operations. Some interesting patterns that are making use of callbacks are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators"><em>generators</em></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><em>promises</em></a><em> </em>and <em>observables</em>.</p><p>If the word <em>callback </em>still makes no sense to you, check out this <a href="https://medium.com/@Osterberg/can-i-callback-32e188015b85#.gd9ncwokn">article</a> where I show how to create a callback function.</p><p>There is a library for creating a background thread in the browser to run JavaScript on called <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web Workers</a>.</p><p>There is a lot more hidden gems in this language. Let me know in comments below what you have encountered.</p><h3>How to store values</h3><p>JavaScript is <em>dynamically</em> typed which means that <em>x</em> with out specifying its type can be assigned to a number, object, string, array, function or what have you. You don’t need <em>type annotations</em> for your data structures or functions<em>.</em></p><p><a href="https://flowtype.org/">flow</a> is a type checker for JavaScript if you are missing static typing.</p><blockquote>“Arrays can’t be bothered”</blockquote><p>It’s easy to get started assigning variables and just as easy minded are <em>arrays. </em>Arrays in JavaScript are collections of values, arrays can be multi dimensional which means that an array can store an array inside of an array, arrays also don’t care if they store a string, number, boolean, object or all four together in the same array. Lazy guys!</p><pre>[1,[&#39;a&#39;],false,[[{ a: &#39;b&#39; }]],undefined] instanceof Array // true</pre><p>The data format <em>JSON </em>and JavaScript objects shares almost the same literal notation.<em> </em>JSON<em> </em>has been adapted as a standard format for data transmission and stands for JavaScript Object Notation and is a record that consists of key-value pairs just like objects in JavaScript.</p><pre>let obj = {}<br>obj.hello = &#39;world&#39;<br>obj // Object {hello: &quot;world&quot;}<br>JSON.stringify(obj) // &quot;{&quot;hello&quot;:&quot;world&quot;}&quot;</pre><p>There is a couple of <a href="https://en.wikipedia.org/wiki/NoSQL">NoSQL</a> databases <a href="https://www.mongodb.com/">MongoDB</a> being the most popular document oriented databases that are using the JSON format. If you don’t want to set up your own backend and configure a database then I would recommend <a href="https://firebase.google.com/">firebase</a>, it provides a realtime database and infrastructure for rapid prototyping.</p><blockquote>“JavaScript is a mutant”</blockquote><p>Data structures are <em>mutable</em> in JavaScript while <em>primitives</em> are immutable. For example:</p><pre>const obj = {state: &#39;on&#39;}<br>obj.state = &#39;off&#39;</pre><pre>obj // Object {state: &quot;off&quot;}<br>obj is mutated</pre><pre>var z = &#39;Hello&#39;<br>z[1] = &#39;l&#39; // &quot;Hlllo&quot;</pre><pre>z // &quot;Hello&quot;<br>z has not been mutated</pre><p><a href="https://facebook.github.io/immutable-js/">immutable</a> is a library that provides persistent immutable data structures.</p><h3>Functional</h3><p>I wont talk in Lambda terms here. However, I want you to understand that JavaScript has functional aspects built into its core. JavaScript has been a great starting point for me to learn about the functional world. To have the ability to approach code from a functional perspective is one of the reasons why I enjoy working with the language.</p><p>JavaScript treats<em> </em>functions as <em>first class citizens </em>to<em> </em>allow functions to be passed around or assigned like any other object.</p><pre>// Function returning a unix timestamp<br>function time() {<br> return new Date().getTime()<br>}</pre><pre>let assigned = time<br>assigned() // 1472589264363<br>assigned() // 1472589272867</pre><p>Functions are higher order functions in JavaScript, meaning that a function can take another function as its parameter which enables us to do <em>function composition</em>.</p><pre>const firstChar = param =&gt; param.charAt(0)<br>const toUpperCase = param =&gt; param.toUpperCase()</pre><pre>toUpperCase(firstChar(&#39;composition&#39;)) // &quot;C&quot;</pre><p>Unlike other <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a> languages JavaScript is not a <em>pure functional language</em>. Meaning that JavaScript allows your functions to have side effects.</p><p>Some functions behaves more pure then others when working with the API surface. A little bit of knowledge and discipline helps you to avoid side effects.</p><p>Here is what I mean</p><pre>let x = []</pre><pre>x.push(&#39;a&#39;)<br>x // [&quot;a&quot;]<br>x.length // 1</pre><pre>x.concat(&#39;b&#39;) // [“a”,”b”]<br>x // [&quot;a&quot;]<br>x.length // 1</pre><p><em>concat</em> would return a copy of the variable with new values. <em>push </em>would go straight away and mutate the state of the variable.</p><p>Another example using the <em>map</em> function</p><pre>const arr = [1,2,3]</pre><pre>arr.map(i =&gt; i*i) // [1, 4, 9]<br>arr.map(i =&gt; i+i) // [2, 4, 6]<br>arr // [1,2,3]</pre><p><em>map </em>will return a new transformed collection of the elements every time it’s executed. If you are like me and curious about how things works under the hood. Here is the magic behind <em>map</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3109e21330888586bc6e29b3690f3e/href">https://medium.com/media/6f3109e21330888586bc6e29b3690f3e/href</a></iframe><p>Speaking about loops. JavaScript has an <em>imperative</em> side that allows you to write <em>for loops </em>but don’t write your own loops<em>. </em>We don’t have to instruct the computer on how to loop over elements, instead use the benefits of<em> </em>JavaScript being a multi paradigm language, we have access to apply different styles of writing operations. Learning how to apply built in helper functions such as <em>map</em> or <em>forEach </em>speeded up my development and taught me how to write more declarative code.</p><p>JavaScript like many other functional programming languages supports a concept called <em>Closures. </em>A closure is a function that is stored and remember its outer environment. Allows you to curry your functions. I wrote a short introduction to closures in JavaScript that you should check out if you are unfamiliar with the concept. Check it out <a href="https://medium.com/@Osterberg/closures-are-awesome-and-confusing-772845522531#.3wbxpq3ac">here</a>.</p><h3>Object Oriented</h3><p>JavaScript as a multi paradigm language works well for both <em>object orientated programming </em>and <em>functional programming. </em>Objects are <em>prototypal inherited</em> and not <em>classical inherited, </em>if you are coming from a class-based background JavaScript will be a new adventure. We can create objects in JavaScript without classes and objects defines their own behaviour, actually with <em>ES6</em> syntactical sugar was added to constructor functions to look like classes, but your instances still deals with prototypes under the hood.</p><p>You could for example create an constructor, assign a function to its prototype, create an instance and then call the function from the instance via the prototype chain. Our instance would have no internal methods on its own neither its constructor.</p><pre>class JediAcedemy {<br> constructor(name) {<br>  this.name = name<br>}</pre><pre>JediAcedemy.prototype.sayName = function() {<br> return `Hey, I&#39;m ${this.name}`<br>}</pre><pre>let luke = new JediAcedemy(&#39;Luke Skywalker&#39;)<br>luke instanceof JediAcedemy // true<br>luke.hasOwnProperty(&#39;sayName&#39;) // false</pre><pre>luke.sayName() // &quot;Hey, I&#39;m Luke Skywalker&quot;</pre><p>Objects are linked via the prototype chain and you can reassign the prototype of your objects. It was a new concept for me and it’s important to know how it works to understand how to use the language, specially to get most out of JavaScript. Prototypes makes JavaScript a flexible language that is fun to use. I wrote a short introduction with some examples of how prototypes works, check it out <a href="https://medium.com/@Osterberg/prototypes-is-a-scary-word-f3376a9dce4c#.x78b6i3ph">here</a>.</p><p>I learned from the scene that there is a debate on how you should create your objects using <em>factory functions</em> vs <em>constructor functions</em>. I recommend you to do some research on the topic and learn about both ways and its constraints. A <em>constructor functions</em> will feel more like home if you are used to <em>classes </em>while <em>factory functions</em> seems to be quite of a JS way of creating objects.</p><pre>function factory() {<br> const language = &#39;JavaScript&#39;<br> return {<br>  learning() {<br>   console.log(`I&#39;m learning ${language}`)<br>  }<br> }<br>}</pre><pre>luke = factory()<br>typeof luke // &quot;object&quot;<br>luke.learning() // &quot;I&#39;m learning JavaScript&quot;</pre><p>As you can see we don’t need the <em>new</em> or <em>this</em> keyword. We are simply assigning a function call to a variable and using the benefits of <em>closures</em>. Really fun and dynamic way of creating objects.</p><p>JavaScript like many other object oriented languages supports <a href="https://en.wikipedia.org/wiki/Method_chaining">method chaining</a>. Allowing us to execute a sequence of methods on a specific object. Before we learned how to return the first character of a string upper cased by composing functions. Same result can be achieved from composing methods.</p><pre>&#39;chain&#39;.charAt(0).toUpperCase() // &quot;C&quot;</pre><h3>Silent Fails</h3><p>If you are a ninja who writes bug free code then this section is not for you. Big parts of learning a new programming language is to figure out how to debug the language. Specially in JavaScript where your program can break in runtime and throws <em>Uncaught TypeError: undefined is not a function.</em></p><blockquote>“log out all the things”</blockquote><p>Log out all the things to the rescue. Sure is there handy debugging tools available, your favourite browser probably has one and you should learn how to use it. Still I use the one and only <em>console.log() </em>(depending on environment)<em> </em>function for logging out what my code is doing, in which context and with which values. Another handy console method that I find neat is <em>console.count(), </em>which allows you to log the number of times count() has been called.</p><p>Lets say we have function that compares the value of items</p><pre>function compareItems(a,b) {<br> console.count(&#39;values compared&#39;)<br> if (a !== b) return &#39;items value not equal, render item to screen&#39;<br>}</pre><pre>compare(&#39;itemX&#39;,&#39;item&#39;)  // items compared: 1<br>compare(&#39;itemY&#39;,&#39;itemX&#39;) // items compared: 2<br>compare(&#39;itemZ&#39;,&#39;itemY&#39;) // items compared: 3<br>// ...You get the point</pre><h3>What I think about JavaScript</h3><p>I find JavaScript to be a really fun language to learn and use. Due to its flexibility, large range of use cases and its lively community. JavaScript feels like a rebel in comparison to many other languages. There is no strict rules or restrictions and lets you focus on being creative productive. I enjoy working with the language but because of its flexibility there is a lot of room for debates. Some strong opinions from the community on best practices will confuse you, but at the end of the day do whatever you want. JavaScript will not complain. Learn its flexibility and start to see its power.</p><p>Many people are coming into JavaScript with the mindset of trying to use the language to favour how they are used to program. Instead of adapting the language for what it is and has to offer.</p><blockquote>“JavaScript fatigue”</blockquote><p>The JS community is very active. Every week you hear about new frameworks, libraries, starter kit, build tools, package managers and services of all kinds. The industry is changing rapidly and it feels overwhelming trying to catch up on all the features. From its large eco system of tools and all the buzz words the term “<em>JavaScript fatigue</em>” was born. I admit that it can be annoying setting up a new project and trying to find and match all the pieces but In my opinion it’s a good sign. It’s a good sign that people are interested in building, sharing, shaping, and pushing innovations forward. There is so much valuable stuff out there for free, ready to be used.</p><p>I’m able to share this knowledge and hopefully educate some of you, because I got the knowledge from the community. For free. I encourage everyone to share their knowledge and make programming the best craft in the world!</p><p>Enough with all the fun facts, can I make a living as a JavaScript developer? at the time of writing this article. Yes, you most defiantly can. There is a huge need of developers on the market today. It’s a good time for JavaScript. It’s the most popular language, especially for web and soon to be mobile development.</p><h3>What does the future behold for JavaScript</h3><p>Well, it’s the language of the web after all so it’s here to stay for a while. I hope that mobile development with JavaScript will become much more popular and common. I’m currently very excited to learn and use <a href="https://facebook.github.io/react-native/">React Native</a> for building native mobile apps.</p><p><strong>A language without a community is a dead language</strong>. The JavaScript community as I described before is active and supportive.</p><p>Every year from now on ECMAScript will have a new version released. Like it or not we will need to expand our tool box and get used to transforming the new generation of JavaScript to an older one, so the browsers can run our applications. I don’t think that we can count on browsers to keep up the support. There is some interesting ideas of brining <a href="http://www.sweetjs.org/">macros</a> to JavaScript, you could then create a macro and then load your syntax as a library. At the time of writing this article <a href="https://babeljs.io/">babeljs</a> is the most popular transpiler. If you are a developer that have not already started to write next generation JS then I don’t know what you are waiting for.</p><p>It will become more popular to compile down to JavaScript, There is already ridicules many <a href="https://github.com/jashkenas/coffeescript/wiki/list-of-languages-that-compile-to-js">languages</a> that you could use if you are interested in another style or principles. If you are scared of learning haskell then <a href="http://elm-lang.org/">Elm</a> is a cool kid that compiles to JavaScript, Elm approaches web development from a functional perspective.</p><p>JavaScript runs on a single thread and our cpu’s are not getting less cores. Concurrency will become an important topic in the future and a potential issue for the language.</p><p>In summary I think JavaScript has a bright future and I’m excited to see how it evolves and to be part of it.</p><p>I hope you enjoyed my bias views and that you are now convinced to learn JavaScript. If you have any questions please drop a comment below or hit me up on <a href="https://twitter.com/osterbergmarcus">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55ffcf89d3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Higher-order Functions]]></title>
            <link>https://medium.com/@Osterberg/can-i-callback-32e188015b85?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/32e188015b85</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Tue, 10 May 2016 19:52:39 GMT</pubDate>
            <atom:updated>2020-01-15T20:47:07.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*pj4PNtA6aVaJzAWfTAVf7A.png" /></figure><p><strong>Async JavaScript With Higher Order Functions</strong></p><p>If JavaScript is a functional programming language or not I leave for you to decide, but the language do have aspects from the functional language paradigm. See reference <a href="https://en.wikipedia.org/wiki/Functional_programming">Wiki</a>.</p><p>In JavaScript functions are <em>Higher-order</em> functions and functions are treated as <em>First-class citizens</em>. You don’t have to know computer science to write JavaScript, but these concepts are the reason why we can pass functions as arguments, store them in variables, create functions inside a functions body and return them. Just like we do with any other object.</p><p>Callback functions are a big deal in JavaScript. It’s a a technique that allows JavaScript to run asynchronously. Meaning that your program can continue to execute with out having to stop and wait for a task to be done. Callbacks are a direct result of Higher-order functions, a function that accepts another function as an argument. You have probably used callback functions when you are passing a function as an argument to the Array.prototype.map() or when you are handling scenarios from different responses on your AJAX calls.</p><p>This is setInterval takes a callback function as an argument:</p><pre>setInterval(() =&gt; { <br>  alert(“Stop calling me”)<br>}, 3000)</pre><p>After three seconds the anonymous function will fire from the callback queue and alert the message. During those three seconds our runtime can continue execute other callbacks or events. Great!</p><blockquote>A callback is a function that executes later</blockquote><p>Lets create our own callback function:</p><pre>let data = []</pre><pre>function mergeData(param) {<br>  setTimeout(() =&gt; {<br>    data = data.concat(param)<br>    alert(&#39;Duplication done&#39;)<br>  }, 3000)<br>}</pre><pre>function setData(…args) {<br>  let [param, callback] = args<br>  data = param</pre><pre>  if(typeof callback === &#39;function&#39;) {<br>    console.log(&#39;Starting merge&#39;)<br>    callback(arr)<br>    console.log(&#39;Continue program while awaiting..&#39;)<br>  }<br>}</pre><p>We are creating a function called merge<em>Data </em>it takes a parameter, starts a time out and after 3 sec it concats <em>data </em>and with the given parameter. Nothing special so far but good enough to show the concept.</p><p>Now we want to pass <em>mergeData</em> as a callback function. We create the function <em>setData, </em>deconstructing its arguments, set the value of data to be what ever the first argument of the function is, validates so that the callback argument is a function, if true then invoke the given callback function. The callback could be named what ever you prefer but for simplicity I named it <em>callback.</em></p><p>Lastly we invoke <em>setData</em> with an array and <em>duplicateData</em> as a callback function:</p><pre>setData([1, 2, 3], duplicateData)<br>-&gt; &#39;Starting merge&#39;<br>-&gt; &#39;Continue program while awaiting..&#39;<br>-&gt; &#39;Duplication done&#39;</pre><pre>data // [1, 2, 3, 1, 2, 3]</pre><p>Callbacks are a powerful component of JavaScript and a fun one. When I was new to JavaScript, I used callbacks for some time without knowing what it was or how it worked. I believe that many people who are new to programming or JavaScript in particular could be confused with the concept.</p><p>If you found this useful or if you have anything to add, please comment below.</p><p>Enjoy your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32e188015b85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript This Keyword Explained]]></title>
            <link>https://medium.com/@Osterberg/which-context-is-this-47fdb20650d2?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/47fdb20650d2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lexical-scope]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Thu, 05 May 2016 20:05:32 GMT</pubDate>
            <atom:updated>2020-01-15T20:43:13.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*75eW9wn_V8PPaBxkufnsUw.jpeg" /></figure><p><strong>What context is this</strong></p><p>Get rid of all the scooping errors, lets learn about how we refer to the context object in JavaScript with the keyword <em>this.</em></p><p>Executing <em>this</em> inside our browsers console would return the global object w<em>indow:</em></p><pre>this // window { external: Object, .... }</pre><p>Lets create a object called <em>world</em> with a method called <em>display</em> that returns <em>this:</em></p><pre>const world = {<br> data: [&#39;Denmark&#39;, &#39;Germany&#39; ],<br><br> display() {<br>  return this<br> }<br>}</pre><pre>world.display() // Object { data: Array[2] }</pre><p>The returned context of<em> this </em>is<em> </em>no<em> </em>longer referring to the global w<em>indow</em> object, it’s now referring to the enclosing execution context which is the <em>world</em> object.</p><p>So now that we know when <em>this</em> is <em>this</em> lets access <em>this data:</em></p><pre>const world = {<br>  data: [&#39;Denmark&#39;, &#39;Germany&#39; ],<br><br>  display() {<br>    this.data.forEach(element =&gt; console.log(element.toUpperCase()))<br>  }<br>}</pre><pre>world.display()<br>-&gt;DENMARK<br>-&gt;GERMANY</pre><p>Very often you find your self want to access data from another scope inside of your context.<br>It’s useful to know how to access a scope from a contexts surrounding environment. Introducing <em>function.prototype.bind()</em> and <em>.call().</em><br>We can bind the context of <em>display</em> to reference the global w<em>indow</em> object:</p><pre>const data = [&#39;Canada&#39;, &#39;Sweden&#39;]</pre><pre>const world = {<br> data: [&#39;Denmark&#39;, &#39;Germany&#39;],</pre><pre> display: function() {<br>  this.data.forEach(element =&gt; console.log(element.toUpperCase()))<br> }.bind(window)<br>}</pre><pre>world.display()<br>-&gt;CANADA<br>-&gt;SWEDEN</pre><p>Lets declare a variable and assign it to the <em>display</em> method:</p><pre>const foo = world.display</pre><p><em>foo</em> don’t know <em>display</em> methods original surrounding context and refer <em>this</em> to the global w<em>indow</em> object instead of <em>world</em>.</p><pre>foo()<br>-&gt;CANADA<br>-&gt;SWEDEN</pre><p>We can provide the original scope for <em>this</em>, by using the <em>.call():</em></p><pre>// Provide the world object as the context of this<br>foo.call(world)<br>-&gt;DENMARK<br>-&gt;GERMANY</pre><p>This has been a brief introduction on how to reference scopes context in JavaScript using the keyword this. Please let me know in the comments below if you found this helpful or have anything to add.</p><p>Keep on learning JavaScript and enjoy your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47fdb20650d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Prototype Inheritance]]></title>
            <link>https://medium.com/free-code-camp/prototypes-is-a-scary-word-f3376a9dce4c?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3376a9dce4c</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Fri, 29 Apr 2016 12:51:00 GMT</pubDate>
            <atom:updated>2020-01-15T20:40:51.819Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Prototypes For Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*neqIcoDM-L6BFqxLtgUVbw.jpeg" /></figure><p>JavaScript is a prototype-based language. Lets deconstruct the definition of prototypes in JavaScript.</p><p>When you start of learning object orientated programming with JavaScript, you will quickly encounter prototypal inheritance.</p><p>A prototype is a member of an object, and can be referenced from an instance. Before we create our own prototype. Lets just see a quick example of how we are already dealing with prototypes.</p><p>Lets create an array:</p><pre>let x = [1, 2]<br>x.map(a =&gt; a + 1) // [2, 3]</pre><p><em>x</em> holds an array. <em>x</em> is an instance of Array. <em>x</em> has a reference to all of the prototype properties from Array. So we could for example call Array.prototype.map() function on <em>x</em></p><blockquote>I’m starting to see prototypes everywhere!</blockquote><p>Let’s set our own prototype:</p><pre>// Creates a constructor called Country<br>class Country {<br> constructor(country) { <br>  this.country = country<br> }<br>}</pre><pre>// Create a new instance of Country<br>let sweden = new Country(&#39;Sweden&#39;)</pre><pre>// sweden is now an object called Country<br>sweden // Country { country: &#39;Sweden&#39; } </pre><p>Now we want <em>sweden</em> to say hello to the world. This is where prototypes and the prototype-chain comes into play</p><pre>// Add method to the prototype of the constructor<br>Country.prototype.helloWorld = function() {<br> return `I am a country called ${this.country}`<br>}</pre><p><em>Country</em> has the method <em>helloWorld as a </em>prototype property. <em>sweden</em> is still the same object but we can now reference <em>helloWorld.</em></p><pre>sweden.helloWorld() // &#39;I am a country called Sweden&#39;</pre><p>The interpreter looks for the <em>helloWorld</em> If no references is found it will start to jump up the prototype chain until the request is satisfied In this case <em>helloWorld</em> can be related to <em>sweden</em> via the prototype chain.</p><p>And if we create a new country:</p><pre>let canada = new Country(&#39;Canada&#39;)</pre><p>Same goes for <em>canada</em>, the new instance of <em>Country </em>can<em> </em>also access the prototypes. This is how a prototype and the prototype chain works. It works as a link between the function and its objects.</p><blockquote>I want to share my constructors prototype with another constructor?</blockquote><p>Lets say we want to add PlanetA prototype object to PlanetB</p><pre>// Constructor PlanetA<br>class PlanetA {<br> constructor(instance) {<br>  this.instance = instance<br> }<br> // prototype method<br> helloWorld() {<br>  return `I am a instance called ${this.instance}`<br> }<br>}</pre><pre>let x = new PlanetA(&#39;x&#39;)</pre><pre>x.helloWorld() // I am a instance called x</pre><p>To demonstrate the flexibility of prototypal inheritance we will link the prototypes of our instance of PlanetA to PlanetB. We can use <em>Object.setPrototypeOf()</em> to do that.</p><pre>// Constructor PlanetB<br>class PlanetB {<br> constructor(instance) {<br>  this.instance = instance<br> }<br>}</pre><pre>let y = new PlanetB(&#39;y&#39;)</pre><pre>Object.setPrototypeOf(y, x)</pre><pre>y.helloWorld() // I am a instance called y</pre><p>This was a basic introduction to the concept of inheritance in JavaScript. The key is to know that you have the ability to dynamic instantiate objects without any internal properties but still be able to access methods on the prototype chain.</p><p>There is more details to prototypes and ways of handling inheritance in JavaScript, depending on how you choose to factor your objects. The ‘class’ keyword is syntactic sugar on constructor functions. There is no such thing as class inheritance in JavaScript only a prototypal way of inheritance.</p><p>I hope you found this helpful and that you can now feel more comfortable talking about prototypes and how OOP works in JavaScript.</p><p>Enjoy your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3376a9dce4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/prototypes-is-a-scary-word-f3376a9dce4c">JavaScript Prototype Inheritance</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Closure Example]]></title>
            <link>https://medium.com/free-code-camp/closures-are-awesome-and-confusing-772845522531?source=rss-8f34ae37cef5------2</link>
            <guid isPermaLink="false">https://medium.com/p/772845522531</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcus Osterberg]]></dc:creator>
            <pubDate>Tue, 26 Apr 2016 15:54:52 GMT</pubDate>
            <atom:updated>2020-01-15T20:44:46.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*JWzsosAtUsTcI97cdYWhMg.jpeg" /></figure><p><strong>Closures are awesome and confusing</strong></p><p>I want to share how I started to understand Closures in JavaScript. This is a beginner friendly view with a simple example. Closures is a function wrapped inside of a functions body that can be referenced to its scope chain e.g. outer variables.</p><blockquote>Definition from the book Speaking JavaScript “A closure is a function plus the connection to the scope in which the function was created”- Dr. Axel Rauschmayer</blockquote><p>This is how it can look like:</p><pre>function newCounter() {<br>  let counter = 0<br>   return function increment() {<br>    counter++<br>    console.log(counter)<br>   }<br>}</pre><pre>let counter1 = newCounter()<br>let counter2 = newCounter()</pre><pre>// Numbers of events<br>counter1() // 1<br>counter1() // 2<br>counter2() // 1<br>counter1() // 3</pre><p><em>newCounter</em> closes over <em>increment</em>, <em>counter</em> can be referenced to and accessed by <em>increment. </em>If JavaScript would not have closures, we would now have to pass <em>counter</em> to our function <em>increment</em> to be able to access the variable. The <em>closure</em> now holds the scope chain and prevents it from being garbage collected.</p><p><em>counter1</em> and <em>counter2</em> will keep track of their own value.</p><p>Closures allows us to do function <em>currying. </em>We can create a sequence of functions where each functions takes an individual parameter. For example:</p><pre>// Lets say we want to create an element with some text and append it to the DOM</pre><pre>const manipulateDOM = (text) =&gt; (node) =&gt; (appendTo) =&gt; {<br> const newText = document.createTextNode(text)<br> const newNode = document.createElement(node)<br> const element = document.querySelector(appendTo)</pre><pre> element.appendChild(newNode)<br> newNode.appendChild(newText)<br>}</pre><pre>manipulateDOM(&#39;Closure&#39;)(&#39;div&#39;)(&#39;#some-id&#39;)</pre><p>All the chained functions above has a closure of the parameters.</p><p>I hope this was a clear introduction to what closures are and how they can be used in JavaScript.</p><p>Enjoy your code</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772845522531" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/closures-are-awesome-and-confusing-772845522531">JavaScript Closure Example</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>