Skip to content

The JavaScript You Need to Know for React

The JavaScript features worth knowing well before you learn React, from callbacks and scope to destructuring and promises, and where each shows up in React code.

NevilleFrontend engineer
· 5 min read

"How much JavaScript do I need to know before learning React?" is a common question among beginners. The answer is subjective, but I'll share my thoughts based on the approach I took when I started, and what I'd recommend from experience.

Many developers, including me, choose a "learn as you go" approach to React. It can seem convenient, but it often hurts productivity in the long run and leaves gaps in your knowledge, especially of JavaScript. When something breaks, it's hard to tell whether you're fighting React or the language.

There are a lot of concepts that are good to know. Here I'll focus on the key features that are important to understand before diving into React.

JavaScript basics

It's important to have a solid grasp of some fundamental JavaScript concepts: not just how they work, but why they work the way they do. Many features you'll meet in React are plain JavaScript used in slightly different ways, so understanding them well makes React much easier to work with.

Some of the basics to learn are:

Callback functions

A callback is a function passed into another function as an argument, to be called later. In React, every event handler you pass (onClick={handleClick}) is a callback. For example:

callbacks.js
function sumValues(num1, num2, callback) {
  const sum = num1 + num2;
  callback(sum);
}
 
function logSum(sum) {
  console.log("THE SUM IS: " + sum);
}
 
sumValues(1, 3, logSum);
// THE SUM IS: 4

Read more about callback functions on freeCodeCamp (opens in a new tab).

Variable scope

Scope is the context in which variables are declared and where they can be accessed. A solid understanding of it is crucial: it shapes how you structure your code and how different parts of your application interact. In React, it's what lets an event handler defined inside a component "see" that component's props and state.

scope.js
function counter() {
  let count = 0; // Private variable
 
  return function () {
    count++; // Updates the private variable
    console.log(count);
  };
}
 
const increment = counter();
increment(); // 1
increment(); // 2
increment(); // 3

The inner function keeps access to count after counter() has returned. That's called a closure, and closures are behind many "stale state" bugs in React, so they're worth understanding well.

Learn more in this video about scope (opens in a new tab).

Array methods

Array methods are powerful, and I've used them in almost every application I've worked on. These are the ones you'll use most often:

  • map
  • filter
  • find
  • includes
  • reduce
  • some
  • every

Here's an example:

arrays.js
const people = [
  { name: "James", age: 20, siblings: [] },
  { name: "Thomas", age: 22, siblings: ["Louis"] },
  { name: "Aseda", age: 19, siblings: ["Anthony"] },
  { name: "Lucy", age: 15, siblings: [] },
  { name: "Thompson", age: 32, siblings: ["Grace", "Philip"] },
];
 
people.map((person) => person.age);
// [20, 22, 19, 15, 32]
 
people.filter((person) => person.age < 20);
// [{ name: "Aseda", … }, { name: "Lucy", … }]
 
people.find((person) => person.age === 15);
// { name: "Lucy", age: 15, siblings: [] }
 
people.reduce((total, person) => total + person.siblings.length, 0);
// 4 (the number of siblings in total)
 
people.some((person) => person.siblings.includes("Grace"));
// true
 
people.every((person) => person.siblings.includes("Grace"));
// false

In React, map is how you render lists (people.map((p) => <li key={p.name}>{p.name}</li>)), and filter is how you derive what to show from state without changing the original array.

Learn more about arrays on MDN (opens in a new tab).

Template literals

Template literals, sometimes called template strings, are mostly used for string interpolation and multi-line strings.

template-literals.js
const firstName = "Neville";
const lastName = "Kati";
 
// Without template literals
console.log("My name is " + firstName + " " + lastName + ".");
// My name is Neville Kati.
 
// With template literals
console.log(`My name is ${firstName} ${lastName}.`);
// My name is Neville Kati.

Learn more about template literals on MDN (opens in a new tab).

Rest and spread operators

Both use the ... syntax, and you can think of them as operating on a collection of values. They mean different things in different places, so it's worth learning the nuances.

The rest syntax lets a function accept any number of arguments, as an array:

rest.js
function add(...numbers) {
  let sum = 0;
  for (const n of numbers) {
    sum += n;
  }
  return sum;
}
 
add(1, 2); // 3
add(1, 2, 3); // 6
add(1, 2, 3, 4, 5); // 15

Learn more about rest parameters on MDN (opens in a new tab).

The spread syntax is mostly used to copy the contents of an array or object into a new one:

spread.js
const firstArray = [5, 10, 15, 20, 25, 30];
const newArray = [...firstArray, 35, 40];
 
console.log(newArray); // [5, 10, 15, 20, 25, 30, 35, 40]

Learn more about spread syntax on MDN (opens in a new tab).

Nullish coalescing operator ??

This is handy when a value might be null or undefined and you need a fallback.

nullish.js
// One way to choose a fallback, but it's cumbersome and hard to read:
const result = a !== null && a !== undefined ? a : b;
 
// This can be simplified to:
const result = a ?? b;
 
// If a is neither null nor undefined, use a; otherwise use b.

Unlike ||, ?? keeps falsy values such as 0 and "", so count ?? 10 stays 0 when the count is 0.

Learn more about the nullish coalescing operator on MDN (opens in a new tab).

Default parameters

A way of giving function parameters default values. You'll use the same syntax to give props defaults.

defaults.js
// b has a default value of 0
const add = (a, b = 0) => a + b;
 
// The same function without default parameters:
function add(a, b) {
  b = b === undefined ? 0 : b;
  return a + b;
}

The conditional (ternary) operator

The ternary operator picks between two values based on a condition. JSX can't contain if…else statements, so in React it's how you choose what to render.

Drinks.jsx
const filledUp = false; // or true
 
const message = filledUp
  ? "The bottle has soda!"
  : "The bottle may not have soda :-(";
 
// is the same as:
let message;
if (filledUp) {
  message = "The bottle has soda!";
} else {
  message = "The bottle may not have soda :-(";
}
 
// In React:
function Drinks() {
  const drinks = [
    { name: "Coca-Cola", quantity: 4 },
    { name: "Fanta", quantity: 2 },
  ];
 
  return drinks.length ? (
    <ul>
      {drinks.map((drink) => (
        <li key={drink.name}>
          {drink.name}: {drink.quantity} left
        </li>
      ))}
    </ul>
  ) : (
    <p>There are no drinks. The sadness.</p>
  );
}

Learn more about the conditional operator on MDN (opens in a new tab).

Optional chaining

Optional chaining lets you safely read properties and call functions that may not exist.

optional-chaining.js
// Before optional chaining:
const city = user && user.address && user.address.city;
 
// With optional chaining:
const city = user?.address?.city;
 
// Returns undefined, instead of throwing, if user or user.address is missing.

Learn more about optional chaining on MDN (opens in a new tab).

Destructuring

This is an amazing JavaScript feature. It gives you an easy way to unpack values from arrays, or properties from objects, into separate variables, and it's how most React components receive their props.

Food.jsx
const names = ["John", "Carine", "Anatelle", "Francis", "Joy"];
const food = { name: "Potato", nutrient: "Carbohydrates", cost: "$1.5" };
 
// Without destructuring:
function Food() {
  return (
    <p>
      {food.name} is mainly made of {food.nutrient}. {names[0]} and {names[1]}{" "}
      love it.
    </p>
  );
}
 
// Destructuring gives a much cleaner syntax:
function FoodDestructured() {
  const { name, nutrient } = food;
  const [first, second] = names;
 
  return (
    <p>
      {name} is mainly made of {nutrient}. {first} and {second} love it.
    </p>
  );
}

You'll see array destructuring in every component that uses state: const [count, setCount] = useState(0).

You can learn more about destructuring on MDN (opens in a new tab).

Promises and async/await

This is a big topic, and it takes practice to get really good at it. Promises help you manage asynchronous operations (opens in a new tab), the most common one being an HTTP request made with fetch().

async/await is special syntax for working with promises, and the two go hand in hand.

fetch-data.js
async function fetchData() {
  try {
    const result = await new Promise((resolve) => {
      // Some asynchronous task
      setTimeout(() => {
        resolve("Data fetched successfully!");
      }, 2000);
    });
    console.log(result); // Runs when the promise resolves
  } catch (error) {
    console.log(error); // Runs when the promise is rejected
  }
}

Learn more:

Conclusion

There are many more JavaScript features and concepts you'll need when building React applications, but in my opinion these are the key ones to really know and understand first. With them in place, most of React is just JavaScript used in a particular way.

I hope you found this useful. Good luck!

Written by Neville

Geologist turned frontend engineer from Cameroon, based in Ghana. Makes web and mobile apps faster and writes down how. More about me

Liked this? Get the next one.

One deep dive a month. No spam, unsubscribe in one click.