I am encountering an issue with the multiple conditional if-else statements in JavaScript

While I am trying to grasp the concept of if-else statements with multiple conditions, I have encountered a slight issue that is causing some trouble. The 'else if' in the external condition section is being highlighted in my Visual Studio Code editor and displaying an error message saying 'Declaration or statement expected'. Could someone please help me troubleshoot this problem? Below is the code snippet that I am working on:

function solve(input) {
    let gender = (input.shift());
    let age = Number(input.shift());

    if (gender === 'Female') {
        if (age >= 18) {
            console.log('You are permitted on the website, lady.')
        }
    } else {
        console.log('You are not permitted on the website, lady.')
    } 
} else if (gender === 'Male') {
    if (age >= 18) {
        console.log('You are permitted on the website, dude.')
    } else {
        console.log('You are not permitted on the website, dude.')
    }
} else {
    console.log('Error')
}

solve(['Female', '13'])

Answer №1

One way to simplify this code is by reducing it to include only two variables: gender and age. These variables can then be inserted into the phrase that is displayed in the console.

It's important to note that just because there are two arguments passed to the function, it does not necessarily mean that each variable needs to be enclosed within separate if/else blocks.

function analyze(input) {
var gender, status;

    input[0] == 'Female'
      ? gender = 'lady'
      : gender = 'dude';
      
   parseInt(input[1]) >= 18
      ? status = 'are'
      : status = 'are not';
      
 console.log('You ' + status + ' permitted on the website, ' + gender + '.')
      
}

analyze(['Female', '13']); // Result: You are not permitted on the website, lady.
analyze(['Male', '19']); // Result: You are permitted on the website, dude.

Answer №2

As noted in the comments, there is an issue with your else if statement referring to a function block instead of the first if statement. By realigning your code and curly brackets, it should work correctly:

function processInfo(data) {
    let type = (data.shift());
    let value = Number(data.shift());

    if (type === 'Female') {
        if (value >= 18) {
            console.log('You are allowed on the website, ma\'am.');
        } else {
            console.log('You are not allowed on the website, ma\'am.');
        }
    } else if (type === 'Male') {
        if (value >= 18) {
            console.log('You are allowed on the website, sir.');
        } else {
            console.log('You are not allowed on the website, sir.');
        }
    } else {
        console.log('Error');
    }
}
processInfo(['Female', '13']);

It's advisable to end your console log statements with a semicolon (e.g. console.log("output");). You can refer to this post for more insights on using semicolons to terminate statements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up Webpack for Node applications

My current challenge involves configuring Webpack for a node app that already exists. I am encountering various issues and struggling to find solutions or even know where to begin. Situation The project's folder structure is as follows: +---app +-- ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

Show an Array of Nested JSON API information on an HTML page using jQuery/JavaScript

Recently, I've delved into the world of jQuery, JavaScript, and AJAX while experimenting with an API that I designed. The backend result I received looks like this: [ { "id": 1, "choice_text": "They work on List View generally", ...

Ways to schedule the execution of a script at a specific time using Node.js

Every time the readDirectory function is called, it checks if any file created date is more than 30 days ago and removes that file from the directory. While this functionality is working correctly, I am concerned about its efficiency. To address this issue ...

Organize an array of JSON objects based on a specific key and eliminate any duplicated entries

I am grappling with the challenge of grouping an array of JSON objects by the id_commande attribute and eliminating any duplicates. I am finding it quite perplexing to figure out a solution to this issue without relying on a library like lodash. Ideally, I ...

Incorporate data from a CSV file into an HTML table on the fly with JavaScript/jQuery

I have a CSV file that is generated dynamically by another vendor and I need to display it in an HTML table on my website. The challenge is that I must manipulate the data from the CSV to show corrected values in the table, only displaying products and not ...

Troubleshooting a Simple JavaScript Game: Mastermind Edition

Currently, I am working on a JavaScript version of the well-known board game "Mastermind". I have been facing some fundamental issues, mainly with JavaScript arrays and how to reference their values or elements. Despite spending quite a bit of time trying ...

Establishing a system for utilizing barcode multimarkers in AR.js

Currently, I am attempting to configure AR.js for multimarkers, as illustrated in this image: barcode markers on wall. The plan is to display a single video within the area encompassed by the markers. Despite my efforts to set up the multimarker player an ...

Trim JSON using JavaScript

I'm currently working on reducing a JSON array. Within the array, there are other objects, and my goal is to convert their attributes into their own separate array. Reduce Function: // parsed.freight.items is the path var resultsReduce = parsed.frei ...

Scroll to the bottom of a textarea in React by automatically shifting focus

I am having issues with appending text to a textarea and then scrolling to the bottom in order to keep the latest content within view. However, it seems that this process is causing the browser to crash or run out of memory. Can someone provide assistance ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

Highcharts failing to connect the dots with lines between data points

UPDATE: After some investigation, it turns out that the issue stemmed from inconsistent intervals. By following the solution outlined in this post, the problem was easily resolved. I have implemented highcharts to create a chart, where the initial data po ...

Unable to execute PHP code within a PHP file loaded through AJAX

I'm currently in the process of developing a webshop using WooCommerce. I have successfully implemented two switch buttons that allow users to toggle between 'List view' and 'Grid view'. Specifically, for the list view button, I am ...

How do I control the opening and closing of my modal using redux state management?

When the user clicks on Checkout within the <CheckoutButton/> component below, the modal should appear. However, instead of this behavior, the modal is appearing when I reload my browser, which is not the expected outcome. What could be causing this ...

Best practice for integrating configuration settings into a Redux application

One essential step before launching my application is to read the config.json file. This file contains the URLs to my backend services, which will be utilized in my Redux action creators. I have contemplated two different approaches: Fetching the JSON a ...

Angular's ngSubmit is malfunctioning

Check out this code snippet: <form data-ng-submit="ctrl.filter()" novalidate="true" class="search-filter ng-valid ng-dirty ng-valid-parse"> <fieldset> <div class="search-filter-group"> <div class="s ...

Guide on transmitting data from a pre-populated React input field to Express server

I have integrated a simple support form in my React App using Express and Sendgrid. The post request is functioning with an input form setup like this: support.jsx <form method="POST" action="http://localhost:4000/support"> ...

Achieving dynamic page number display in relation to Pagination in ReactJS

I have a website that was created by someone else, and the pagination feature is becoming overwhelming for me as I am not a coder or developer. Image Link Currently, my navigation pagination displays 17 pages. I would like to limit this to only showing 1 ...

Issue with Vue and Axios: Error retrieving API data using coinmarketcap key

As a beginner in programming, I'm currently working on fetching API data using Axios and Vue.js. However, I'm facing difficulties in passing the data through Axios. Below is the Nodejs code snippet for requesting the API: const rp = require(&apos ...

Displaying various elements with distinct properties in React using ES6

<---------------------MODIFICATION------------------------> I initially thought I needed multiple onChange functions, but after reviewing the answers provided, I discovered a solution thanks to the helpful user's response. With some experimenta ...