icon

The only JavaScript you need to know for using Next JS or React - Part 1

summary

In this blog, we will look at the JavaScript concepts you need to know for using Next.js or React to build your website.

tech stack
JavaScript
Next.js
React
published date
last edited time
thumbnail

You need to know basic JavaScript to use React or Next.js. You don't need to be a master of it to build cool web applications.

Here, I've shown the basic JavaScript concepts with examples. Just learn the concept of what is happening, and then you can search on Google to delve deeper into those particular concepts.

I am using Next.js App router here.

Const and Let Variables

In JavaScript, variables are used for storing data, and there are primarily two types of variable declarations: const and let.

const

The const keyword is used to declare variables whose values are intended to remain constant throughout their lifetime. Once assigned, the value of a const variable cannot be reassigned. if we try to reassign the value of a

a = 12 then we get this error : Cannot assign to 'a' because it is a constant.ts(2588)

let

The let keyword, on the other hand, is used to declare variables that are mutable, meaning their values can be reassigned.

like in the example the first value of b is 6, then we reassigned to 10, so the b value is 10 now, then we reassign b value to 20 , now the final b = value is 20

javascript

Copy

export default function Page() {
  // using const to store the value
  const a = 6;

  // using let to store the value
  let b = 6;
  b = 10;
  b = 20; // reassigning the value of a

  return (
    <main className="p-6">
      <div>
        <h1>const and let </h1>
        <p>a : {a}</p>
        <p>b : {b}</p>
      </div>
    </main>
  );
}
app/page.tsx

Data types

JavaScript supports a variety of data types, each serving different purposes in programming. These data types include:

  • String: Represents textual data and is enclosed in double or single quotes.
  • Number: Represents numeric values, including integers and floating-point numbers.
  • Bigint: Represents integers of arbitrary length, useful for working with large numbers.
  • Boolean: Represents logical values, either true or false.
  • Undefined: Represents a variable that has been declared but has not been assigned any value.
  • Null: Represents the intentional absence of any value.
  • Symbol: Represents unique identifiers, useful for creating hidden or private object properties.
  • Object: Represents complex data structures composed of key-value pairs, arrays, functions, and other objects.
javascript

Copy

export default function Page() {

  // Data types
  // String
  const name = "John";

  // Number
  const age = 30;

  // Boolean
  const isStudent = true; // or false

  // Undefined
  let tee; // not given any value yet

  // Null
  const emptyValue = null;

  // Object
  const person = {
    name: "John",
    age: 30,
    isStudent: true,
  };
  // Array object:
  const cars = ["Saab", "Volvo", "BMW"];

  // Date object:
  const date = new Date("2024-03-06");
  const currentDate = Date(); // gives current live date

  return (
    <main className="p-6">
      <div>
        <h1>Data Types</h1>

        <p>String: {name}</p>

        <p>Number: {age}</p>

        <p>Boolean: {String(isStudent)}</p>

        <p>Undefined: {String(tee)}</p>

        <p>Null: {String(emptyValue)}</p>

        <p>Object: {JSON.stringify(person)}</p>

        <p>Array: {JSON.stringify(cars)}</p>

        <p>Date: {date.toDateString()}</p>

        <p>Current Date: {currentDate.toString()}</p>
      </div>
    </main>
  );
}

The Object Datatype*

The object data type is versatile and can contain different kinds of data:

  • An object: Represents a collection of properties where each property has a key-value pair.
  • An array: Represents a sequential collection of elements, accessed by numeric indices, often used for lists of data.
  • A date: Represents a specific point in time, enabling time-related operations and calculations.

Objects and Arrays and the difference

Objects:

  • Definition: Objects are collections of key-value pairs, where each key is a string (or symbol) and each value can be any data type.
  • Usage: Objects represent entities with named attributes, such as users, products, or any real-world concept.
  • Accessing Values: Values in objects are accessed using their corresponding keys.
javascript

Copy

// Object representing a person
const person = {
  name: 'John',
  age: 30,
  isStudent: true
};

// Accessing values
console.log(person.name);    // Output: John
console.log(person.age);     // Output: 30
console.log(person.isStudent); // Output: true

Arrays:

  • Definition: Arrays are ordered lists of values, where each value can be any data type.
  • Usage: Arrays store collections of related data, such as lists of items or sequential data.
  • Accessing Values: Values in arrays are accessed using numeric indices, starting from 0.
  • Note: Array is a type of object.
javascript

