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

Invoking one service from another service in AngularJS

I'm trying to access a service from another service and use the returned object for some operations. However, I keep encountering a TypeError: getDefinitions is not a function error. Here is the code for my services and controller: definitions.servi ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

achieve precise outcomes using mapping techniques

I am currently learning react.js and encountering an issue with obtaining specific results on the map. Below is the code I am working with: render(){ const friends = [ {id:1, name: 'Dave',age:50}, {id:2,name: 'Kellie',age:42}, {id:3, ...

Tips for effectively combining an array with jQuery.val

My goal is to have multiple form fields on a page, gather the input results into an array, and then store them in a database. This process was successful for me initially. However, when I introduced an autocomplete function which retrieves suggestions from ...

"Integrating JavaScript in C# Code Behind: A Step-by-Step Guide

Is there a way to trigger this javascript function using C# code in the backend when the page loads? Your assistance is greatly appreciated, thank you. <script type="text/javascript"> document.onkeydown = function (event) { event = ( ...

The navigation bar is positioned with white space above it

Currently working on a website design and facing an issue with adding a clickable button to the Nav-bar. Noticed some white-space above the Nav-bar which is not desired. I had previously posted a similar question but unable to identify the CSS error causi ...

Looking to duplicate a row of input fields while maintaining the same validation rules as the original row?

form <form action="assign_web_menu_action.php" method="post" name="form1" id="form1" > <table id='menuAssign'> <tbody> <tr class="clone_row"> <td> <input type="text" name="menuname[]" id="menuname1" ...

Do you know if there is a setting in prettier that allows line breaks to be preserved?

Encountering an issue with the prettier extension in VS Code, Whenever I enter the following code: const result = await pool .request() .query('select NumberPlate, ID, TimeStamp from RESULTS order by ID'); and save the file, it con ...

The specified variable will not be visible in the window object

I recently created a JavaScript code snippet that looks like this: let var1 = 1; window.var2 = 2; After running the code in the Chrome console, I entered window to inspect the global window object. Surprisingly, only the second variable appeared and the ...

Update the input type on the fly

Hey there, I've got a bit of an unusual question. I'm looking to create a form with fields that vary for each user, like a text input or a checkbox. I attempted using Angular to achieve this: <div ng-controller="myCtrl" ng-repeat="x in prova" ...

Issue arises when Protractor is unable to compare a variable with a web element due to unresolved promises

My strategy for this examination was to extract the inner text of an element, modify it, and then verify that the change had taken place by comparing the element with the variable. var fixedValue = element(by.xpath('/html/body/section/div/section/sec ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

What is the best way to incorporate Form Projection into Angular?

I have been attempting to incorporate form projection in Angular, inspired by Kara Erickson's presentation at Angular Connect in 2017, but I am encountering difficulties and errors along the way. view talk here The code provided in the slides is inco ...

What could be the reason for my select list not showing up?

Hello fellow developers, I am currently working on creating a dynamic tablerow that allows users to fill in input fields and select options from a list for each cell. While the input fields are functioning properly, I am facing an issue with displaying th ...

Issues with displaying HTML5 audio player in iOS Chrome and Safari browsers

My html5/jquery/php audio player is working well on desktop browsers, but when I tried testing it on iOS, all I could see was a grey track bar. I suspect that the controls are hidden behind the track bar because sometimes the associated file starts playing ...

Uncovering the User's Browser Specifically for UC-Mini and Opera-Mini

I'm in need of a script that can identify if the user's browser is uc-mini or opera-mini. These particular browsers do not support the "transition" feature. Therefore, when this specific browser is detected, I would like to deactivate the "trans ...

Issue: A child component's function is unable to update the state of the parent component

I have been working on a project using React. Below is the code for the parent component: class Parent extends Component { constructor(props) { super(props); this.state = { deleteConfirm: false }; } onDelete = pass => { thi ...

What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply retu ...

Having trouble with my Bootstrap 4 navbar button - what am I doing wrong?

After conducting research online, I found myself unable to resolve my issue due to my lack of proficiency in English. I apologize for any confusion caused and would like to revisit the topic. The problem lies with my navbar toggle that is not functioning ...

Is there a way to instantly remove script from the document head using jQuery instead of waiting a few seconds?

I currently have a setup where I am utilizing Google Maps in production. To make this work, I must include a script in the head of my document that contains the API key for the Google Maps JavaScript API that my application relies on. The API key is being ...