One place for hosting & domains

      Practical

      Understanding JavaScript Closures: A Practical Approach

      Introduction

      Learning a new language involves a series of steps, whereas its mastery is a product of patience, practice, mistakes, and experience.

      Some developers will have enough knowledge to deliver on features as per a client’s demand, but it takes more than just that to be a good developer.

      A good developer is one who takes time to go back and get a good grasp of a language’s underlying/core concepts.

      Today we take a deeper look at JavaScript closures and hope that the knowledge you learn will be beneficial in your projects.

      A JavaScript Closure is when an inner function has access to members of the outer function (lexical scope) even when executing outside the scope of the outer function.

      Therefore, we cannot afford to talk about closure while leaving out functions and scope.

      Scope refers to the extent of visibility of a variable defined in a program. Ways to create scope in JavaScript are through: try-catch blocks, functions, the let keyword with curly braces among others. We mainly have two variations of scope: the global scope and local scope.

      var initialBalance = 0 
      
      function deposit (amount) {
        
        var newBalance = parseInt(initialBalance) + parseInt(amount)
        return newBalance
      }
      

      Each function in JavaScript creates its own local scope when declared.

      This means that whatever is declared inside the function’s local scope is not accessible from the outside. Consider the illustration below:

      var initialBalance = 300 
      
      function withdraw (amount) {
        var balance 
      
        balance = parseInt(initialBalance) - parseInt(amount)
        return balance
      }
      console.log(initialBalance) 
      console.log(balance) 
      

      JavaScript’s Lexical Scope is determined during the compile phase. It sets the scope of a variable so that it may only be called/referenced from within the block of code in which it is defined.

      A function declared inside a surrounding function block has access to variables in the surrounding function’s lexical scope.

      var initialBalance = 300 
      
      function withdraw (amount) {
        
        var balance = parseInt(initialBalance) - parseInt(amount)
      
        const actualBalance = (function () {
          const TRANSACTIONCOST = 35
          return balance - TRANSACTIONCOST 
        })() 
      
        
        return actualBalance
      }
      

      Invoking an inner function outside of its enclosing function and yet maintain access to variables in its enclosing function (lexical scope) creates a JavaScript Closure.

      function person () {
        var name = 'Paul'  
      
        var actions = {
          speak: function () {
          
            console.log('My name is ', name) 
          }
        } 
      
        return actions 
      }
      
      person().speak() 
      

      A Closure allows us to expose a public interface while at the same time hiding and preserving execution context from the outside scope.

      Some JavaScript design patterns make use of closures.

      One of these well-implemented patterns is the module pattern, this pattern allows you to emulate: private, public, and privileged members.

      var Module = (function () {
        var foo = 'foo' 
      
        function addToFoo (bam) { 
          foo = bam
          return foo
        }
      
        var publicInterface = {
          bar: function () { 
            return 'bar'
          },
          bam: function () { 
            return addToFoo('bam') 
          }
        }
      
        return publicInterface 
      })()
      
      Module.bar() 
      Module.bam() 
      

      From our module pattern illustration above, only public methods and properties in the return object will be available outside the closure’s execution context.

      All private members will still exist as their execution context is preserved but hidden from the outside scope.

      When we pass a function into a setTimeout or any kind of callback. The function still remembers the lexical scope because of the closure.

      function foo () {
        var bar = 'bar'
        setTimeout(function () {
          console.log(bar)
        }, 1000)
      }
      
      foo() 
      

      Closure and loops

      for (var i = 1; i <= 5; i++) {
        (function (i) {
          setTimeout(function () {
            console.log(i)
          }, i * 1000)
        })(i)
      }
      
      
      for (let i = 1; i <= 5; i++) {
        (function (i) {
          setTimeout(function () {
            console.log(i)
          }, i * 1000)
        })(i)
      }
      
      

      I bet we now have an understanding of closures and can do the following:

      • Illustrate its use cases or identify it in contexts we never knew we used it
      • Preserve execution context as we wish
      • Implement code in JavaScript’s module pattern
      • Use closures in our code, with a clear understanding

      Until next time, happy coding.

      Practical Kubernetes Networking: How to Use Kubernetes Services to Expose Your App


      How to Join

      This Tech Talk is free and open to everyone. Register below to get a link to join the live stream or receive the video recording after it airs.

      DateTimeRSVP
      September 22, 202111 a.m.–12 p.m. ET / 3–4 p.m. GMT

      About the Talk

      You’ve deployed an application and a few microservices into your Kubernetes cluster and now you’re wondering how to configure the workloads so that they communicate with one another, and more importantly, how to expose your application to the internet. This talk will show you how to use Kubernetes Services to enable communication between your workloads and how to configure your application so it can accept traffic from the internet.

      What You’ll Learn

      • The difference between the kinds of Kubernetes Services
      • How to use the ClusterIP service to enable internal communication between workloads
      • How to use the LoadBalancer service to expose an application so it is reachable from the internet

      This Talk Is Designed For

      • Anyone running containerized workloads in a non-Kubernetes environment
      • Anyone looking to gradually migrate to Kubernetes
      • Anyone interested in how Kubernetes microservices communicate with one another

      Prerequisites

      • You have containerized an application or microservice
      • You have basic knowledge of containers and Kubernetes
      • You are familiar with Kubernetes Deployments

      Resources

      Kubernetes Docs: Services
      Networking Best Practices To Power Your Kubernetes Deployment
      Using a Service to Expose Your App

      Kubernetes in minutes, on DigitalOcean

      DigitalOcean Kubernetes (DOKS) is a managed Kubernetes service that lets you deploy Kubernetes clusters without the complexities of handling the control plane and containerized infrastructure. Clusters are compatible with standard Kubernetes toolchains and integrate natively with DigitalOcean Load Balancers and block storage volumes.

      DigitalOcean Kubernetes is designed for you and your small business. Start small at just $10 per month, and scale up and save with our free control plane and inexpensive bandwidth.



      Source link

      Practical Guide to Using CSS Position Relative & Absolute


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      Introduction

      In this article, you’ll learn how to use CSS position: relative and position: absolute through ample amounts of demos, and learning aids.

      CSS position is sometimes considered an advanced topic because it can do things that are somewhat unexpected. Well, don’t let “the experts” intimidate you from pursuing excellence in your CSS competence! It’s a very accessible topic once you’re equipped with some of the underlying ideas.

      Render Flow

      An important concept to understanding relative/absolute positioning is render flow.

      The general idea is that HTML elements all take up some space. Your browser’s rendering engine always renders everything in a grid-like fashion, starting at the top-left corner and moving successively towards the bottom-right until it’s done placing all of your HTML content.

      If you’ve ever had a slow internet connection, and watched as large stuff on the webpage would push everything rightward and downward, that is essentially “render flow” in action.

      You can change this default behavior using CSS position.

      CSS Position

      CSS position is sometimes considered an advanced skill because it’s not as intuitive as font-size or margin, etc., since it changes the natural “render flow” of the browser.

      These are the possible values for CSS position:

      .foo {
        position: static;
        /* position: relative;
        position: absolute;
        position: sticky;
        position: fixed; */
      }
      

      Today we’re just going to look at position: absolute and position: relative since they’re perhaps the most versatile ones that will get you a lot of mileage once you feel confident with them.

      Relative Positioning

      When you make an HTML element position: relative, it’ll remain “in the flow” of the layout but you can move it around!

      .green-square {
        position: relative;
        top: 25px;
        left: 25px;
        /* ... */
      }
      

      Along with position: relative you’ll usually want to define the top, right, bottom, or left offset.

      You can think of “relative” position as being: “relative to where it was initially positioned.” In this case, the green square is now 25px from the left, and 25px from the top of where it was initially going to be.

      What’s also worth noting is that its width and height is preserved in the square grid. That means it’s still considered “in the flow” of the layout… it just got kinda nudged.

      Absolute Positioning

      Absolute positioning is a very powerful CSS rule for moving HTML elements around. Sometimes yielding unexpected results:

      .orange-square {
        position: absolute;
        top: 0px;
        left: 0px;
        /* ... */
      }
      

      The orange square is actually the 13th of these 25 squares (the one in the middle of the grid), but it looks like it’s the last square! Weird. Using position: absolute takes elements “out of flow” so its grid space gets collapsed.

      Yea but why’s it all the way up there?!

      Originating coordinates

      The orange square gets placed at the 0x, 0y coordinates (eg.: the top-left corner). Just how browser rendering always begins at the top-left corner, position: absolute elements use that as their rendering origin too. You can use top/right/bottom/left properties to offset it from there.

      But, you can also give it different originating coordinates…

      .grid {
        position: relative;
      }
      .orange-square {
        position: absolute;
        top: 0px;
        left: 0px;
        /* ... */
      }
      

      In the example above, the parent element (div.grid) has the position: relative rule which causes the orange square to take that as its rendering origin.

      While this may seem unintuitive behavior, it’s actually intentional! Allowing for this gives you a lot of control over where/how you arrange HTML elements…

      Conclusion

      When you start using position: relative and position: absolute it opens a new world of design possibilities. You can create layered visual elements, and feel a deep sense of confidence about how browsers will render, and thus place the visual elements that you’ve so meticulously designed.

      Learn more about CSS position at the Mozilla Developer Network



      Source link