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.

Heroku

The AI PaaS for deploying, managing, and scaling apps.

Heroku tackles the toil β€” patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Get Started

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM appsβ€”no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

πŸ‘‹ Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's dayβ€”leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay