• 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:

  • JavaScript Booleans Explained
  • Compress For Loops
  • The onabort Event in JavaScript
  • The JavaScript function Math.pow()

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us