One place for hosting & domains

      August 2021

      Understanding Closures in JavaScript


      In this article, you will cover the basics of what a closure is and why JavaScript benefits from closures.


      If you would like to follow along with this article, you will need:

      • Familiarity with JavaScript variables, functions, scope, and callbacks.

      Defining a Closure

      A closure can be defined as a persistent scope that is held onto by a variable. Languages like JavaScript and Ruby support closures, which allows variables to have references to their parent scope even after their programming block has been executed and, as long as these variables have a reference somewhere, the closure exists.

      Consider the following closure example:

      function outerFunction() {
       let delayed = veryLongOperation();
       let innerFunction = function() { someCallback(delayed); }

      The innerFunction is a function that is able to access its parent scope elements – like the delayed object.

      Using Closures

      Now that we’ve seen what closures are, why are they useful?

      JavaScript can be asynchronous when it comes to execution. When an operation is completed, a callback has to be employed. This callback now has to run with the same execution context as its caller/parent. This means that whatever variables or functions were available to the parent must now be made available to the callback as well. If these callbacks did not have closures, then we’d have to manually bind the needed scope members.

      Closures make our lives a lot easier by handling this for us in the background. If there is a function inside a function, the inner function has access to its scope members throughout its lifetime.

      Consider the following class definition example:

      let classExample = function () {
        let randomNumber = Math.floor(Math.random() * 10);
        return function() {

      The scope chain of the inner function is extended to include the members of the classExample function.

      Another instance where closures come into play is during currying. Currying is the process of returning multiple functions to reduce arity. It’s employed in functional programming paradigm to reduce state changes.

      Closures can be used along with currying to introduce private members for JavaScript classes.

      function curryingExample() {
        let message = "Hello.";
        return {
          getMessage: function() { console.log('private message', message); }

      Create a new curryExample() instance:

      let curry = new curryingExample();

      Attempt to access message:

      console.log('undefined message', curry.message);

      When console.log(curry.message); executes the value will be undefined.

      Attempt to use getMessage():


      When curry.getMessage(); executes, the value will be "Hello.".


      Closures are a very subtle yet powerful feature of JavaScript and understanding them is a very important step on the path to becoming a serious JavaScript developer.

      This is explained in more detail in Kyle Simpson’s excellent write-up on Closures.

      Source link

      How To Get Total Result Count in Laravel Eloquent

      Part of the Series:
      A Practical Introduction to Laravel Eloquent ORM

      Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. In this project-based series, you’ll learn how to make database queries and how to work with relationships in Laravel Eloquent. To practice the examples explained throughout the series, you’ll improve a demo application with new models and relationships.

      When working with database query results, it is often useful to obtain only the total number of rows in a result set, instead of pulling the full dataset content with a regular query. Eloquent offers a few different aggregate methods that return a scalar number instead of an Eloquent object, including count(), max(), and sum(), among others. These are all made available through the inherent query builder that is built into every Eloquent model.

      In this part of the series, you’ll update the main application view to show the total number of links in each list.

      Open the file resources/views/index.php in your code editor:


      Locate the paragraph styled with the subtitle class, which contains the foreach loop that renders the application menu:

      <p class="subtitle">
           @foreach ($lists as $list)<a href="{{ route("link-list', $list->slug) }}" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }}</a> @endforeach

      To obtain the total number of links in each list, you can access the query builder from within the $list->links() relationship method defined on the LinkList class, and call the count() method that is available through the query builder:

      {{ $list->links()->count() }}

      Update the code inside the foreach loop to include the count() method call, which will display the number of links in a list. Make sure to place it inside the <a> tag and right after the list title. You can wrap this information inside a parenthesis for more readability in the rendered HTML output.

      This is how the code should look like once you are finished:

       <p class="subtitle">
            @foreach ($lists as $list)<a href="{{ route("link-list', $list->slug) }}" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }} ({{ $list->links()->count() }})</a> @endforeach

      Save the file when you’re finished. Then, reload the main application page on your browser:


      You’ll obtain a page like the following, showing the total number of links included in each list, on the top menu:

      Updated application showing number of links in each link on the top menu

      In the next part of this series, you’ll learn how to limit the number of results in a query, and how to paginate results in Laravel Eloquent.

      This tutorial is part of an ongoing weekly series about Laravel Eloquent. You can subscribe to the Laravel tag if you want to be notified when new tutorials are published.

      Source link

      How To Install the Deno JavaScript Runtime on Ubuntu 20.04


      Deno is a new JavaScript runtime being developed by the creator of Node.js, with a focus on security, developer experience, and compatibility with standard browser APIs.

      Deno uses the same V8 JavaScript engine as Node.js and the Chrome web browser, but ships with secure sandboxing, built-in TypeScript support, and a curated set of standard modules.

      In this tutorial we will download and install Deno on Ubuntu 20.04, and run a hello world statement to test out our installation.


      This tutorial assumes you are running Ubuntu 20.04 and are logged in as a non-root, sudo-enabled user. For help setting this up, please refer to our Initial Server Setup with Ubuntu 20.04 tutorial.

      If you would like to follow along with this tutorial using a terminal in your browser, click the Launch an Interactive Terminal! button below. You’ll be able to run each of the commands right from your browser.

      Launch an Interactive Terminal!

      Step 1 — Downloading Deno

      Deno ships as a single executable file, making it possible to download and install it manually. First navigate to a directory where you can download the roughly 30mb file. We’ll use the /tmp directory here:

      Next, use curl to download the latest release of Deno from GitHub:

      • curl -Lo "" ""

      This will display a progress bar:


      % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 158 100 158 0 0 3361 0 --:--:-- --:--:-- --:--:-- 3361 100 641 100 641 0 0 8902 0 --:--:-- --:--:-- --:--:-- 8902 100 31.3M 100 31.3M 0 0 132M 0 --:--:-- --:--:-- --:--:-- 132M

      When the download is complete, you’ll have a file in your current directory. In the next step, you’ll decompress this file and install the deno executable.

      Step 2 — Installing Deno

      Now that you’ve downloaded the Deno zip file, it’s time to install it. First you’ll need to make sure you have the unzip command installed to decompress the file. Update your system’s package index and then install unzip with apt. You may be prompted to provide your sudo user’s password if this is the first time you’re using sudo in this session:

      • sudo apt update
      • sudo apt install unzip

      When installed, use unzip to decompress the deno executable into the /usr/local/bin directory:

      • sudo unzip -d /usr/local/bin /tmp/

      The -d flag tells unzip to place the resulting file in /usr/local/bin. Note that because you’re unzipping into a protected system directory, you’ll need to use sudo above.

      The installation should now be complete. Use ls to list the new /usr/local/bin/deno file and make sure it has the correct owner and permissions:

      • ls -al /usr/local/bin/deno


      -rwxr-xr-x 1 root root 87007232 Aug 23 21:06 /usr/local/bin/deno

      The above permissions are typical. Only root should have write (w) permissions, and everybody should have execute (x) permissions. For more information on Linux permissions, please see our Introduction to Linux Permissions tutorial.

      Next, run the deno command with a --version flag to make sure it executes properly:

      deno will print out some version information:


      deno 1.13.2 (release, x86_64-unknown-linux-gnu) v8 9.3.345.11 typescript 4.3.5

      You’ve now successfully downloaded and installed Deno. Next we’ll use it to run a hello world statement.

      Step 3 — Using the Deno REPL

      If you run the bare deno command with no subcommands, it’ll put you into the Deno REPL. REPL is short for “read-eval-print loop”, an interactive prompt where you can input statements and have them evaluated, with the results printed immediately.

      REPLs can be a good way to experiment with a new programming language.

      Open the Deno REPL now:

      deno will print out its version, some help text, and a > prompt:


      Deno 1.13.2 exit using ctrl+d or close() >

      Type in the following JavaScript hello world example and hit ENTER to have Deno evaluate it and print the results:

      • ['hello', 'world'].join(' ')

      This statement creates a JavaScript array (['hello', 'world']), then uses the array’s join() method to join the two words together with a space character:


      "hello world"

      It worked! To exit the Deno REPL, press CTRL+D or type close() and press ENTER.


      In this tutorial you downloaded and installed Deno, then ran a hello world statement in its REPL. For more information on Deno, please see the official Deno Manual and the Deno API documentation.

      For general JavaScript information, see our How To Code in JavaScript tutorial series, or our JavaScript tag page which will have links to more tutorials and community Q&A.

      Source link