Copy

// Array representing a list of fruits
const fruits = ['apple', 'banana', 'orange'];

// Accessing values
console.log(fruits[0]);   // Output: apple
console.log(fruits[1]);   // Output: banana
console.log(fruits[2]);   // Output: orange

In summary, objects are used for storing named properties and represent entities with attributes, while arrays are used for storing ordered collections of values and manage lists of data.

Operators and Ternary Operators

Operators are symbols that perform operations on operands, such as variables or values. Ternary operators are a type of operator used for conditional expressions.

Operators:

Arithmetic Operators:

  • Arithmetic operators perform mathematical operations on operands.
javascript

Copy

const a = 10;
const b = 5;

const sum = a + b;          // Addition
const difference = a - b;   // Subtraction
const product = a * b;      // Multiplication
const quotient = a / b;     // Division
const remainder = a % b;    // Remainder
// Increment a
a++;                        // Increment a by 1

// Decrement b
b--;                        // Decrement b by 1

Comparison Operators:

  • Comparison operators compare two values and return a boolean result.
javascript

Copy

const x = 10;
const y = 5;

const isequal = x == y;                 // Equal to 
const isEqualandeqaltype = x === y;     // Equal to and equal type 
const isNotEqual = x != y;              // Not equal 
const isNotEqualnoteqaltype = x !== y;  // Not equal to or not equal type 

const isGreaterThan = x > y;     // Greater than
const isLessThan = x < y;        // Less than
const isGreaterOrEqual = x >= y; // x is Greater than or equal to y
const isLessOrEqual = x <= y;    // Less than or equal to

Logical Operators:

  • Logical operators combine two or more boolean expressions and return a single boolean result.
javascript

Copy

const isAdult = true;
const hasLicense = false;

// Logical AND
const canDrive = isAdult && hasLicense; // Can drive if adult and has license
// Logical OR
const canVote = isAdult || hasLicense;  // Can vote if adult or has license
// Logical NOT
const cannotDrive = !canDrive;  // Cannot drive if not canDrive

// Ternary Operator 
const drivingStatus = canDrive ? "Can drive" : "Cannot drive";
console.log(drivingStatus);    // Output depends on values of isAdult and hasLicense

Ternary Operator:

  • The ternary operator condition ? exprIfTrue : exprIfFalse is a shorthand for an if...else statement.
javascript

Copy

const age = 20;

const message = age >= 18 ? "You are an adult" : "You are a minor";

console.log(message); // Output: "You are an adult"

In summary, operators in JavaScript perform various operations on operands, and ternary operators provide a concise way to write conditional expressions. Understanding and using these operators effectively is essential for writing expressive and efficient JavaScript code.

If, Else Statements

In JavaScript, if and else statements are used for conditional execution, allowing your code to make decisions based on certain conditions.

if Statement:

  • The if statement evaluates a condition inside parentheses. If the condition is true, the code block inside the curly braces {} is executed.
  • If the condition is false, the code block is skipped.
javascript

Copy

const age = 25;

if (age >= 18) {     //  ">=" this is ternary opperator
  console.log("You are an adult.");
}
// output You are an adult

else Statement:

  • The else statement follows an if statement and executes a code block if the if condition is false.
  • It doesn't have a condition of its own; it's simply a fallback option when the if condition is not met.
javascript

Copy

const age = 15;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}
// output You are a minor.

else if Statement:

  • The else if statement allows you to specify additional conditions to test if the previous conditions are false.
  • It follows an if statement or another else if statement and executes its code block if its condition is true.
javascript

Copy

const score = 75;

if (score >= 90) {
  console.log("You got an A.");
} else if (score >= 80) {
  console.log("You got a B.");
} else if (score >= 70) {
  console.log("You got a C.");
} else {
  console.log("You need to improve your score.");
}
// output You got a B

Nested if Statements:

  • You can nest if statements inside other if or else statements to handle more complex conditions.
javascript

Copy

const age = 25;
const isStudent = false;

if (age >= 18) {
  if (isStudent) {
    console.log("You are an adult student.");
  } else {
    console.log("You are an adult worker.");
  }
} else {
  console.log("You are a minor.");
}
// output You are an adult worker.

In summary, if and else statements are fundamental for controlling the flow of your JavaScript code based on conditions, allowing for more dynamic and responsive behavior in your applications.

💟

That's all for Part 1. In Part 2, we'll cover the most important topics related to data fetching Here is the link . Happy Coding