Seeking assistance in identifying the highest value in JavaScript (excluding the use of the max method)

Greetings and thank you for stopping by. I'm new to Javascript and currently facing an issue that I could use some help with. I am trying to identify the highest number from a set of variables using conditional statements within a function, but I seem to be stuck.

UPDATE: A big thank you to everyone who helped me out. I now have a clearer understanding of what areas I need to focus on for further learning.

const number1 = 103;
const number2 = 72;
const number3 = 189;

const getMax = (a, b, c) => {
  let max = a;
  
  if(b > max) {
    let max = b;
  } else if (c > max){
    let max = c;
  };
  
  return max;
}

getMax(number1, number2, number3);

console.log(`The maximum number is ${getMax}`);

Answer №1

When using the let keyword, variables have a block scope meaning they are only accessible within the block in which they were declared. Make sure to remove the additional let declarations inside your if/else statement.

Additionally, consider using multiple if statements instead of an else statement to ensure all conditions are checked independently and not just when the first one is satisfied.

It's important to pass the function call itself rather than just the object reference to the console.log for accurate results.

Lastly, make sure to avoid using undefined variables in your code for better functionality.

const number1 = 54;
const number2 = 72;
const number3 = 189;

const getMax = (a, b, c) => {
  let max = a;
  
  if(b > max) {
    max = b;
  }
  
  if (c > max){
    max = c;
  };
  
  return max;
}

console.log(`The maximum value is ${getMax(number1, number2, number3)}`);

Answer №2

There seems to be some issues in your code based on the comments provided, which makes the question unclear. Here is an alternative approach that may help...

function getMax() {
  const nums = arguments;
  var max = null;

  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
    if (max === null || num > max) {
      max = num;
    }
  }

  return max;
}

This function allows you to compare an infinite number of arguments and is not limited to a fixed number of inputs. You can use it like this:

const validExample1 = getMax(33, 72, 189, 4, 1); // Output: 189
const validExample2 = getMax(2, 2); // Output: 2
const validExample3 = getMax(320, 1, 8); // Output: 320
const validExample4 = getMax(-1, -200, -34); // Output: -1

Instead of using the arrow function expression, you can utilize the arguments keyword to access all values. If arrow functions are required, you can opt for the spread syntax (...) as shown below:

const getMax = ( ...nums ) => {
  var max = null;

  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
    if (max === null || num > max) {
      max = num;
    }
  }

  return max;
}

A complete example:

const number1 = 3;
const number2 = 72;
const number3 = 189;

function getMax() {

  const nums = arguments;
  var max = null;

  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
    if (max === null || num > max) {
      max = num;
    }
  }

  return max;
}

const result = getMax(number1, number2, number3);

console.log(`The maximum value is ${result}`);

Answer №3

It is important to exclude the "else" part in this scenario, as even if b is not greater than a, a comparison with c still needs to be made.

Two key points to consider are:

  1. A blockwise declaration of max is unnecessary since the outer value does not depend on the condition.

  2. The result of calling getMax is never utilized.

const getMax = (a, b, c) => {
    let max = a;

    if (b > max) max = b;
    if (c > max) max = c;

    return max;
}



console.log(`max value: ${getMax(2, 72, 189)}`);

Answer №4

I have noticed several issues. Initially, you set the maximum value twice. let max = a; and then you refer to max. Furthermore, the usage of else if is incorrect.

Consider the scenario where c < b < a. In this case, only the first if statement will be executed even though c is greater than a.

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

Capture video frames from a webcam using HTML and implement them in OPENCV with Python

While many may find it simple, I am facing a challenge in extracting video frames from HTML or JavaScript and utilizing them in my Python OPENCV project. I have a strong background in Python OPENCV and Deeplearning, but lack knowledge in HTML and JavaScr ...

a single line within a compartment

I am encountering an issue with the code snippet below, which is responsible for generating the location of different records within a table: return ( <TableRow> <TableCell > // some code_1 < ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Can you provide me with some insight on the process of iterating through an object utilizing the

I've developed an app that randomly plays a sound from a selected array when a button is pressed. Now, I want to add the functionality to display and play all sounds in the array upon request. I've explored various methods such as for loops and ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

Is it recommended to utilize addEventListener?

Is it better to use the addEventListener method in these scenarios? <input id="input" type="file" onchange="fun()> or document.getElementById("input").addEventListener("change", function() { fun(); }); What are the advantages of using one over ...

Is Implementing a Promise for Preprocessing in NodeJS Worth It?

Looking to achieve the following using NodeJS + Express: Client sends a post request with JSON document data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}; Need to call an external WebSocket service for sentiment analysis on the ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Issue with Ajax load function not functioning properly on Internet Explorer 8

My ajax load function is working in Chrome, Safari, Opera, and Firefox but it's not working in Internet Explorer 8. (using jQuery version "jquery-1.11.2") This is my JavaScript code: function solFrame(islem, sayfa) { if (sayfa == '') { ...

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Creating a feature that uses a button press to initiate an Ajax request based on a specific identifier

I'm looking for the most efficient way to structure a page that involves making Ajax calls. My main issue lies in setting up the event binding for when a user clicks a button. I'm struggling to find a method to pass the ID to the function that t ...

Troubleshooting problems with form submission through the combination of jQuery and Ajax

Hi there! I've got a couple of questions regarding form submission using jQuery and Ajax. Currently, I'm working on validating a login form using jQuery/Ajax requests. My goal is to disable the login submit button after a successful login. Howev ...

Is there a directive in AngularJS that allows for binding HTML templates using ng-bind-html

I'm working on a directive that has the ability to use dynamic templates with expressions inside them. The challenge I face is if I use ng-bind-html, the expression won't be evaluated properly. On the other hand, using ng-bin-template results in ...

How to Utilize Raw HTML in GWT with the Power of Jquery/Javascript?

Below is the HTML code snippet: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function( ...

Finding the occurrences of elements in an array using JavaScript

While browsing Stack Overflow, I stumbled upon a question that has yet to be answered: How can I count the occurrences of elements in a specific array using JavaScript?. let array = [6, 1, 5, 1, 1, 8, 2, 4, 6, 0] // Elements in array getOccurrence(array) ...

While attempting to deploy my project on Vercel by pulling in my code from GitHub, I ran into this error

As a self-taught Front End developer diving into building and hosting my first web page using React, I've encountered this warning. Any suggestions on how to resolve it? Cloning gitohub.com/Passion94/React-Apps (Branch: main, Commit: da89a2a) Cloning ...

Issue with Navigation Scrolling Feature on Wordpress

I am in the process of implementing a 'scroll-nav' for my website. To achieve this, I decided to separate the Navigation into two sections and incorporate some jQuery: <nav class="main-nav clearfix"> <?php wp_nav_menu(array('th ...

I'm all set to launch my express js application! What are the major security concerns that I need to keep in

As a beginner in deploying express applications, I find myself lacking in knowledge about the essential security measures that need to be taken before launching a web application. Here are some key points regarding my website: 1) It is a simple website ...

The Navbar's Toggle Icon Causes Automatic Window Resize

I implemented a mobile navigation bar using React and JS that slides in from the left when clicked. However, I encountered two issues: whenever I click on a menu button in the navbar or when my ad carousel moves, the window resizes for some reason. Additio ...