• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Basics / One-Liner If-Else Statements

One-Liner If-Else Statements

One-Liner If-Else Statements

This is a common feature in many programming languages. Instead of writing an if-else on multiple lines, you can use the ternary operator to write the whole statement with one line of code.

For example:

const age = 12;
let ageGroup;

// LONG FORM
if (age > 18) {
  ageGroup = "An adult";
} else {
  ageGroup = "A child";
}

// SHORTHAND
ageGroup = age > 18 ? "An adult" : "A child";

However, do not overuse this. It can quickly make your code more verbose too. It is wise to replace only simple expressions with this to improve readability and reduce lines of code.

Source

https://medium.com/geekculture/20-javascript-snippets-to-code-like-a-pro-86f5fda5598e

Basics

Related Snippets:

  • How To Clone An Object In JavaScript
  • Javascript Conditionals Explained
  • How To Convert a String to Boolean in JavaScript
  • The JavaScript function Math.floor()

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers