DEV Community

Cover image for JavaScript Arrow Functions & Ternary Operator Explained
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

3

JavaScript Arrow Functions & Ternary Operator Explained

ES6 introduced Arrow Functions and the Ternary Operator, making JavaScript code cleaner and more readable. These features are widely used in React for handling functions and conditional rendering. Let's explore both in detail!

1.Arrow Functions in JavaScript & React

Arrow functions provide a shorter syntax for writing functions. They also handle the thiskeyword differently compared to traditional functions, making them useful in React components.

Basic Arrow Function
Before ES6, we wrote functions like this:


function greet() {
  return "Hello, World!";
}

Enter fullscreen mode Exit fullscreen mode

With Arrow Functions, the same function can be written like this:


const greet = () => {
  return "Hello, World!";
};

Enter fullscreen mode Exit fullscreen mode

If the function has only one return statement, you can skip the returnkeyword and {}:


const greet = () => "Hello, World!";
console.log(greet()); // Output: Hello, World!

Enter fullscreen mode Exit fullscreen mode

Arrow Function with Parameters
If the function requires parameters, pass them inside the parentheses:


const greetUser = (name) => `Hello, ${name}!`;
console.log(greetUser("Sudhanshu")); // Output: Hello, Sudhanshu!

Enter fullscreen mode Exit fullscreen mode

For a single parameter, you can remove the parentheses:


const square = num => num * num;
console.log(square(5)); // Output: 25

Enter fullscreen mode Exit fullscreen mode

How Arrow Functions Handle this

Unlike regular functions, arrow functions do not bind their own this. Instead, they inherit this from the surrounding scope. This is especially useful in React class components.

🚫 Regular Function (this Issue)

class Car {
  constructor(name) {
    this.name = name;
  }

  showName() {
    console.log(this.name);
  }
}

const myCar = new Car("Tesla");
setTimeout(myCar.showName, 1000); // ❌ Output: undefined
Enter fullscreen mode Exit fullscreen mode

The problem? When showNameis called inside setTimeout, thisno longer refers to the Carobject.

Arrow Function (this Fixed)
Using an arrow function, this is preserved:

class Car {
  constructor(name) {
    this.name = name;
  }

  showName = () => {
    console.log(this.name);
  };
}

const myCar = new Car("BMW");
setTimeout(myCar.showName, 1000); // ✅ Output: BMW


Enter fullscreen mode Exit fullscreen mode

💡 In React, arrow functions are useful for binding event handlers in class components!


2.Ternary Operator in JavaScript & React

The ternary operator (? :) is a shorthand for if-else conditions. It’s commonly used in React for conditional rendering.

Basic Ternary Operator Example
Before using the ternary operator:


let age = 18;
let message;

if (age >= 18) {
  message = "You are an adult!";
} else {
  message = "You are a minor!";
}

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


Enter fullscreen mode Exit fullscreen mode

Now, let's simplify it with a ternary operator:


const age = 18;
const message = age >= 18 ? "You are an adult!" : "You are a minor!";
console.log(message); // Output: You are an adult!


Enter fullscreen mode Exit fullscreen mode

Ternary Operator in React for Conditional Rendering

In React, we use the ternary operator to conditionally render elements.

🚫 Without Ternary Operator (Using if-else)

function App() {
  const isLoggedIn = true;

  if (isLoggedIn) {
    return <h1>Welcome, User!</h1>;
  } else {
    return <h1>Please log in.</h1>;
  }
}


Enter fullscreen mode Exit fullscreen mode

With Ternary Operator (Cleaner Code)


function App() {
  const isLoggedIn = true;

  return <h1>{isLoggedIn ? "Welcome, User!" : "Please log in."}</h1>;
}

Enter fullscreen mode Exit fullscreen mode

Benefits of using Ternary Operator in React:
✔ Makes JSX code shorter & cleaner
✔ Easy to use for inline conditional rendering


Conclusion

✔ Arrow functions make function syntax shorter and handle this better in React.
✔ Ternary operator simplifies if-else logic and makes React components more readable.
✔ These ES6 features improve JavaScript and React code structure.

$150K MiniMax AI Agent Challenge — Build Smarter, Remix Bolder, Win Bigger!

Join the MiniMax AI Agent Challenge — Build your first AI Agent 🤖

Developers, innovators, and AI tinkerers, build your AI Agent and win $150,000 in cash. 💰

Read more →

Top comments (0)

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

👋 Kindness is contagious

Dive into this compelling post celebrated by our lively DEV Community. Developers everywhere are invited to share insights and uplift our collective expertise.

A simple “thank you” can make someone’s day—drop your appreciation in the comments!

On DEV, sharing expertise sparks growth and tightens our community bonds. Found this helpful? A quick nod to the author goes a long way.

Get started