Best Website-BuildersBest Website-Builders
    What's Hot

    Cheltenham Gold Cup 2023: A Plus Tard, Galopin Des Champs, Bravemansgame among runners

    March 16, 2023

    Musicians, Machines, and the AI-Powered Future of Sound

    March 16, 2023

    England: Gareth Southgate sticks with players he trusts for Euro 2024 qualifiers against Italy and Ukraine

    March 16, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      Sigil 1.9.30 | Neowin

      March 16, 2023

      Root’s CS ranked highest to lowest in the latest report [LIST]

      March 16, 2023

      Marshall Wace LLP Expands Roth CH Acquisition IV Co. Asset Holdings

      March 16, 2023

      Press and Information Bureau

      March 16, 2023

      SK Siltron CSS places Bay County at the forefront of growing domestic demand for semiconductor chips

      March 16, 2023
    • Joomla

      PANDACU Studio Website Development Cooperation First Page Sage SEO Dsign Chicago adstargets Cardinal Digital Agency

      March 16, 2023

      Bluehost Review: Best Solution for Your Web Hosting Needs? – WISH-TV | Indianapolis News | Indiana Weather

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023

      Best Free Web Hosting Services to Choose for Your Site – WISH-TV | Indianapolis News | Indiana Weather

      March 14, 2023
    • PHP

      Husband of Jared Bridegan’s Ex-Wife Charged with Murder of Microsoft Exec

      March 16, 2023

      Pregnancy is becoming more dangerous in the US, new data shows, especially for blacks

      March 16, 2023

      These African Net Sponges Really Help Smooth Skin

      March 16, 2023

      Gwyneth Paltrow tried rectal ozone therapy.Here’s what the experts think

      March 16, 2023

      TikTok’s Jim Bros Eat Dog Food, Experts Say It May Be Harmful

      March 16, 2023
    • UX

      Alibaba’s AliExpress Prioritizes Spain for Overseas Growth, Focuses on South Korea

      March 16, 2023

      Why Mobile and Biometrics Go Mainstream in Cloud-Based Access Control Systems – Commercial Observer

      March 16, 2023

      Quigley Hires Dalton Mangin as Chief Revenue Officer

      March 16, 2023

      Brian Young, Vice President of Iron Mountain, Delves into Optimized User Experience, Digitization and More

      March 16, 2023

      Ericsson and MediaTek perform 5G carrier aggregation

      March 16, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Intel’s record 56-core rig consumes as much power as a tumble dryer

      March 16, 2023

      Google Glass Enterprise finally bites the dust

      March 16, 2023

      Can’t wait for Microsoft’s new ChatGPT feature to roll out to everyone

      March 16, 2023

      The latest Pixel 7a has leaked out and is confirmed to be coming soon

      March 16, 2023

      Microsoft brings AI to Microsoft 365.tech radar

      March 16, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » How to simplify if statements in JavaScript
    JavaScript

    How to simplify if statements in JavaScript

    websitebuildersnowBy websitebuildersnowMarch 14, 2023No Comments4 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Conditional statements are an important part of JavaScript. It can execute code based on whether a certain condition is true or false, and multiple can be nested. other statements (and other than that) to evaluate multiple conditions.


    But here comes the problem. if…otherwise Chaining can quickly make things messy and result in code that is hard to read and understand.

    Learn how to do long and complicated refactorings if…else if…else It makes the conditional chain a more concise, cleaner and easier to understand version.


    Complex if…else chains

    Writing clean, concise, and understandable code is essential when writing complex if…else statements in JavaScript. for example, if…otherwise A conditional chain in the function below:

     function canDrink(person) {
      if(person?.age != null) {
        if(person.age < 18) {
         console.log("Still too young")
        } else if(person.age < 21) {
          console.log("Not in the US")
        } else {
          console.log("Allowed to drink")
        }
      } else {
        console.log("You're not a person")
      }
    }

    const person = {
      age: 22
    }

    canDrink(person)

    The logic here is simple.first time If The statement is Man the object is Year property (otherwise he or she is not a person).among them If block, added if… if not… if A chain that basically says:

    If the person is under the age of 18, they are too young to drink. If you are under the age of 21, you are under the legal drinking age in the United States. Otherwise, they can legally get their drinks.

    The code above is valid, but the nesting makes it difficult to understand. Luckily, you can refactor your code to make it cleaner and easier to read. guard clause.

    guard clause

    anytime If In the statement that wraps all your code, guard clause To remove all nesting:

     function canDrinkBetter() {
      if(person?.age == null) return console.log("You're not a person")

      if(person.age < 18) {
        console.log("Still too young")
      } else if(person.age < 21) {
        console.log("Not in the US")
      } else {
        console.log("Allowed to drink")
      }
    }

    At the start of the function, we defined a guard clause to indicate that the function should exit if certain conditions are not met. canDrinkBetter() It works immediately (logs “you are not a person” to the console).

    However, if the condition is met, if…otherwise Chain to see applicable blocks. Running the code produces the same result as the first example, but this code is easier to read.

    don’t use single return

    You might argue that the above technique is not a good programming principle because you are using multiple returns in the same function. Also, you might think it’s better to use only one return statement (aka single return policy).

    However, this is a terrible way to write code because you end up in the same crazy nested situation you saw in the first code sample.

    i.e. you can use multiple return Statements to further simplify the code (and remove nesting):

     function canDrinkBetter() {
      if(person?.age == null) return console.log("You're not a person")

      if(person.age < 18) {
        console.log("Still too young")
        return
      }

      if(person.age < 21) {
        console.log("Not in the US")
        return
      }

      console.log("Allowed to drink")
    }

    This code works the same as the previous two examples, just a little cleaner.

    The last code block was cleaner than the first two, but still not the best.

    instead of lengthening if…otherwise Chaining within one function allows you to create another function canDrinkResult() It will do the check for you and return the result:

     function canDrinkResult(age) {
      if(age < 18) return "Still too young"
      if(age < 21) return "Not in the US"
      return "Allowed to drink"
    }

    Then, inside the main function, first apply the guard clause, then canDrinkResult() Use a function (with age as a parameter) to get the result.

     function canDrinkBetter() { 
      if(person?.age == null) return console.log("You're not a person")

      let result = canDrinkResult(person.age)
      console.log(result)
    }

    In this case, I delegated the task of checking drinking age to a separate function and called it only when necessary. This makes the code cleaner and easier to work with than all the previous examples.

    Keep else out of conditionals

    You learned how to use guard clauses and function extraction techniques to refactor complex, nested conditional chains into shorter, more readable ones.

    please try to keep other than that Use both guard clauses and function extraction techniques to keep statements as far away from conditionals as possible.

    New to using JavaScript? if…otherwise Statement, start with the basics.



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleReddit – Dive into anything
    Next Article Facebook-owner Meta to cut 10,000 staff
    websitebuildersnow
    • Website

    Related Posts

    The safe word for the npm registry is Socket • The Register.

    March 16, 2023

    Learn JavaScript Online: The 10 Best Courses for 2023

    March 15, 2023

    Understanding AngularJS, Its Benefits and Challenges | Spiceworks

    March 14, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    Cheltenham Gold Cup 2023: A Plus Tard, Galopin Des Champs, Bravemansgame among runners

    March 16, 2023

    Musicians, Machines, and the AI-Powered Future of Sound

    March 16, 2023

    England: Gareth Southgate sticks with players he trusts for Euro 2024 qualifiers against Italy and Ukraine

    March 16, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.