Learn Javascript

High level walkthrough of javascript key concepts

JavaScript is a versatile programming language used for both client-side and server-side applications. React is a popular JavaScript library for building user interfaces, and Next.js is a powerful framework built on top of React that simplifies the development of scalable and performant web applications.

In this tutorial, we'll introduce some important JavaScript concepts and demonstrate how to use them with React and Next.js by building a simple bicycle rental application. We'll cover the following topics:

  1. Running JavaScript code using online tools

  2. Variables, Constants, and Data Types

  3. Functions

  4. Conditional Statements

  5. Loops

  6. Arrays

  7. Objects

  8. Asynchronous Programming

  9. React Components

  10. Next.js Pages

Prerequisites

To follow along, you'll need to have Node.js and npm (Node package manager) installed on your computer. If you don't have them, refer to the Installing Node.js / NPM section.

0. Running JavaScript code using online tools

Before we dive into the code, you may want to try out some JavaScript code snippets without setting up a complete project. Online tools like JSFiddle (https://jsfiddle.net/) or CodeSandbox (https://codesandbox.io/) allow you to write, run, and share JavaScript code directly in your browser.

To get started, visit one of these websites, create a new fiddle or sandbox, and start writing your JavaScript code in the designated area.

Getting Started

First, let's create a new Next.js application using the terminal:

npx create-next-app bicycle-rental-app
cd bicycle-rental-app
npm run dev

Replace "bicycle-rental-app" with your desired project name. The development server will start on http://localhost:3000.

1. Variables, Constants, and Data Types

JavaScript has three ways to declare variables: var, let, and const. We'll be using let and const in this tutorial.

const rentalRate = 10; // Rental rate per hour in dollars
let numberOfBikes = 20; // Total number of bikes available

JavaScript supports several data types, such as strings, numbers, booleans, and objects.

2. Functions

Functions are blocks of code that can be defined and called by name. Functions can take parameters and return values.

function calculateRentalCost(hours) {
  return rentalRate * hours;
}

const rentalCost = calculateRentalCost(3);
console.log(rentalCost); // 30

3. Conditional Statements

Conditional statements execute code based on certain conditions. The most common conditional statement is the if statement.

let customerAge = 16;

if (customerAge < 18) {
  console.log("A parent or guardian must sign the rental agreement.");
} else {
  console.log("Proceed with the rental.");
}

4. Loops

Loops are used to execute a block of code repeatedly. The most common loop in JavaScript is the for loop.

for (let i = 1; i <= numberOfBikes; i++) {
  console.log(`Bike #${i} is ready for rental.`);
}

5. Arrays

Arrays are used to store multiple values in a single variable.

const availableBikes = [
  { id: 1, type: "Mountain" },
  { id: 2, type: "Road" },
  // ...
];
console.log(availableBikes[0].type); // Mountain

6. Objects

Objects are a collection of properties and methods.

const bicycleRental = {
  rentalRate: 10,
  numberOfBikes: 20,
  availableBikes: [
    { id: 1, type: "Mountain" },
    { id: 2, type: "Road" },
    // ...
  ],
  rentBike: function (bikeId) {
    this.numberOfBikes--;
    console.log(`Bike #${bikeId} rented. Remaining bikes: ${this.numberOfBikes}`);
  },
  returnBike: function (bikeId) {
    this.numberOfBikes++;
    console.log(`Bike #${bikeId} returned. Remaining bikes: ${this.numberOfBikes}`);
  },
};

bicycleRental.rentBike(1); // Bike #1 rented. Remaining bikes: 19
bicycleRental.returnBike(1); // Bike #1 returned. Remaining bikes: 20

7. Asynchronous Programming

JavaScript supports asynchronous programming using callbacks, Promises, and the async/await syntax.

async function fetchBicycleData() {
  const response = await fetch("https://api.example.com/bicycles");
  const data = await response.json();
  return data;
}

fetchBicycleData().then((bicycles) => {
  console.log(bicycles);
});

8. React Components

React components are the building blocks of the user interface. Components can have state and props, and they return JSX to render the UI.

Create a new file BicycleList.js in the components folder:

import React from "react";

const BicycleList = ({ bicycles }) => {
  return (
    <div>
      <h2>Available Bicycles</h2>
      <ul>
        {bicycles.map((bicycle) => (
          <li key={bicycle.id}>
            {bicycle.type} - Bike #{bicycle.id}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default BicycleList;

9. Next.js Pages

Next.js automatically creates a route for each page in the pages folder. To display the list of bicycles, create a new file index.js in the pages folder:

javascriptCopy codeimport React, { useState, useEffect } from "react";
import BicycleList from "../components/BicycleList";

const bicyclesData = [
  { id: 1, type: "Mountain" },
  { id: 2, type: "Road" },
  // ...
];

export default function Home() {
  const [bicycles, setBicycles] = useState([]);

  useEffect(() => {
    // You can replace this with a call to fetchBicycleData()
    setBicycles(bicyclesData);
  }, []);

  return (
    <div>
      <h1>Bicycle Rental Application</h1>
      <BicycleList bicycles={bicycles} />
    </div>
  );
}

Now, you can run the application by executing npm run dev in the terminal, and visit http://localhost:3000 to see the bicycle rental application in action.

Last updated