<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Njong Emy - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Njong Emy - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 13 May 2026 22:43:53 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/njong329/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Dockerize a Go Application – Full Step-by-Step Walkthrough ]]>
                </title>
                <description>
                    <![CDATA[ Imagine that you want to share your source code with someone who doesn’t have Go installed on their computer. Unfortunately, this person won’t be able to run your application. Even if they do have Go  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-dockerize-a-go-application-full-step-by-step-walkthrough/</link>
                <guid isPermaLink="false">69f248846e0124c05e445b7a</guid>
                
                    <category>
                        <![CDATA[ Docker ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Docker compose ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Wed, 29 Apr 2026 18:05:56 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/e49dda12-fd5e-4474-aa18-b72624640bf3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Imagine that you want to share your source code with someone who doesn’t have Go installed on their computer. Unfortunately, this person won’t be able to run your application. Even if they do have Go installed, application behaviour may differ because your local development environment is different from theirs.</p>
<p>So how do you bundle up your application so that it can run the same way in every local environment? That’s where Docker comes in.</p>
<p>For beginners, Docker isn't always a very easy concept to grasp. But once you get it, I promise that it’s very interesting. So interesting that you’ll want to dockerize every application you lay your hands on.</p>
<p>For this article, a Go application will be our case study. The fundamental concept of containerization as explained here is transferable, so don’t worry too much about how dockerizing applications in another language will look like.</p>
<p>We’ll go through the basics of dockerizing a Go app with just Docker, images and containers, setting up multiple containers in one application with Docker Compose, and the constituent of a Docker Compose file.</p>
<p>By the end of this article, you'll have a basic understanding of what Docker is, what an image or container is, and how to orchestrate multiple, dependent containers with Docker Compose.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ol>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-what-is-docker">What is Docker</a>?</p>
</li>
<li><p><a href="#heading-how-to-install-docker">How to Install Docker</a></p>
</li>
<li><p><a href="#heading-what-is-a-dockerfile">What is a Dockerfile</a>?</p>
</li>
<li><p><a href="#heading-what-is-docker-compose">What is Docker Compose</a>?</p>
</li>
<li><p><a href="#heading-the-app-container">The app Container</a></p>
</li>
<li><p><a href="#heading-the-database-container">The database Container</a></p>
</li>
<li><p><a href="#heading-the-phpmyadmin-container">The phpMyAdmin Container</a></p>
</li>
<li><p><a href="#heading-running-everything-together">Running Everything Together</a></p>
</li>
<li><p><a href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>You don't need any prior knowledge of Docker to follow this tutorial. This article is written with a beginner POV in mind, so it's okay if the concept is new to you.</p>
<p>In order to be fully engaged and understand the Go coding examples used here, it'll be helpful if you have basic knowledge of Golang. If you already understand how to set up a Go application on your local computer, you're good to go. If not, you can check this article on <a href="https://www.freecodecamp.org/news/how-to-get-started-coding-in-golang/">how to get started coding in Go</a>.</p>
<h2 id="heading-what-is-docker">What is Docker?</h2>
<p>Imagine that you have a box. In that box, you put your code and everything that it needs to run. That is, the programming language it uses and any other external packages you need to install.</p>
<p>If someone needs your application, you can just hand them the box. You can also hand this box to as many people as you want. They don’t need to install the language or any other thing on their computer because everything they need is already inside the box. So, when they run the application, what they're actually doing is running an instance of that box.</p>
<p>The app is running within the box which is the standard environment. This means for everyone who got the box and “opened it”, the application is going to run the exact same way.</p>
<p>With the help of Docker, apps can run under the same conditions across different systems, and you avoid the problem of “it works on my machine”.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/3b2b169d-d882-48a8-88bf-233e4acec611.png" alt="A box containing dependencies, runtime, and source code that has arrows pointing to multiple developers" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>In technical Docker terms, this box is called an <strong>image</strong> and the running instance is called a <strong>container</strong>.</p>
<p>An image is a lightweight, standalone, executable package that includes everything needed to run a piece of software. That is, code, runtime, libraries, system tools, and even the operating system.</p>
<p>A container is simply a runnable instance of an image. This represents the execution environment for a specific application.</p>
<p>If all this seems to abstract, don’t worry. We’ll get our hands dirty in a little bit.</p>
<h2 id="heading-how-to-install-docker">How to Install Docker</h2>
<p>In order to install Docker, we're going to install Docker Desktop which comes bundled up with the Docker Engine. Docker Destop is a GUI for managing containers, and you'll see how useful it is in subsequent sections.</p>
<p>At the time of writing, I'm using WSL (Windows Sub-system for Linux). If you're doing the same, you'll need to take that into consideration before installing because Docker requires different installation prerequisites and steps for different operating systems.</p>
<p>To install Docker Desktop on WSL,</p>
<ol>
<li><p>Download and install the <a href="https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe?utm_source=docker&amp;utm_medium=webreferral&amp;utm_campaign=docs-driven-download-windows&amp;_gl=1*6mcgze*_gcl_au*MTg5NDEzMjg4NS4xNzc0ODU5MzQ3*_ga*MTkwMzQzNjIyLjE3NzQ4NTkzNDc.*_ga_XJWPQMJYHQ*czE3NzY2MzUyMzgkbzMkZzEkdDE3NzY2MzY3MDkkajYwJGwwJGgw">windows</a> <code>.exe</code> file</p>
</li>
<li><p>Start Docker Desktop from the Start Menu and navigate to settings</p>
</li>
<li><p>Select <strong>Use WSL 2 based engine</strong> from the <strong>General</strong> tab</p>
</li>
<li><p>Click on apply.</p>
</li>
</ol>
<p>That’s it for the WSL installation. If you are running another operating system, the <a href="https://docs.docker.com/get-started/introduction/get-docker-desktop/">official docs</a> have a list of installation options for you.</p>
<h2 id="heading-what-is-a-dockerfile">What is a Dockerfile?</h2>
<p>In order to build your box in the first place, Docker needs to follow a couple of outlined steps. It needs to know the dependencies, the run time, and it also needs to have the source code. All these steps we list in a Dockerfile.</p>
<p>Before we get down to cracking anything, let’s create a working directory and navigate into it.</p>
<pre><code class="language-bash">mkdir go_book_api &amp;&amp; cd go_book_api
</code></pre>
<p>To intialise the Go module in your application, run the following command:</p>
<pre><code class="language-bash">go mod init go_book_api
</code></pre>
<p>This creates a <code>go.mod</code> file to keep track of your project dependencies. In the root of the project, create a <code>cmd</code> directory, and a <code>main.go</code> file in it. This will serve as the entry point of your application. In the <code>main.go</code> file, you can have a simple print statement:</p>
<pre><code class="language-go">// cmd/main.go
package main

import "fmt"

func main() {
	fmt.Println("Look at me gooo!")
}
</code></pre>
<p>Now, go ahead and create a file in the root of your project and call it <code>Dockerfile</code>. This file has no extensions, but your system automatically knows that it's a file for Docker commands.</p>
<p>Go ahead and paste the following in that file, and then we'll go through each of them one by one:</p>
<pre><code class="language-bash"># base image
FROM golang:1.24

# define the working directory
WORKDIR /app

# copy the go.mod and go.sum so that the packages to be installed
# are known in the container. ./ here is the WORKDIR, /app
COPY go.mod ./

# command to install modules
RUN go mod download

# copy source code into working dir
COPY . .

# build
RUN CGO_ENABLED=0 GOOS=linux go build -o /docker-gs-ping ./cmd/main.go

# run the compiled binary when the container starts
CMD ["/docker-gs-ping"]
</code></pre>
<p>Most Dockerfiles begin with a base image, which is specified by the <code>FROM</code> keyword. A base image is a foundational template that provides minimal operating system environment, libraries, or dependencies required to build and run an application within a container.</p>
<p>In this case, your base image is <code>golang:1.24</code> . Your base image could have been an operating system like Linux. In that case. when you ship your code to someone who isn’t running a Linux operating system, they wouldn’t have to worry because they will be running the application in an environment that already has a minimal Linux OS. In the same light, someone who doesn’t have Go installed locally can run your application.</p>
<p>To figure out what base image to use when setting up your Dockerfile, you can always peruse the official Docker Hub repository for published images. For this case, you can check out base images that are officially published by Golang <a href="https://hub.docker.com/hardened-images/catalog/dhi/golang/images">here</a>.</p>
<p>The next step is to define a working directory. Inside your box, you have a filesystem that is almost identical to the ones you’d see on a Linux system. You have folders like <code>/app</code>, <code>/bin</code> , <code>/usr</code> , and <code>/var</code> , and so on. The working directory you've defined in this case is <code>/app</code>, and it's done with the <code>WORKDIR</code> command.</p>
<p>After setting a working directory, you want to copy the <code>go.mod</code> and <code>go.sum</code> file into it, so that Docker knows what dependencies to add into your box.</p>
<p>The <code>COPY</code> command in Docker takes at least two arguments: the source directory(ies), and then the destination directory. In this case, you want to copy <code>go.mod</code> and <code>go.sum</code> into the working directory of your box, <code>/app</code>.</p>
<p>In the box, you'll run a command that downloads and installs all the modules defined in the <code>go.mod</code> file. To run a command in Docker environment, use <code>RUN</code> and then the command, which is <code>go mod download</code> in this case.</p>
<p>The next step is to copy any source code you have into the working directory.</p>
<p>At this point, you have the dependencies and the source code. The last step is to build the Go application into a single executable file which can be run inside your environment (inside the container).</p>
<p>Within the container, you’ll have a compiled binary at <code>/docker-gs-ping</code>, which is as a result of the compilation of the code in your <code>main.go</code> file. The last step is a <code>RUN</code> command that just tells Docker to run the executable binary after building it. It’s a way of saying “once the container starts running, execute this binary file”.</p>
<p>With these steps, Docker will build an image (a box per our analogy) that you can run. To build the image, you can run this command in your terminal:</p>
<pre><code class="language-go">docker build -t go_book_api .
</code></pre>
<p>The <code>docker build</code> command tells Docker to build an image based on the steps in the Dockerfile. <code>-t</code> is the flag for a tag, and this helps you refer to the image later when running the container.</p>
<p>To accompany your tag, you'll provide a name to the image which is <code>go_book_api</code> in this case. The <code>.</code> at the end is important because it tells Docker where the Dockerfile in question is, and the files that you need to copy into your image.</p>
<p>This is what the building looks like in my IDE:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/361a805e-153d-4034-9d9a-d34c9015738a.png" alt="screenshot of IDE terminal showing a Docker image being built" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>If you check the Images tab on Docker Compose, you'll see that an image is built:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/b569277e-295b-4a3d-8e51-fb91dd7e3d91.png" alt="screenshot of a built container image on Docker Desktop" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>You can host this image on a public image repository platform like <a href="https://www.docker.com/products/docker-hub/">Docker Hub</a>, and share it with your friends. They can pull your image, set it up, and run your application even if they don’t have Go installed. All they need to do is get the container running.</p>
<p>If you click on the little play button to the far-right, you can spin up an instance of the image (a container).</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/09726294-be22-458d-b660-5f6d32102205.png" alt="screenshot of Docker Compose modal for running a new container" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>You can give a descriptive name to the container (Docker will generate a random one if you don’t), and click on the Run button. Once the container starts running, you're redirected to its log page.</p>
<p>Your container is up and running! You can see that this is a running instance of your application.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/3133c16c-0950-4f03-9502-ae6495535c13.png" alt="screenshot of a running docker container on Docker Compose" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<h2 id="heading-what-is-docker-compose">What is Docker Compose?</h2>
<p>If you were building a simple Go application that needed no external dependencies, the above set-up would be more than sufficient.</p>
<p>In our example here, the application is supposed to be for a book API, so you’d expect that we'd have some service like a database and a database administrator client like phpMyAdmin to visualize or tables.</p>
<p>To set all this up in one file would be a little complicated using just Docker. This is because Docker doesn't allow you to have one base image for Go, another base image for a database, and so on, in one file.</p>
<p>You could use the base image of a small operating system, and then run commands to manually install these other services as dependencies, but this method makes your application hard to maintain and scale. This method isn't advisable because if one dependency crashes, the whole application will collapse instantly.</p>
<p>To remedy this situation, Docker compose allows you to have multiple containers for your application that are connected together. Docker compose handles running the containers in the right order, allows one container to use a folder from another container, or even keep its data in another container – and so on.</p>
<p>Our previous analogy of boxes is the same, except with Docker Compose, we don’t necessarily have only one box anymore:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/2c890de4-8d5d-4457-a27a-fc441f58d794.png" alt="image of a box containing multiple containers that have arrows pointing to different developers" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>The point of Docker Compose is to help you orchestrate multiple images needed to run your application. You can think of it as connecting several boxes together.</p>
<p>Following the explanation from before, your application would be running in the <code>Go book api</code> container, the book data we'll create with your application would be stored in the <code>mysql</code> container which is the database, and you can visualize your database with phpMyadmin, which is in the <code>phpMyadmin</code> container.</p>
<p>To see this technically, create a <code>docker-compose.yml</code> file in the root of the project. The name of this file is important, and Docker Compose only accepts filenames such as <code>compose.yml</code> , <code>docker-compose.yml</code> , or <code>docker-compose.yaml</code>. The file extension hints that the commands are written in <code>yaml</code> which is a language mostly used for file configurations.</p>
<pre><code class="language-bash">services:
  app:
    depends_on:
      - database
    build: 
      context: .
    container_name: go_book_api
    hostname: go_book_api
    networks:
      - go_book_api_net
    ports:
      - 8080:8080
    env_file:
      - .env
    
  database:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
      MYSQL_DATABASE: ${DB_NAME}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USER}
    volumes:
      - mysql-go:/var/lib/mysql
    ports:
      - 3356:3306
    networks:
      - go_book_api_net

  phpmyadmin:
    image: phpmyadmin
    restart: always
    ports:
      - 9000:80
    environment:
      PMA_HOST: database
      PMA_ARBITRARY: 1
    depends_on:
      - database
    networks:
      - go_book_api_net

volumes:
  mysql-go:

networks:
  go_book_api_net:
    driver: bridge
</code></pre>
<p>At the root level of the docker-compose file, you have <code>services</code> . These are all the containers that are your application needs to run, and in the context of Docker Compose, they're each regarded as a service.</p>
<h3 id="heading-the-app-container">The <code>app</code> Container</h3>
<pre><code class="language-bash"> app:
    depends_on:
      - database
    build: 
      context: .
    container_name: go_book_api
    hostname: go_book_api
    networks:
      - go_book_api_net
    ports:
      - 8080:8080
    env_file:
      - .env
</code></pre>
<p>The very first container is the <code>app</code> container, which is your Go application. Under the <code>app</code> container, you'll need to define a few parameters that this container also needs to run.</p>
<p>The <code>depends_on</code> attribute controls the start-up and shut-down order of services within a container. This ensures that if container A depends on container B to start, the container B should be started first so that container A can use it. In this case, the <code>database</code> container must be started before the <code>app</code> container. Note that this doesn't mean <code>app</code> will always wait for the <code>database</code> to be ready.</p>
<p>The next attribute which is <code>build</code> tells Docker Compose to build the Docker image from the local project. Since the Dockerfile for your application is in the root of your app, you'll specify the root path with the <code>context</code> attribute as <code>.</code> .</p>
<p>To give a specific name to your container, you'll use <code>container_name</code>. <code>hostname</code> is what other containers will use for communication.</p>
<p>Recall that the point of Docker Compose is to have multiple containers communicating with each other. They do this with the help of networks. So you'll create another attribute, <code>networks</code>, and give it a name, <code>go_book_api_net</code> . To every other container that you want to associate with this <code>app</code>, you're going to specify the same network.</p>
<p>The next attribute is <code>ports</code> . Your application is an API, which means it's running on a backend Go server. To access the API, you'll need to map a local port to a port on the container. You're mapping port <code>8080</code> on your computer to port <code>8080</code> in the container.</p>
<p>The <code>env_file</code> attribute just tells Docker Compose where to read environment variables from. In this case, you can create a <code>.env</code> file in the root of your project to store important variables that your container will need.</p>
<h3 id="heading-the-database-container">The <code>database</code> Container</h3>
<pre><code class="language-bash">  database:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
      MYSQL_DATABASE: ${DB_NAME}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USER}
    volumes:
      - mysql-go:/var/lib/mysql
    ports:
      - 3356:3306
    networks:
      - go_book_api_net
</code></pre>
<p>The second container is the <code>database</code> container. Note, that you can give whatever name you choose to your listed services, but giving your containers descriptive names is always a good convention to follow.</p>
<p>For your Go application database, you'll be working with a MySQL database in this case. Your application needs MySQL to run, so you must set it up as one of the services.</p>
<p>Remember that to build a container, you need a base image. Your base image in this case is <code>mysql:8.0</code> , as you've specified with the <code>image</code> property above. When trying to set up this container, Docker Compose knows to build your database container from this already existing official image.</p>
<p>If you’ve set up a database locally before, you know that configuration is a step you can’t skip. Every database you create needs a user, a password, and the database name. You can set these variables up in the <code>environment</code> property. Instead of hardcoding these values, you can set them up in a <code>.env</code> file, and reference the environmental variables as you've done here.</p>
<p>Database servers usually listen on specific ports for incoming connections, whether the database is running locally or remotely. Just as you specified for your <code>app</code> container, you can set a port for your database and map it to a corresponding port in the container. If you want to access the database locally, you'd do that on port <code>3356</code>, and all requests are forwarded to port <code>3306</code> in the database container.</p>
<p>Once your containers go functional and your application starts running, creating, and storing data in the database, you’ll realise that every time you stop and then restart your containers, you lose the data stored in the database.</p>
<p>To avoid this, you'll need to store your data outside the container. That way, you won't lose the contents of your database every time you stop running your containers.</p>
<p>This is what volumes are for. You can allocate a specific location outside the database container to store all that content. For your <code>volume</code> in this case, the storage location you specified is <code>mysql-go:/var/lib/mysql</code> .</p>
<p>Just as you set the network in your <code>app</code> container above to <code>go_book_api_net</code>, you'll specify the same network for this database container. Since you want the containers to communicate with each other, it makes sense that they're within the same network.</p>
<h3 id="heading-the-phpmyadmin-container">The <code>phpMyAdmin</code> Container</h3>
<p>The last container or last service you need (but that is optional) to configure in this case is the phpMyAdmin container. I find it easier having a database client because it lets me easily see the structure and content of my database.</p>
<pre><code class="language-bash"> phpmyadmin:
    image: phpmyadmin
    restart: always
    ports:
      - 9000:80
    environment:
      PMA_HOST: database
      PMA_ARBITRARY: 1
    depends_on:
      - database
    networks:
      - go_book_api_net
</code></pre>
<p>The process is almost the same as the previous containers you've configured. You'll start by pulling the official <code>phpmyadmin</code> image from Docker so that your container is built on it.</p>
<p>The <code>restart</code> option here is just so that if you stop and restart the container, phpMyAdmin automatically reloads again.</p>
<p>On the host machine, which is your local environment, you can have access to this service via port <code>9000</code> and it maps to port <code>80</code> in the container.</p>
<p>As for the <code>environment</code> , <code>PMA_HOST</code> tells phpMyAdmin to connect to a host called <code>database</code> (which is your database container). This works because both containers are on the same network, as you can see in the <code>networks</code> attribute. <code>PMA_ARBITRARY</code> is used so that if you decide to connect to another host (say, you set up a another database in future and still wish to connect via phpMyAdmin), you can do that via the UI.</p>
<p>Your database client depends on the <code>database</code> container, and so you need to specify that in <code>depends_on</code>:</p>
<pre><code class="language-bash">volumes:
  mysql-go:

networks:
  go_book_api_net:
    driver: bridge
</code></pre>
<p>The final section of your Docker Compose file is where you declared named values for the volume and network you've used in setting up your containers.</p>
<p>For the <code>volumes</code>, you'll declare a value called <code>mysql-go</code>. To the container where you want to attach this volume, you'll assign a specific storage location. You can see this in use in the database container.</p>
<pre><code class="language-bash"> volumes:
      - mysql-go:/var/lib/mysql
</code></pre>
<p>The same concept follows for the network. You have a named network called <code>go_book_api_net</code> that every container within this same network can use. The <code>driver</code> option is used here to specify the network type, and <code>bridge</code> is used for private internal networks.</p>
<h3 id="heading-running-everything-together">Running Everything Together</h3>
<p>Before Docker Compose, you had one Dockerfile that built a single container for your Go application. With Docker Compose, You’re gonna be building three containers (your application container, the database, and phpMyAdmin), and orchestrating them to work together as one single application.</p>
<p>You can push all this to a platform like GitHub, and someone can clone, start, and run the application without having any of these services (MySQL or PhpMyAdmin) installed locally on their computer. But they do need to have Docker installed.</p>
<p>To build your containers all together, you can use the command <code>docker compose build</code>:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/0040fbdc-c541-494f-af9b-664d6a00bc17.png" alt="screenshot of IDE terminal showing build for an image" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>If you check your Docker Compose UI again, we see that a new image has been built, and it corresponds to the app service</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/736be9be-feb1-4888-8d15-c818e4683f4b.png" alt="screenshot of a built image on Docker Desktop" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>To start running the containers, you can use the command <code>docker compose up</code>:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/8ba14bb9-77d5-48a1-b574-54a848f54b1e.png" alt="a screenshot of running containers in terminal IDE" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>If you navigate to the container tab of Docker Compose, you can see that your containers are up and running:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/82e3d54d-bfec-4cea-806a-c52846a3e077.png" alt="A screenshot of running containers on Docker Desktop" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>The main app service, <code>go_book_api</code>, isn’t running because when you run your image, your binary runs and exits almost immediately.</p>
<p>In your <code>main.go</code>, let’s rewrite the code to set up a minimal HTTP handler function that listens on port <code>8080</code>:</p>
<pre><code class="language-go">// cmd/main.go
package main

import (
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	})

	log.Println("listening on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}
</code></pre>
<p>If you’re new to Go, don’t let the code above bother you too much. All it does it set up a <code>health</code> endpoint with an associated handler function that listens on a port (<code>8080</code> in this case) and prints “ok”.</p>
<p>In your <code>Dockerfile</code>, let’s add a command to execute the created binary when the container starts:</p>
<pre><code class="language-go"># run the compiled binary when the container starts
CMD ["/docker-gs-ping"]
</code></pre>
<p>After adding this, you'll need to rebuild the containers and start them again. You can see that all containers are running now:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/3ddf3e15-87b8-4978-851f-d6179e323166.png" alt="A screenshot of running containers on Docker Desktop" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>If you click on the <code>go_book_api</code> container, you can see that your server is running on port <code>8080</code> as configured:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/ddd07614-eb53-4bfc-b088-e824f651ef6c.png" alt="A screenshot of a running container on Docker Desktop" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Since your app is running on port <code>8080</code> and you have a <code>/health</code> endpoint set up for it, you can actually visit that endpoint in a browser to see the output “ok”.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/39a1ea3e-7cbf-4d46-9bbe-bf8053d48586.png" alt="an image of health endpoint showing ok response on the browser" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Also, if you click on the exposed <code>phpmyadmin</code> port, you can access the database client locally on port <code>9000</code>. Based on the environment variables set up in the <code>.env</code> file, you can log in.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/8d7de244-7268-4d17-a779-785feae389c4.png" alt="screenshot of browser with phpMyAdmin login form" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Another interesting thing to look for on Docker desktop is volumes. There is a volumes tab where you can see your configured <code>mysql-go</code> volume.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61d7e29f8d56921d07b9014e/66d1dde3-2fc1-48aa-b701-7504dba2007f.png" alt="a screenshot of the volumes tab on Docker Desktop" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>You can always open these volumes/containers on the docker GUI, go through the files and logs, experiment with putting one container down and seeing how the others respond, and so on.</p>
<p>After this entire setup, what do you notice? You didn’t have to install Go, MySQL, or phpMyAdmin locally. You only used officially published base images to orchestrate a full application. That's the magic of Docker.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Docker can be very abstract at the beginning, but understanding the fundamental purpose behind it makes everything much clearer.</p>
<p>In this article, you've learned what Docker is, how to containerize a basic Go application, and how to manage multiple containers with Docker Compose.</p>
<p>If you have trouble wrapping your head around why or how the Dockerfile is set up in the order that it is, my advice is not to get too stuck figuring it out on your own. As a Docker beginner, I realised that it’s easier if you imagine it as creating a recipe. If you try to build an image and it fails, you know there’s a step that you’re skipping.</p>
<p>The <a href="https://www.docker.com/">official docker documentation</a> has amazing resources if you want to understand Docker further than this tutorial. I encourage you to do so because this article only scratches the surface of the amazing things you can achieve with containerization.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Get Started Coding in Golang ]]>
                </title>
                <description>
                    <![CDATA[ In the world of Software Engineering, there are plenty of programming languages to learn. And there are both low-level and high-level options. I’ve tried my hand at a few of them, and the one language ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-started-coding-in-golang/</link>
                <guid isPermaLink="false">69b2e2251be92d8f177786a8</guid>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Thu, 12 Mar 2026 15:56:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/a429db13-593a-4afe-be02-2c94ae1f246f.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the world of Software Engineering, there are plenty of programming languages to learn. And there are both low-level and high-level options.</p>
<p>I’ve tried my hand at a few of them, and the one language that feels like it touches both worlds is Golang – popularly known as Go. Although Go is a high-level language, it has pretty amazing performance that brings it close to the low-level edge.</p>
<p>Go is a fast, statically typed programming language. Types are declared at compile time, and you don’t need to run the code before catching errors. It’s also a general-purpose language that you can use for backend, cloud, servers, and more.</p>
<p>Go has built-in testing support, so you don’t need to install extra testing libraries. Go also has some features of object-oriented languages, but in its own way. It mirrors some OOP concepts, but also uses concepts like interfaces, structs, and so on.</p>
<p>In this tutorial, we're going to be looking at a few basic concepts you need to know when getting started in any programming language. A few of them are generic to many programming languages, but some of them are concepts specific to the Go programming language. We'll take a look at:</p>
<ul>
<li><p>Variables</p>
</li>
<li><p>Formatting strings</p>
</li>
<li><p>Arrays and slices</p>
</li>
<li><p>Loops</p>
</li>
<li><p>Functions</p>
</li>
<li><p>Maps</p>
</li>
<li><p>Structs, and</p>
</li>
<li><p>Package scope</p>
</li>
</ul>
<p>By the end of the article, you'll be grounded in the pure basics of Go, and we'll run a few examples to see how these work on the command line.</p>
<h3 id="heading-what-well-cover">What we'll cover:</h3>
<ol>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-how-to-install-go">How to Install Go</a></p>
</li>
<li><p><a href="#heading-how-to-write-your-first-go-program">How to Write Your First Go Program</a></p>
</li>
<li><p><a href="#heading-how-to-work-with-variables-and-numbers-in-go">How to Work with Variables and Numbers in Go</a></p>
</li>
<li><p><a href="#heading-how-to-format-strings-in-go">How to Format Strings in Go</a></p>
</li>
<li><p><a href="#heading-how-to-work-with-arrays-and-slices-in-go">How to Work with Arrays and Slices in Go</a></p>
</li>
<li><p><a href="#heading-how-to-work-with-loops-in-go">How to Work with Loops in Go</a></p>
</li>
<li><p><a href="#heading-how-to-work-with-functions-in-go">How to Work with Functions in Go</a></p>
</li>
<li><p><a href="#heading-how-to-work-with-maps-in-go">How to Work with Maps in Go</a></p>
</li>
<li><p><a href="#heading-how-to-work-with-structs-in-go">How to Work with Structs in Go</a></p>
</li>
<li><p><a href="#heading-package-scope-in-go">Package Scope in Go</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, it’ll be helpful if you know the basics of any programming language, such as variables, data types, and data structures. I’ll assume that you’ve worked with at least one programming language before.</p>
<h2 id="heading-how-to-install-go">How to Install Go</h2>
<p>To install Go, head to <a href="http://golang.org/">golang.org</a>. Depending on what OS you are running, the documentation provides different installation options.</p>
<p>In my case, I’m using <strong>WSL</strong> (Windows Subsystem for Linux) with Ubuntu, so I’ll install Go inside that environment.</p>
<p>First, update your package list:</p>
<pre><code class="language-plaintext">sudo apt update
sudo apt upgrade -y
</code></pre>
<p>Next, install a tool to download files from the internet. We’ll use <strong>wget</strong>:</p>
<pre><code class="language-plaintext">sudo apt install -y wget
</code></pre>
<p>Now download the Go binary package:</p>
<pre><code class="language-plaintext">wget https://dl.google.com/go/go1.24.2.linux-amd64.tar.gz
</code></pre>
<p>Extract the archive to <code>/usr/local</code>:</p>
<pre><code class="language-plaintext">sudo tar -C /usr/local -xzf go1.24.2.linux-amd64.tar.gz
</code></pre>
<p>After installing Go, add the Go binary directory to your <strong>PATH</strong> so the <code>go</code> command is available in the terminal:</p>
<pre><code class="language-ruby">export PATH=$PATH:/usr/local/go/bin
</code></pre>
<p>You can make this change permanent by adding the line above to your <code>~/.bashrc</code> or <code>~/.profile</code>.</p>
<p>To confirm Go was installed successfully, run:</p>
<pre><code class="language-go">go version
</code></pre>
<p>You should see the installed Go version printed in the terminal.</p>
<p>If you use VS Code, you can also install the Go extension for syntax highlighting.</p>
<h2 id="heading-how-to-write-your-first-go-program">How to Write Your First Go Program</h2>
<p>Before we get into writing our first program, we need to establish how Go puts its code together. In Go, every file or code is part of a package.</p>
<p>In this example, we’ll create a file called <code>main.go</code>. The name isn’t special to Go, but it’s a common convention for the file that contains the program’s entry point.</p>
<pre><code class="language-go">package main

import "fmt"

func main() {
	fmt.Println("Hello, ninjas")
}
</code></pre>
<p>This is the most important file in our project. We'll begin by making the code we’ll write in this file part of a package we call <code>main</code>.</p>
<p>The <code>fmt</code> import is a package from the Go standard library. <code>fmt</code> is for formatting strings and outputting to the console. Notice that the <code>Println</code> function starts with a capital letter, because within the <code>fmt</code> package, the method is exported. Variables or methods that are exported in Go should begin with capital letters. The <code>Println</code> prints a line to the console.</p>
<p>The <code>main</code> function serves as the entry point of a Go program. A compiled Go program must contain <strong>exactly one</strong> <code>main</code> <strong>function inside a</strong> <code>package main</code>. (A larger codebase can still contain multiple programs, each in its own directory with its own <code>package main</code>.)</p>
<p>So when you run a Go program, the Go toolchain builds all files in the same package together and then starts execution from the <code>main()</code> function. The filename <code>main.go</code> does not determine execution order – it’s simply a common naming convention.</p>
<p>Unlike other custom packages, which are used to bundle application logic into libraries or reusable code, the <code>main</code> package is used to specify that a program is a standalone executable.</p>
<p>To run the code, you can simply type <code>go run main.go</code>, specifying the Go file that we want to execute.</p>
<pre><code class="language-go">Hello, ninjas
</code></pre>
<h2 id="heading-how-to-work-with-variables-and-numbers-in-go">How to Work with Variables and Numbers in Go</h2>
<h3 id="heading-how-to-declare-variables">How to Declare Variables</h3>
<p>A variable is just a store for data. Go does not allow unused local variables. If you declare a variable inside a function and never use it, the compiler will raise an error. This helps prevent cluttered code and unused definitions.</p>
<p>Let’s see how to declare variables in Go by declaring a string</p>
<pre><code class="language-go">package main

import "fmt"

func main() {

	// strings
	var nameOne string = "emy"

	fmt.Println(nameOne)
}
</code></pre>
<p>Because Go is a statically typed language, every variable must have a type at compile time. Here, we have a variable <code>nameOne</code>, it’s type, and then an initial value assigned to it.</p>
<p>But what if we don't want to state the variable type ourselves? Fortunately, Go lets us define variables without a type stated at compile time</p>
<pre><code class="language-go">// strings
var nameOne string = "emy"
var nameTwo = "blessing"
var nameThree string
</code></pre>
<p>For <code>nameTwo</code>, we don’t need to explicitly state the type because Go directly infers it. If you hover above the variable, you can see that Go already tells you the type. The third variable, <code>nameThree</code>, has no value assigned to it just yet. We’ve only just declared it.</p>
<p>If you log the output to the console, you can see <code>nameOne</code> and <code>nameTwo</code> displayed, but you can’t see <code>nameThree</code>. It’s also logged, you just can’t see it because it has no value.</p>
<pre><code class="language-go">emy blessing 
</code></pre>
<p>There’s an even shorter and simpler way to declare variables in Go:</p>
<pre><code class="language-go">nameFour := "peaches"
</code></pre>
<p>Here, Go also infers the variable type based on the value assigned to it. Notice how we also didn’t use the <code>var</code> keyword. You can use this method inside any function, not just in <code>main</code>. Just keep in mind that you can't use this method of declaring variables when reassigning or updating a variable, declaring constants, or declaring safe types.</p>
<h3 id="heading-how-to-declare-integers">How to Declare Integers</h3>
<p>When it comes to declaring integers, we pretty much use the same technique as above:</p>
<pre><code class="language-go">var ageOne int = 20
var ageTwo = 30
ageThree := 40

fmt.Println(ageOne, ageTwo, ageThree)
</code></pre>
<p>When declaring integers, we can specify the amount of memory or the bit size we want an integer to have. We can declare the integer as <code>int8</code>, <code>int16</code>, or <code>int64</code>.</p>
<p>Each of these memory sizes can hold a specific range of numbers. <code>int8</code>, for example, can only hold integers between -128 and 127. Anything bigger than that would throw an error:</p>
<pre><code class="language-go">// bits and memory
	var numOne int8 = 25
	var numTwo int8 = -128

	var numThree int8 = 129 // will throw an error
</code></pre>
<p>Another type of integer in Go is the unsigned integer, declared with <code>uint</code>. You’ll use this to declare only positive integers – you can’t use it to store negative values.</p>
<p><code>uint</code>, just like the <code>int</code> type, can also be associated with bit sizes. You could have a <code>uint8</code>, <code>uint16</code>, and so on. But the ranges for these are different. You can check the complete list of bit sizes for the integer type and their ranges on this <a href="https://go.dev/ref/spec#Numeric_types">Go page</a>.</p>
<p><code>int</code> is specifically used to declare whole integer numbers. To declare decimal numbers, you can use a float. The concept is the same with <code>int</code>, where you can have floats with different bit sizes. But you can only have <code>float32</code> and <code>float64</code>, where the latter can store bigger numbers than the former.</p>
<h2 id="heading-how-to-format-strings-in-go">How to Format Strings in Go</h2>
<h3 id="heading-printing-strings-to-the-console">Printing Strings to the Console</h3>
<p>We came across the <code>fmt</code> package at the beginning of the article. Let’s go through some of the methods this package exposes.</p>
<p>First, we have the <code>Print()</code> method which logs some output the console. This method is used to log simple strings to the command line when we just want to see the output of something, and don’t really care about the readability.</p>
<p>If we have two simple strings as shown below;</p>
<pre><code class="language-go">// Print
fmt.Print("Hello, ")
fmt.Print("world!")

// Output: Hello, world!
</code></pre>
<p>You can see that the code above is not on separate lines, and this is the downside of the <code>Print</code> function. If we had multiple things to log to the command line, this function would just lump them together and readability could suffer.</p>
<p>But we can enforce a new line with <code>Print()</code> by using the escape character <code>\\n</code> .</p>
<pre><code class="language-go">fmt.Print("hello! \\n")
fmt.Print("new line \\n")

/*
	hello! 
	new line 
*/
</code></pre>
<p>Using escape characters throughout our code can get tiring very quickly. Luckily for us, Go has a function that helps us achieve the perfect separate line formatting we are looking for. We don’t need to use escape characters when we use <code>Println</code> .</p>
<pre><code class="language-go">fmt.Println("Hello, friends.")
fmt.Println("How are you?")

/*
	Hello, friends.
	How are you?
*/
</code></pre>
<h3 id="heading-format-specifiers">Format Specifiers</h3>
<p>Sometimes, you may want to log a string to the console, but you may also want to have variables within that string. This is called a formatted string, and we can achieve this with the help of format specifiers. These format specifiers are reserved characters that Go uses at runtime to position variables within strings.</p>
<p>Let’s use a concrete example to see the concept better,</p>
<pre><code class="language-go">name := "Emy"
age := 27

fmt.Printf("my age is %v and my name is %v", age, name)

// Output: my age is Emy and my name is 27
</code></pre>
<p>The format specifier <code>%v</code> is the default format specifier that stands for variable. We can see that in the position of the format specifiers, Go has placed the values of the arguments we passed to the <code>Printf</code> (<code>age</code> and <code>name</code>). It's important to note that the order in which we pass these arguments is important.</p>
<p>As we just saw above, the output of this code:</p>
<pre><code class="language-go">name := "Emy"
age := 27

fmt.Printf("my age is %v and my name is %v", name, age)
</code></pre>
<p>Would be <code>my age is Emy and my name is 27</code>. The order in which we pass the arguments is the same way in which the compiler will replace the format specifier within our string.</p>
<p>Something new you might also notice is that we didn't use <code>Print</code> or <code>Println</code> in this code like we did before. When working with formatted directives, Go puts the functions <code>Printf</code>, <code>Sprintf</code>, and <code>Appendf</code> at our disposal.</p>
<ul>
<li><p><code>Printf</code> directs the output to the console, as we’ve seen.</p>
</li>
<li><p>With <code>Sprintf</code>, we don't direct the output to the command line, but we can store it in a variable and then use that variable somewhere else in our code.</p>
</li>
<li><p>It gets a little more complex when working with <code>Appendf</code>, which formats according to a format specifier and appends the result to a byte slice (bytes are a bit out of the scope of this article, so we won’t dwell on them).</p>
</li>
</ul>
<p>Besides the <code>%v</code> format specifier, we can also use <code>%q</code> if we want the embedded variable to have quotes around it.</p>
<pre><code class="language-go">// strings
	name := "Emy"

	fmt.Printf("my name is %q", name)

// output: my name is "Emy"
</code></pre>
<p>This will work for the <code>name</code> variable, but not really for the <code>age</code> because it’s an integer.</p>
<pre><code class="language-go">name := "Emy"
age := 27

fmt.Printf("my age is %q and my name is %q", name, age)

//Output: my age is '\\\\x1b' and my name is "Emy"
</code></pre>
<p>We also have the <code>%T</code> specifier, which is used to output the type of a variable.</p>
<p>If we wanted to get the type of <code>age</code>:</p>
<pre><code class="language-go">fmt.Printf("This is a variable of type %T", age)
</code></pre>
<p>The output of this would be:</p>
<pre><code class="language-go">This is a variable of type int
</code></pre>
<p>You can check out other format specifiers on the official <a href="https://pkg.go.dev/fmt">fmt package page</a>.</p>
<h2 id="heading-how-to-work-with-arrays-and-slices-in-go">How to Work with Arrays and Slices in Go</h2>
<h3 id="heading-arrays-in-go">Arrays in Go</h3>
<p>Arrays in Go are a little bit of a mouthful. Let’s take a look at how to define an array:</p>
<pre><code class="language-go">var ages = [3]int{20, 25, 30}
</code></pre>
<p>In this code, we have the variable name on the left side as is typical. On the right side, we have <code>[3]</code> to specify the size of the array, the type as <code>int</code> , and the values for the array inside the squiggly braces.</p>
<p>Once we declare an array, we can never change its size. This is kind of a bummer if you ask me, because during coding, you don’t always know the size of an array when you declare it (more on this below when we talk about slices).</p>
<p>Arrays in Go also can’t contain multiple types. The array we declared above can’t also contain a string, for example.</p>
<p>If we log the array to the console alongside its length with <code>fmt.Println(ages, len(ages))</code>, on the console we get:</p>
<pre><code class="language-go">[20 25 30] 3
</code></pre>
<h3 id="heading-slices-in-go">Slices in Go</h3>
<p>If you need to define an array where you don’t know or don’t want to specify the size during declaration, you can use a slice. Slices are abstractions of arrays, and are more flexible than arrays because they have dynamic sizing.</p>
<pre><code class="language-go">var scores = []int{100, 50, 60} // we don't specify the size
scores[2] = 25 // to update a value
scores = append(scores, 50) // returns a new scores slice with 50 appended to it  (you cannot do this with arrays)
fmt.Println(scores, len(scores)) // [100 50 60 50] 4
</code></pre>
<p>An important part of working with arrays, slices, or any data structures that store data is knowing how to get the elements we want. We may only want to grab data that belongs to a certain range, or data at certain positions, based on certain conditions, and so on.</p>
<p>When it comes to dealing with ranges, say you want to output the slice elements from position 1 (that is, <a href="https://en.wikipedia.org/wiki/Zero-based_numbering">index 0</a>, the first element) right up to the third position (index 2).</p>
<pre><code class="language-go">rangeOne := scores[0:3] // [100 50 60]
</code></pre>
<p>The range <code>scores[0:3]</code> indicates that the code should list the scores from index 0 up to index 3 minus 1. So it doesn’t include the element at index 3.</p>
<p>If you wanted to log from index 2 in the slice right up to the end, for example, you’d write <code>scores[2:]</code> . Similarly, you could log from the beginning of the slice up to and excluding some position (in this case, index 3) like so, <code>scores[:3]</code> .</p>
<h2 id="heading-how-to-work-with-loops-in-go">How to Work with Loops in Go</h2>
<h3 id="heading-how-to-iterate-loops">How to Iterate Loops</h3>
<p>Loops in Go are similar to loops in other programming languages. The difference is that Go focuses on the <code>for</code> loop and doesn’t really dwell on <code>while</code>, <code>do-while</code>, or <code>for-each</code>.</p>
<pre><code class="language-go">x := 0
for x &lt; 5 {
	fmt.Println("the value of x is", x)
	x++
}
</code></pre>
<p>The loop above is straightforward and just prints the value of <code>x</code> from 0 to 4.</p>
<p>To create a loop that uses an iterator, you can write this:</p>
<pre><code class="language-go">for i := 0; i &lt; 5; i++ {
	fmt.Println("value of i is", i)
}
    /*
		value of i is 0
		value of i is 1
		value of i is 2
		value of i is 3
		value of i is 4
	*/
</code></pre>
<p>It does pretty much the same thing as the loop above it, but we declared the iterator, it’s range, and we iterate over it in the same expression.</p>
<p>What if you wanted to iterate or loop over a slice, for example? We can also use an iterator to achieve this as we have above.</p>
<pre><code class="language-go">names := []string{"emy", "ble", "winkii"}

for i := 0; i &lt; len(names); i++ {
		fmt.Println(names[i])
}
</code></pre>
<h3 id="heading-how-to-use-the-range-keyword">How to Use the <code>range</code> Keyword</h3>
<p>Another interesting keyword related to iterations is <code>range</code>. Using the <code>range</code> keyword, you can use loops to perform actions on elements in a slice. <code>range</code> provides the index and value of the element in a slice, and allows you to access those within the loop.</p>
<pre><code class="language-go">for index, value := range names {
		fmt.Printf("the position of %v is %v \\\\n", value, index)
	}
</code></pre>
<p>What if you didn’t want to use the index and only the value? Well, <code>range</code> requires that you define an index and a value. So if you rewrite your loop like this:</p>
<pre><code class="language-go">for index, value := range names {
		fmt.Printf("the value is %v \\\\n", value)
}
</code></pre>
<p>Go is going to throw an error because you’re declaring the <code>index</code> but not using it.</p>
<p>Luckily, there’s a way to bypass this, and Go does it neatly using the blank identifier, <code>_</code>. We use this identifier when a method or function expects that you define a return value that you don't need.</p>
<pre><code class="language-go">for _, value := range names {
		fmt.Printf("the value is %v \\\\n", value)
}
</code></pre>
<p>You could apply the same strategy if you wanted only the index, but not the value.</p>
<pre><code class="language-go">for index, _ := range names {
		fmt.Printf("the index is %v \\\\n", index)
}
</code></pre>
<h2 id="heading-how-to-work-with-functions-in-go">How to Work with Functions in Go</h2>
<p>A function is a reusable block of code. Functions in Go are mostly created outside the <code>main</code> function. This way, other files can access and use them.</p>
<pre><code class="language-go">package main

import (
	"fmt"
)

func sayGreeting(n string){
	fmt.Printf("Good morning")
}

func main() {
	sayGreeting("emy")
}
</code></pre>
<p>Go also allows you to pass functions as parameters to other functions.</p>
<pre><code class="language-go">func cycleNames(n []string, f func(string)) {
	for _, value := range n {
		f(value)
	}
}
</code></pre>
<p>The function above takes a slice and a function as parameters. The function passed as a parameter in turn takes a string. You could pass a slice of names alongside the greeting function, so that for each name in the slice, you run the greeting function to print a greeting for that name.</p>
<pre><code class="language-go">func main(){
	cycleNames([]string{"emy", "pearl"}, sayGreeting)
}
</code></pre>
<p>When passing the <code>sayGreeting</code> function as a parameter, you don’t invoke it immediately because that’s done within the <code>cycleNames</code> function already. You only pass its reference.</p>
<h3 id="heading-functions-with-return-values">Functions with <code>return</code> Values</h3>
<p>Functions may also need to have a return value. So, how does Go handle that? Let’s see a small example:</p>
<pre><code class="language-go">package main

import "fmt"

func sayHello(name string) string {
	fmt.Printf("Hello %v", name)
	return name
}

func main() {
	sayHello("Emy")
}

// Output: Hello Emy
</code></pre>
<p>Just like with variables, we must specify the data type for every function parameter, and also specify the data type of the expected return value. In the example above, our function <code>sayHello</code> takes a string and returns a string.</p>
<p>Functions can also have multiple return values, as we see in the example below:</p>
<pre><code class="language-jsx">package main

import "fmt"

func sayHello(name string, age int) (string, int) {
	fmt.Printf("Hello %v, you are %v years old", name, age)
	return name, age
}

func main() {
	sayHello("Emy", 27)
}
</code></pre>
<p>Just like the previous example, we have to specify data types for our function parameters and return values.</p>
<h2 id="heading-how-to-work-with-maps-in-go">How to Work with Maps in Go</h2>
<p>A map in Go is a built-in, unordered collection of unique key-value pairs, similar to dictionaries in Python or hash tables in other languages. Maps provide fast lookups, insertions, and deletions.</p>
<p>With maps, all the keys must be of the same data type, and so must the values. If one key is a string, then all the other keys must also be strings. The same concept applies for values.</p>
<pre><code class="language-go">scores := map[string]float64{
		"maths":           20,
		"english":         15,
		"french":          14,
		"spanish":         12,
	}

	fmt.Println(scores)
	fmt.Println(scores["maths"])

	/*
	map[english:15 french:14 maths:20 spanish:12]
	20
	*/
</code></pre>
<p>You can also loop through maps to get their keys and corresponding values:</p>
<pre><code class="language-go">// loops maps
	for key, value := range scores {
		fmt.Println(key, "-", value)
	}

	/*
	french - 14
	spanish - 12
	maths - 20
	english - 15
	*/
</code></pre>
<p>When it comes to mutating maps, it's important to note that maps are reference types. Reference types are types whose variables don’t store the actual data, but rather an internal pointer to the actual data. This means that if the same data is assigned to multiple variables, when one instance gets modified, the original gets modified as well.</p>
<p>Let’s understand this with an example;</p>
<pre><code class="language-go">package main

import "fmt"

func main() {
	scores := map[string]float64{
		"maths":   20,
		"english": 15,
		"french":  14,
		"spanish": 12,
	}

	scores2 := scores

	scores2["maths"] = 15
	fmt.Println(scores)
}

// Output: map[english:15 french:14 maths:15 spanish:12]
</code></pre>
<p>If you check out the output, you can see that we modified the math score for <code>scores2</code>, but that modification also affected the original map, <code>scores</code> .</p>
<h2 id="heading-how-to-work-with-structs-in-go">How to Work with Structs in Go</h2>
<p>A big downside of using maps is that we can only store one data type for keys and one data type for values. This feels restrictive. We need a data structure that lets us store a collection of data with different data types. This is where structs (or structures) come in.</p>
<p>Let’s look at an example:</p>
<pre><code class="language-go">type Book struct {
	ID     uint
	Title  string
	Author string
	Year   int
	UserID uint
}
</code></pre>
<p>Here we have a Book struct. Structs are defined by specifying the key of the data you want the struct to carry, and the data type associated with that key.</p>
<pre><code class="language-go">package main

import "fmt"

type Book struct {
	ID     uint
	Title  string
	Author string
	Year   int
    UserID uint
}

func main() {

	var book1 Book

	book1 = Book{1, "Jane Eyre", "Jane Austen", 1990, 6}

	fmt.Println(book1)
}
</code></pre>
<p>We initialised the <code>Book</code> struct by providing it with the data we stated in its definition. If you check the output of this (and ignore that Jane Austen didn’t write Jane Eyre, of course):</p>
<pre><code class="language-go">{1 Jane Eyre Jane Austen 1990 6}
</code></pre>
<p>If you look closely, structs resemble classes from the OOP languages. They define properties (just as with methods, properties starting with a capital letter are public and can be exported), and these properties can be used within methods or functions. The difference comes at the level of inheritance, because structs, unlike classes, support only composition and not inheritance.</p>
<p>We can also individually modify the properties of a struct using dot notation, like so:</p>
<pre><code class="language-go">	var book1 Book

	book1 = Book{1, "Jane Eyre", "Jane Austen", 1990, 6}

	book1.Title = "Things Fall Apart"
	book1.Author = "Chinua Achebe"

	fmt.Println(book1)
</code></pre>
<p>If you check the output again, you can see that what you initialised the struct to contain has been modified at the level of the <code>Title</code> and <code>Author</code>.</p>
<pre><code class="language-go">{1 Things Fall Apart Chinua Achebe 1990 6}
</code></pre>
<p>When working with real systems, structs come in very handy when creating models or designing the structure of data you want to store in your database.</p>
<h2 id="heading-package-scope-in-go">Package Scope in Go</h2>
<h3 id="heading-importing-functions-within-the-same-package">Importing Functions Within the Same Package</h3>
<p>When coding real applications, it's uncommon to write all our application files in one file. This can get messy very quickly. Normally, we would write a function in one file and then call it from another file.</p>
<p>In this case, you can declare variables and functions in other files and still use them in your entry point file. Say you create another <code>greetings.go</code> file and declared some variable and method in it like this:</p>
<pre><code class="language-go">// greetings.go
package main

import "fmt"

var points = []int{20, 90, 100, 45, 70}

func sayHello(n string) {
	fmt.Println("Hello", n)
}
</code></pre>
<p>Notice that there is no <code>func main()</code> in this file (remember that we can have only one throughout our application).</p>
<p>Now, in your <code>main.go</code> file, you can reference the <code>sayHello()</code> function and <code>points</code> variable you created.</p>
<pre><code class="language-go">// main.go
func main() {
	sayHello("emy")

	for _, v := range points {
		fmt.Println(v)
	}
}
</code></pre>
<p>To run this, you’ll need to have both files running at the same time. That is:</p>
<pre><code class="language-bash">go run main.go greetings.go
</code></pre>
<p>You can see that the output is the result of running the <code>sayHello()</code> function and looping over the <code>points</code> slice.</p>
<p>You could also define functions and variables in the <code>main.go</code> file and pass them to the <code>greetings.go</code> file. Remember that all these functions and variables passed between files must be declared outside the <code>main()</code> function.</p>
<h3 id="heading-importing-functions-across-different-packages">Importing Functions Across Different Packages</h3>
<p>What if your application has, say, 100 files? Will you run all those files simultaneously? No, you won't. Since our Go code can be organised in packages, we can import a function from one package within another package. Let’s rewrite our code above, but using two different packages.</p>
<p>In our <code>greetings.go</code> file, we now have our code under a new package, <code>greetings</code> , and our <code>SayHello</code> function begins with a capital letter so that other files can import and use it.</p>
<pre><code class="language-jsx">// greetings.go
package greetings

import "fmt"

var Points = []int{20, 90, 100, 45, 70}

func SayHello(n string) {
	fmt.Println("Hello", n)
}
</code></pre>
<p>In our <code>main.go</code> file,</p>
<pre><code class="language-jsx">// main.go
package main

import (
	"fmt"
	"greetings"
)

func main() {
	greetings.SayHello("emy")

	for _, v := range points {
		fmt.Println(v)
	}
}
</code></pre>
<p>As you can see, we’ve imported the <code>greetings</code> package we declared in another file, and we can access the <code>SayHello()</code> method from it with dot notation.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you’ve learned some key Go concepts. You’re now familiar with how variables, strings, arrays and slices, loops, functions, maps, structs, and package scope works in Go.</p>
<p>At this point, you should try to take that further by building something a little bigger so you can see just how powerful and amazing Golang is.</p>
<p>The official <a href="https://go.dev/tour/welcome/1">Tour of Go</a> website is also an amazing resource to reference if you want to explore these concepts a little deeper.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Practical Skills for Open Source Maintainers – How to Effectively Maintain OSS ]]>
                </title>
                <description>
                    <![CDATA[ Open source software is used by organizations large and small around the world. And it's become very popular in the tech industry. Many people want to be involved in this open side of tech, and luckily there are many different ways to contribute. Sti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/practical-skills-for-open-source-maintainers/</link>
                <guid isPermaLink="false">66d4608d47a8245f78752aa1</guid>
                
                    <category>
                        <![CDATA[ Collaboration ]]>
                    </category>
                
                    <category>
                        <![CDATA[ community ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                    <category>
                        <![CDATA[ skills ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Mon, 14 Nov 2022 14:51:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/Purple-Minimal-We-Are-Hiring-Twitter-Post--9-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Open source software is used by organizations large and small around the world. And it's become very popular in the tech industry.</p>
<p>Many people want to be involved in this open side of tech, and luckily there are many different ways to contribute.</p>
<p>Still, open source can be scary at first sight. My first official contribution was during Hacktoberfest 2021, and even after that, it took me while to really feel welcome.</p>
<p>The open source community helped a ton, and it's the route I would advise any new techie to take – get involved with the community around a project you care about.</p>
<p>In addition to being a contributor – making updates to open source code bases, updating documentation, and so on – you can also eventually become a project maintainer. Maintainers are responsible for the thrill you experience when your pull requests get merged.</p>
<p>As daunting as it is to become a first time contributor, it is also quite scary becoming a first time maintainer. So in this article, I'll discuss some of the soft skills project maintainers should cultivate to be successful.</p>
<h2 id="heading-a-little-background">A Little Background</h2>
<p>After open sourcing a project very close to my heart, I was lucky enough to gain some much needed experience. I also held a Twitter space with some amazing folks, and they had much to share as well. Hence, this article.</p>
<p>I won't say I am an expert, but to successfully scale an open source project, no matter how big or small, there are certain skills you need to have. And some of these I didn't pick up until after I had been a maintainer for a while.</p>
<h2 id="heading-skills-you-need-to-maintain-an-open-source-project">Skills You Need to Maintain an Open Source Project</h2>
<h3 id="heading-develop-good-time-management-skills">Develop Good Time Management Skills</h3>
<p>On day one of releasing the project, my email was flooded with GitHub notifications.</p>
<p>I was happy people where checking the project out, but it was too much for me to handle. I was putting off work to attend to issues, assigning, labeling, merging pull requests, fixing conflicts... It quickly became too much to manage. I needed to allocate time and set boundaries.</p>
<p>If you are running a big project, notifications are probably nothing new. If you're running the project alone (like I was at that point), it is way worse.</p>
<p>Putting aside specific time to attend to GitHub tasks was the best way out. It could be in the morning before work, or after work, or only on weekends, depending on what works for you and the project.</p>
<h3 id="heading-be-patient">Be Patient</h3>
<p>I hear people advise contributors that they shouldn't spam maintainers if those maintainers can't attend to their issues/pull requests in time. This level of understanding should go both ways.</p>
<p>Contributors also have lives. If a contributor claims an issue, it is important to give them time to actually submit a pull request. Open source is fun (we've agreed on that already, but just for emphasis), but some people can only contribute in their spare time.</p>
<p>If a claimed issue is taking too long to address, a subtle reminder is fine. Constantly reminding a contributor that they need to submit a pull request could be off-putting, and it isn't a good look for you or your project.</p>
<p>On some rather large projects, however, a time frame is given to contributors who claim issues. I've seen cases where a contributor has about seven days to raise a pull request. While this is understandable because of the fast paced nature of these projects, I personally feel that it's too much pressure, especially for new contributors.</p>
<h3 id="heading-be-empathetic">Be Empathetic</h3>
<p>For me, this is the most important skill. I can remember my first open source contribution. The joy I felt when my pull request got merged and the immense support from the community were wonderful.</p>
<p>Think of this when you merge pull requests. It could be the contributor's first time too. I try to close off pull requests with a message other than just 'LGTM'. It can be as simple as throwing in a bomb emoji, and thanking them.</p>
<p>People come back to a place where they feel welcome.</p>
<h3 id="heading-be-firm">Be Firm</h3>
<p>This can be hard, but it's also important. You won't merge every pull request that is opened, and that's a fact. But abruptly closing off a pull request without justification isn't exactly good practice either.</p>
<p>If a pull request is too big, or it doesn't add to the project like you would've wanted, it is okay to close it. But do not be afraid to kindly explain to the contributor why it can't be merged. Don't leave a pull request open forever because you feel guilty about closing it.</p>
<p>People can be more understanding than you think if you give them simple common courtesy.</p>
<h3 id="heading-work-on-communication-skills">Work on Communication Skills</h3>
<p>Collaboration is the basic foundation of open source as a whole. And to collaborate effectively, you need to be a good communicator.</p>
<p>Having people come in and work with you on your project is cool and all – but if you can't properly communicate with these people, you'll end up with a closed open source project (if that makes sense).</p>
<p>Collaboration doesn't have to be you spinning up some huge discord server for the project. It could just be you sharing messages in your code reviews.</p>
<p>If the comment sections under your issues are too small, then GitHub has a discussion tab for each repository. This is a great place to spin up new ideas and start some great connections.</p>
<p>You never know whom you might meet!</p>
<h3 id="heading-listen-and-learn">Listen and Learn</h3>
<p>After open sourcing my app, I've probably learnt more React than I would've if I was watching tutorials and building in private.</p>
<p>Smart people will come along and open your eyes to ideas that you couldn't have thought of on your own. My project has improved so much, mainly because I wasn't afraid to try out new things.</p>
<p>The community wants to help – so let them.</p>
<h3 id="heading-cultivate-a-community-spirit">Cultivate a Community Spirit</h3>
<p>Someone recently reached out to me, saying they wanted to get involved in reviewing pull requests because it was fun. They aren't officially a maintainer, but I would like to think that they enjoy being a part of the project.</p>
<p>Building an open source project is a community effort. And as a maintainer, you will need that community spirit.</p>
<p>You need to be excited with what you do. Collaboration should be fun. You are happy that the contributor added something, but let them also be happy that they contributed.</p>
<p>People love good, honest feedback. And it also helps you build up your little community.</p>
<h3 id="heading-be-responsible">Be Responsible</h3>
<p>If the open source project is your idea, then you're the pioneer. If you decide to be the lead maintainer, be the lead maintainer. Be reliable, and most importantly, be present.</p>
<p>Even if you are a supporting maintainer for some big project, it is good to show that you know what you're doing and that you're committed to the project.</p>
<p>Some projects go stale because the maintainers stop responding to issues and pull requests. It's true that life catches up to us sometimes. If you decide to commit to a project, though, it's important to always show that the project is alive.</p>
<p>But how? Well, everything leads back to collaboration. Keep your collaborators involved and they'll help you out.</p>
<h3 id="heading-be-nice-and-welcoming">Be Nice and Welcoming</h3>
<p>People are coming from different backgrounds to check out your project. Whoever they are, they won't come back if their first experience was a mean maintainer, whose project had poor documentation.</p>
<p>No matter how easy you make things, expect questions. Be ready to answer these questions. Point people to the right resources, no matter how obvious the solution could be.</p>
<p>If a contributor is having a hard time, check your documentation. Most times, it's not them, it's us (pun intended). The README might've skipped some steps, or a screenshot wasn't clear enough. Instead of telling them off, point them in the right direction and update your docs if need be.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>All in all, being a maintainer is hard work. Whether you're going solo on your project, or working with other maintainers, the goal is the same: collaborating to build great products.</p>
<p>Projects with poorly structured management and responses are one of the main reasons some people feel discouraged when it comes to contributing to open source.</p>
<p>The skills I've covered here are mostly based on personal experience, but I hope they help anyone maintaining a project, or thinking of being an open source maintainer.</p>
<p>If you want to check out my open source project, you can do so <a target="_blank" href="https://github.com/Njong392/Abbreve">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the Rough Notation Library to Animate Your Website ]]>
                </title>
                <description>
                    <![CDATA[ I love animating websites. It's so fun when you just look at a site, and there are cool animations that make everything look pretty. Getting started with an animation library does not have to be hard. Anyone can add a bit of animation to their site r... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-add-animation-to-your-site-with-rough-notation/</link>
                <guid isPermaLink="false">66d4608ba326133d12440a4b</guid>
                
                    <category>
                        <![CDATA[ animation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Libraries ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Tue, 02 Aug 2022 16:52:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/png_20220803_195955_0000.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I love animating websites. It's so fun when you just look at a site, and there are cool animations that make everything look pretty.</p>
<p>Getting started with an animation library does not have to be hard. Anyone can add a bit of animation to their site regardless of whether they are good working with the front end or not.</p>
<p>Let me show you how you can get started.</p>
<h1 id="heading-what-is-rough-notation">What is Rough Notation?</h1>
<p>Rough notation is lightweight yet amazing JavaScript animation library that you can use to get started with animations pretty quickly. And it is open source!</p>
<p>The docs are pretty straightforward, which is one reason it's a great animation library to start with.</p>
<p>In this article, I'll take you through the basic steps to get started with Rough Notation, and we'll build a pretty small site with some animations.</p>
<p>If you like using the library, check out their super repository. Give it a star, and if you love this article, shout them out! (This isn't sponsored. I just love the library :))</p>
<p>You can <a target="_blank" href="https://github.com/rough-stuff/rough-notation">check out the Rough Notation docs here</a>.</p>
<h2 id="heading-lets-get-animating">Let's Get Animating</h2>
<h3 id="heading-how-to-code-the-htmlcss">How to Code the HTML/CSS</h3>
<p>We can't animate something we don't see. So to start, we'll create a pretty simple static page with some minimal HTML and CSS.</p>
<p>For now, our HTML will just look bland. Nothing much going on. Just a nicely centered thing with a Poppins font going on.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"main"</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header"</span>&gt;</span>Aloha. Hello. Salut.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Today, we will animate this with <span class="hljs-tag">&lt;<span class="hljs-name">scan</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"rough-notation"</span>&gt;</span>Rough Notation<span class="hljs-tag">&lt;/<span class="hljs-name">scan</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is a pretty simple site. If you love this, check Rough Notation out on <span class="hljs-tag">&lt;<span class="hljs-name">scan</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"link"</span>&gt;</span>Github<span class="hljs-tag">&lt;/<span class="hljs-name">scan</span>&gt;</span>. They are open source, and they are amazing!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores omnis molestias voluptas, odit laboriosam esse distinctio provident pariatur accusamus cum?<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>A bit about Rough Notation<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>It's open source.<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>It's easy to start with.<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>I love it!<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In the above code, notice the classes I have added to some of the elements. This is how we select what elements to animate.</p>
<p>Our CSS itself is bare, but here is how it is and what our page looks like:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@import</span> url(<span class="hljs-string">'https://fonts.googleapis.com/css2?family=Poppins:wght@300&amp;display=swap'</span>);
*{
    <span class="hljs-attribute">box-sizing</span>: border-box;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
}
<span class="hljs-selector-tag">body</span>{
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Poppins'</span>, sans-serif;
}
<span class="hljs-selector-class">.main</span>{
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: center;
    <span class="hljs-attribute">align-items</span>: center;
    <span class="hljs-attribute">flex-direction</span>: column;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">40px</span>;
}
<span class="hljs-selector-tag">h1</span>{
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
}
<span class="hljs-selector-tag">p</span>{
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
}
<span class="hljs-selector-tag">ul</span>{
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">20px</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Screenshot-from-2022-08-01-17-31-32.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Screenshot of how our bare static page looks. There is an h1 header that says 'Aloha. Hello. Salut.' A few other paragraphs make up the page and there is an unordered list that states three little facts about Rough Notation.</em></p>
<h3 id="heading-lets-add-some-javascript">Let's Add Some JavaScript</h3>
<p>Hold on, this is the juicy part! For our animations to take any kind of effect, we need a JavaScript file. Just create one, and link it to your HTML like you would normally do.</p>
<p>Now let's see how Rough Notation works.</p>
<p>The docs offer a few ways to add the library to our projects. For the sake of simplicity, we will load the ES module directly.</p>
<p><a target="_blank" href="https://github.com/rough-stuff/rough-notation">Check out the repo and the docs here</a>.</p>
<p>So essentially, we will add the an extra script tag to our HTML so that it looks like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/rough-notation?module"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Now that Rough Notation is partially present in our project, we can dig into our JavaScript file, and import it. The first line of our JavaScript doc would look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { annotate } <span class="hljs-keyword">from</span> <span class="hljs-string">'rough-notation'</span>;
</code></pre>
<p>Now that Rough Notation is fully set up, let's grab what we want to animate from the page. Based on what elements we added classes to, we would have the following:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> header = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.header'</span>);
<span class="hljs-keyword">const</span> roughNotation = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.rough-notation'</span>);
<span class="hljs-keyword">const</span> link = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.link'</span>);
<span class="hljs-keyword">const</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.list'</span>);
</code></pre>
<p>The next step is what will bring our page to life. Say, I wanted to highlight the header a light pink color. I would write this code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> annotation = annotate(header, { <span class="hljs-attr">type</span>: <span class="hljs-string">'highlight'</span> , <span class="hljs-attr">color</span>:<span class="hljs-string">'pink'</span>});
annotation.show();
</code></pre>
<p>We assign the variable annotation to a function called <code>annotate</code>. The annotate function takes two parameters – the element we want to annotate, and an object.</p>
<p>The object can take in a few attributes. In this case we have two: the type of annotation we want on the header, and the color.</p>
<p>And just to mention a few other types of annotations that we can do:</p>
<ul>
<li><p>Highlight</p>
</li>
<li><p>Circle</p>
</li>
<li><p>Underline</p>
</li>
<li><p>Brackets</p>
</li>
<li><p>Box</p>
</li>
<li><p>Strike-through</p>
</li>
<li><p>Crossed-off</p>
</li>
</ul>
<p>Back to our header animation. The last line is <code>annotation.show()</code> which just basically displays our animation.</p>
<p>If we save our page, and check our browser, nothing happens. It was supposed to work (according to the docs), but we get nothing.</p>
<p>I found a solution to the problem on a YouTube video, and in order for us to make the animation come to life, we have to adjust the import line in our JavaScript file.</p>
<p>So you can update it like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { annotate } <span class="hljs-keyword">from</span> <span class="hljs-string">"https://unpkg.com/rough-notation?module"</span>;
</code></pre>
<p>If you are like me, and love opening issues to complain (just kidding) about open source projects, feel free to raise an issue on the Rough Notation repository if the animation doesn't work for you either. But only open an issue if no one has beat you to it yet. So do check recent open and closed issues first. May the best issue opener win :)</p>
<p>If you refresh after fixing the problem we had, our header gets a nice pink highlight. You see it nicely swooshing across the page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Screenshot-from-2022-08-01-18-24-31.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Screenshot of our site now, with the header highlighted in pink.</em></p>
<p>Nice and pretty, right?</p>
<p>Let's go ahead and add a few more animations:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> annotation = annotate(header, { <span class="hljs-attr">type</span>: <span class="hljs-string">'highlight'</span> , <span class="hljs-attr">color</span>:<span class="hljs-string">'pink'</span>});
<span class="hljs-keyword">const</span> annotation2 = annotate(roughNotation, {<span class="hljs-attr">type</span>:<span class="hljs-string">'circle'</span>, <span class="hljs-attr">color</span>:<span class="hljs-string">'yellow'</span>, <span class="hljs-attr">padding</span>:<span class="hljs-number">7</span>});
<span class="hljs-keyword">const</span> annotation3 = annotate(link, { <span class="hljs-attr">type</span>: <span class="hljs-string">'box'</span> , <span class="hljs-attr">color</span>:<span class="hljs-string">'blue'</span>, <span class="hljs-attr">padding</span>:<span class="hljs-number">7</span>});
<span class="hljs-keyword">const</span> annotation4 = annotate(list, { <span class="hljs-attr">type</span>: <span class="hljs-string">'bracket'</span> , <span class="hljs-attr">color</span>:<span class="hljs-string">'red'</span>, <span class="hljs-attr">brackets</span>:[<span class="hljs-string">'left'</span>, <span class="hljs-string">'right'</span>], <span class="hljs-attr">strokeWidth</span>:<span class="hljs-number">5</span>});

<span class="hljs-keyword">const</span> array = annotationGroup([annotation, annotation2, annotation3, annotation4]);
array.show();
</code></pre>
<p>This time, we have added quite a bit. But don't let it get overwhelming. We'll walk through it step by step.</p>
<p>First, we have added <code>padding</code> to our <code>annotation2</code> animation. Just like we saw with the header, the <code>roughNotation</code> (which is the <code>rough-notation</code> class in our HTML) gets a yellow circle with a padding of 7.</p>
<p>But padding isn't the only new attribute we introduced. <code>annotation4</code> has a few new things we need to learn about. The object parameter has an attribute, <code>brackets</code>, with an array as value. <code>left</code> and <code>right</code> indicate that we want opening and closing brackets on both sides of the element. It also has <code>strokeWidth</code>, which determines the thickness of the brackets.</p>
<p>Since we have to "show" the animation of each element, which kind of gets boring if we have to animate a lot, I created an array, stored each animation in it, and then "showed" the array all at once. It's neat, and saves a lot of time.</p>
<p>So we've introduced <code>annotationGroup</code>. For this to take effect, we are going to add it to our import line like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { annotate, annotationGroup } <span class="hljs-keyword">from</span> <span class="hljs-string">"https://unpkg.com/rough-notation?module"</span>;
</code></pre>
<p>So... our final site looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Screenshot-from-2022-08-01-19-46-08.png" alt="Final screenshot with all animations put in place." width="600" height="400" loading="lazy"></p>
<p>The animations will work better on your browser, because you get to refresh and see them take effect one after the other.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Writing this was fun! And I hope that you not only learned something new, but that you tried it out too.</p>
<p>Make sure to check out the Rough Notation repository and docs, because they cover a whole lot more than what we discussed in this article.</p>
<p>Happy animating!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous JavaScript – Callbacks, Promises, and Async/Await Explained ]]>
                </title>
                <description>
                    <![CDATA[ If you've been learning JavaScript for a while now, then you've probably heard the term "asynchronous" before. This is because JavaScript is an asynchronous language...but what does that really mean? In this article, I hope to show you that the conce... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-javascript-explained/</link>
                <guid isPermaLink="false">66d460893a8352b6c5a2aac5</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Mon, 20 Jun 2022 20:10:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727436410214/26117e35-6f63-4788-9b97-3aa225527213.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've been learning JavaScript for a while now, then you've probably heard the term "asynchronous" before.</p>
<p>This is because JavaScript is an asynchronous language...but what does that really mean? In this article, I hope to show you that the concept is not as difficult as it sounds.</p>
<h1 id="heading-synchronous-vs-asynchronous">Synchronous vs Asynchronous</h1>
<p>Before we hop into the real deal, let's look at these two words – synchronous and asynchronous.</p>
<p>By default, JavaScript is a synchronous, single threaded programming language. This means that instructions can only run one after another, and not in parallel. Consider the little code snippet below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> sum = a + b;
<span class="hljs-built_in">console</span>.log(sum);
</code></pre>
<p>The above code is pretty simple – it sums two numbers and then logs the sum to the browser console. The interpreter executes these instructions one after another in that order until it is done.</p>
<p>But this method comes along with disadvantages. Say we wanted to fetch some large amount of data from a database and then display it on our interface. When the interpreter reaches the instruction that fetches this data, the rest of the code is blocked from executing until the data has been fetched and returned.</p>
<p>Now you might say that the data to be fetched isn't that large and it won't take any noticeable time. Imagine that you have to fetch data at multiple different points. This delay compounded doesn't sound like something users would want to come across.</p>
<p>Luckily for us, the problems with synchronous JavaScript were addressed by introducing asynchronous JavaScript.</p>
<p>Think of asynchronous code as code that can start now, and finish its execution later. When JavaScript is running asynchronously, the instructions are not necessarily executed one after the other as we saw before.</p>
<p>In order to properly implement this asynchronous behavior, there are a few different solutions developers has used over the years. Each solution improves upon the previous one, which makes the code more optimized and easier to understand in case it gets complex.</p>
<p>To further understand the asynchronous nature of JavaScript, we will go through callback functions, promises, and async and await.</p>
<h1 id="heading-what-are-callbacks-in-javascript">What are Callbacks in JavaScript?</h1>
<p>A callback is a function that is passed inside another function, and then called in that function to perform a task.</p>
<p>Confusing? Let's break it down by practically implementing it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired first'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired second'</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired third'</span>);
},<span class="hljs-number">2000</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fired last'</span>);
</code></pre>
<p>The snippet above is a small program that logs stuff to the console. But there is something new here. The interpreter will execute the first instruction, then the second, but it will skip over the third and execute the last.</p>
<p>The <code>setTimeout</code> is a JavaScript function that takes two parameters. The first parameter is another function, and the second is the time after which that function should be executed in milliseconds. Now you see the definition of callbacks coming into play.</p>
<p>The function inside <code>setTimeout</code> in this case is required to run after two seconds (2000 milliseconds). Imagine it being carried off to be executed in some separate part of the browser, while the other instructions continue executing. After two seconds, the results of the function are then returned.</p>
<p>That is why if we run the above snippet in our program, we will get this:</p>
<pre><code class="lang-javascript">fired first
fired second
fired last
fired third
</code></pre>
<p>You see that the last instruction is logged before the function in the <code>setTimeout</code> returns its result. Say we used this method to fetch data from a database. While the user is waiting for the database call to return results, the flow in execution will not be interrupted.</p>
<p>This method was very efficient, but only to a certain point. Sometimes, developers have to make multiple calls to different sources in their code. In order to make these calls, callbacks are being nested until they become very hard to read or maintain. This is referred to as <strong>Callback Hell</strong></p>
<p>To fix this problem, promises were introduced.</p>
<h1 id="heading-what-are-promises-in-javascript">What are Promises in JavaScript?</h1>
<p>We hear people make promises all the time. That cousin of yours who promised to send you free money, a kid promising to not touch the cookie jar again without permission...but promises in JavaScript are slightly different.</p>
<p>A promise, in our context, is something which will take some time to do. There are two possible outcomes of a promise:</p>
<ul>
<li><p>We either run and resolve the promise, or</p>
</li>
<li><p>Some error occurs along the line and the promise is rejected</p>
</li>
</ul>
<p>Promises came along to solve the problems of callback functions. A promise takes in two functions as parameters. That is, <code>resolve</code> and <code>reject</code>. Remember that resolve is success, and reject is for when an error occurs.</p>
<p>Let's take a look at promises at work:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getData = <span class="hljs-function">(<span class="hljs-params">dataEndpoint</span>) =&gt;</span> {
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span> (<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
     <span class="hljs-comment">//some request to the endpoint;</span>

     <span class="hljs-keyword">if</span>(request is successful){
       <span class="hljs-comment">//do something;</span>
       resolve();
     }
     <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(there is an error){
       reject();
     }

   });
};
</code></pre>
<p>The code above is a promise, enclosed by a request to some endpoint. The promise takes in <code>resolve</code> and <code>reject</code> like I mentioned before.</p>
<p>After making a call to the endpoint for example, if the request is successful, we would resolve the promise and go on to do whatever we want with the response. But if there is an error, the promise will get rejected.</p>
<p>Promises are a neat way to fix problems brought about by callback hell, in a method known as <strong>promise chaining</strong>. You can use this method to sequentially get data from multiple endpoints, but with less code and easier methods.</p>
<p>But there is an even better way! You might be familiar with the following method, as it's a preferred way of handling data and API calls in JavaScript.</p>
<h1 id="heading-what-is-async-and-await-in-javascript">What is Async and Await in JavaScript?</h1>
<p>The thing is, chaining promises together just like callbacks can get pretty bulky and confusing. That's why Async and Await was brought about.</p>
<p>To define an async function, you do this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> asyncFunc = <span class="hljs-keyword">async</span>() =&gt; {

}
</code></pre>
<p>Note that calling an async function will always return a Promise. Take a look at this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> test = asyncFunc();
<span class="hljs-built_in">console</span>.log(test);
</code></pre>
<p>Running the above in the browser console, we see that the <code>asyncFunc</code> returns a promise.</p>
<p>Let's really break down some code now. Consider the little snippet below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> asyncFunc = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(resource);
       <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
}
</code></pre>
<p>The <code>async</code> keyword is what we use to define async functions as I mentioned above. But how about <code>await</code> ? Well, it stalls JavaScript from assigning <code>fetch</code> to the response variable until the promise has been resolved. Once the promise has been resolved, the results from the fetch method can now be assigned to the response variable.</p>
<p>The same thing happens on line 3. The <code>.json</code> method returns a promise, and we can use <code>await</code> still to delay the assigning until the promise is resolved.</p>
<h1 id="heading-to-block-code-or-not-to-block-code">To Block Code or Not to Block Code</h1>
<p>When I say 'stalling', you must think that implementing Async and Await somehow blocks code execution. Because what if our request takes too long, right?</p>
<p>Fact is, it doesn't. Code that is inside the async function is blocking, but that doesn't affect program execution in any way. The execution of our code is just as asynchronous as ever. To show this,</p>
<pre><code class="lang-markdown">const asyncFunc = async () =&gt; {
<span class="hljs-code">    const response = await fetch(resource);
       const data = await response.json();
}
</span>
console.log(1);
cosole.log(2);

asyncFunc().then(data =&gt; console.log(data));

console.log(3);
console.log(4);
</code></pre>
<p>In our browser console, the output of the above would look something like this:</p>
<pre><code class="lang-markdown">1
2
3
4
data returned by asyncFunc
</code></pre>
<p>You see that as we called <code>asyncFunc</code>, our code continued running until it was time for the function to return results.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>This article does not treat these concepts in great depth, but I hope it shows you what asynchronous JavaScript entails and a few things to look out for.</p>
<p>It is a very essential part of JavaScript, and this article only scratches the surface. Nonetheless, I hope this article helped to break down these concepts.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Primitive vs Reference Data Types in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Data types can be a bit of a mind boggling concept. But as programmers, we use data types everyday – so they're something we should understand. Question is, how does the computer store these data types? It can't possibly treat every data type the sam... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/primitive-vs-reference-data-types-in-javascript/</link>
                <guid isPermaLink="false">66d4608fd14641365a050941</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Njong Emy ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jan 2022 19:24:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/Purple-Minimal-We-Are-Hiring-Twitter-Post-1.gif" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Data types can be a bit of a mind boggling concept. But as programmers, we use data types everyday – so they're something we should understand.</p>
<p>Question is, how does the computer store these data types? It can't possibly treat every data type the same.</p>
<p>In JavaScript, data types are split in two categories, and the computer treats each one differently. We have primitive data types and reference data types. But what are these? And why is it important to know the difference? That's what we'll learn in this article.</p>
<h1 id="heading-primtive-data-types-in-javascript">Primtive data types in JavaScript</h1>
<p>These data types are pretty simple, and are sometimes treated as the lowest level of implementation of a programming language. They are not objects, and do not have methods.</p>
<p>Examples of such data types are numbers, strings, booleans, null, and undefined.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/Purple-Minimal-We-Are-Hiring-Twitter-Post--1-.png" alt="Primitive data types" width="600" height="400" loading="lazy"></p>
<p>But you might be wondering about strings, because they do have methods. The fact is, JavaSvript converts primitive strings to string objects, so that it is possible to use string object methods.</p>
<h1 id="heading-how-are-primitive-data-types-treated-in-javascript">How are primitive data types treated in JavaScript?</h1>
<p>When you declare a primitive data type in JavaScript, it is stored on a stack. A stack is a simple data structure that the computer uses to store and retrieve data quickly.</p>
<p>A primitive data type on the stack is identified by the variable name you used for declaration in your program. With each primitive data type you create, data is added to the stack.</p>
<p>To implement this, say we declare a variable, <code>numOne</code>, and give it a value of 50. We go on to create another variable, <code>numTwo</code>, and assign it the same value of 50. So both variables have the same value.</p>
<p>What happens on the stack is that, the computer creates room for <code>numOne</code> and stores its assigned value on the stack. When <code>numTwo</code> is created, the computer again creates room, and stores 50 on the stack. It does not matter that both variables are assigned the same value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/Purple-Minimal-We-Are-Hiring-Twitter-Post--3-.png" alt="Storing data on the stack" width="600" height="400" loading="lazy"></p>
<p>What if during the coding process, we decided to update the value of <code>numOne</code> to say, 100? Does it mean <code>numTwo</code> will change too? The answer is no.</p>
<p>Since <code>numOne</code> and <code>numTwo</code> were stored differently on the stack, updating one of them will not affect the other. And we can experiment with that by actually trying it out in our code editor.</p>
<p>Logging <code>numOne</code> to the console will output 100, and logging <code>numTwo</code> will output 50. So, in effect, the two variables have no relationship to each other.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numOne = <span class="hljs-number">50</span>;
<span class="hljs-keyword">let</span> numTwo = numOne; <span class="hljs-comment">//numTwo=numOne=50</span>
numOne = <span class="hljs-number">100</span>;
<span class="hljs-built_in">console</span>.log(numOne); <span class="hljs-comment">//outputs 100</span>
<span class="hljs-built_in">console</span>.log(numTwo); <span class="hljs-comment">//outputs 50</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/Purple-Minimal-We-Are-Hiring-Twitter-Post--4-.png" alt="Updated stack" width="600" height="400" loading="lazy"></p>
<p>Now that we've seen how easy it is to handle primitive data types, let's see how similarly reference data types work.</p>
<h1 id="heading-reference-data-types-in-javascript">Reference data types in JavaScript</h1>
<p>Reference data types, unlike primitive data types, are dynamic in nature. That is, they do not have a fixed size.</p>
<p>Most of them are considered as objects, and therefore have methods. Examples of such data types include arrays, functions, collections, and all other types of objects.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/Purple-Minimal-We-Are-Hiring-Twitter-Post--2-.png" alt="Reference data types" width="600" height="400" loading="lazy"></p>
<h1 id="heading-whats-the-difference-between-primitive-and-reference-data-types">What's the difference between primitive and reference data types?</h1>
<p>The difference comes in when the computer has to store a reference data type. When you create a variable and assign it a value that is a reference data type, the computer does not directly store that data type in that variable (as is the case with primitive types).</p>
<p>What you have assigned to that variable is a pointer that points to the location of that data type in memory. Confusing? I know.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/Purple-Minimal-We-Are-Hiring-Twitter-Post--5-.png" alt="Reference data types" width="600" height="400" loading="lazy"></p>
<p>As you can see in the image above, we have two data structures now. A stack, and a heap. Say we declared an object, for example. The object itself is stored on a heap, and its pointer is stored on a stack. The pointer is identified by the object's variable name, and points to that object.</p>
<p>Now, we could create a variable, <code>object1</code>, and assign an object to it. What if like before, we create another variable <code>object2</code>, and assign it to <code>object1</code>. Does that mean another object will be created on the heap? The answer is no.</p>
<p>Since the object already exists on the heap, <code>object2</code> and <code>object1</code> will both point to the same object.</p>
<p>Another difference comes in when we update <code>object1</code>. If we log both variables to the console, we see that the change affected them both. This is because they are pointing to the same object on the heap – and updating one variable of course affects the other.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> object1 = {
<span class="hljs-attr">name</span>:<span class="hljs-string">'Bingeh'</span>,
<span class="hljs-attr">age</span>:<span class="hljs-number">18</span>
};
<span class="hljs-keyword">let</span> object2 = object1;

<span class="hljs-comment">//updating object1,</span>
object1.age = <span class="hljs-number">20</span>;

<span class="hljs-built_in">console</span>.log(object2); <span class="hljs-comment">//we see that object2 also updates the age attribute</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/Purple-Minimal-We-Are-Hiring-Twitter-Post--6-.png" alt="Update on heap" width="600" height="400" loading="lazy"></p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>Now you know the difference between primitive and reference data types. It is important to know these differences – especially when you get errors like 'null pointer reference' – so you can figure out why they're happening.</p>
<p>This sometimes happens with Java developers, so I hope that this article helps you clear up any doubts.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
