How to find maximum between two numbers in javascript using switch case? - javascript

I am trying to run with this code block but it does not work
Switch (num1>num2) {
case 0:
document.write(num2);
break;
case 1:
document.write(num1);
break;
}

You could use something simple as Math.max(5, 10);
const numOne = 5;
const numTwo = 10;
console.log(`Bigger number is: ${Math.max(numOne, numTwo)}`);
Or if you absolutely 'have to' use switch statement, you can try something like this:
const numOne = 5;
const numTwo = 10;
switch(true) {
case (numOne > numTwo):
console.log(`Bigger number is ${numOne}`);
break;
case (numOne < numTwo):
console.log(`Bigger number is ${numTwo}`);
break;
case (numOne === numTwo):
console.log(`${numOne} is equal to ${numTwo}`);
break;
default: console.log(false, '-> Something went wrong');
}

Logical operations return boolean on Javascript.
document.write writes HTML expressions or JavaScript code to a document, console.log prints the result on the browser console.
switch (num1>num2) {
case true:
console.log(num1);
break;
case false:
console.log(num2);
break;
}

switch (with a lower case s) uses strict comparison === so the value of a boolean like 11 > 10 will never === 0 or 1.
You need to test for the boolean if you want to do it this way:
let num1 = 10
let num2 = 20
switch (num1>num2) {
case false:
console.log(num2);
break;
case true:
console.log(num1);
break;
}
If for some reason you were given numbers you could explicitly cast them to booleans with something like case !!0: but that starts to get a little hard on the eyes.
If your goal is to find the max of two numbers, Math.max(num1, num2) is hard to beat for readability.

You would just use the greater than / less than inside of the switch statement.
var x = 10;
var y = 20;
switch(true) {
case (x > y):
console.log(x);
break;
case ( y > x):
console.log(y);
break;
}

Related

How can i check two variables in a switch-case statement?

The question is something like this.
You are given a cubic dice with 6 faces. All the individual faces have a number printed on them. The numbers are in the range of 1 to 6, like any ordinary dice. You will be provided with a face of this cube, your task is to guess the number on the opposite face of the cube.
Ex:
Input:
N = 6
Output:
1
Explanation:
For dice facing number 6 opposite face
will have the number 1.
I did it using a normal switch-case by checking all six faces and returning the respective die face number value, which passed my test cases. However, I need to simplify the code. Is it possible for me to do so?
oppositeFaceOfDice(N) {
//code here
switch(N){
case 1:return 6;
break;
case 6:return 1;
break;
case 2:return 5;
break;
case 5:return 2;
break;
case 3:return 4;
break;
case 4:return 3;
break;
default: return -1;
}
}
oppositeFaceOfDice(N) {
switch(N){
case 1||6 : return 6?1:6;
break;
case 2||5: return 2?5:2;
break;
case 3||4: return 4?3:4;
break;
}
}
Use an object literal instead of a switch statement:
function oppositeFaceOfDice(N) {
return {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}[N];
}
Or use #DavidThomas' suggestion above which is particularly clever:
function oppositeFaceOfDice(N) {
if(N < 1 || N > 6) return undefined;
return 7 - N;
}
Other than rewriting the codes, since in your case, the codes are very clear and easy to debug, you can remove the break statement since it's not necessary.
oppositeFaceOfDice(N) {
//code here
switch(N){
case 1:return 6;
case 6:return 1;
case 2:return 5;
case 5:return 2;
case 3:return 4;
case 4:return 3;
}
}

How to insert only one return code in JavaScript function with if statement?

I am trying to learn JavaScript and I wrote a function, that works as an easy calculator. It works OK, but I think there must be a way how to write only one return line of code. Any ideas how to simplify my code? (Without actually rewriting it all :)
Thank you for you help!
Here is my code:
There is no point in using return in the first place, i would use switch case instead of all these messy if else statements.
switch (operator) {
case '+':
alert(`Your result is ${number1 + number2}`);
break;
case '-':
alert(`Your result is ${number1 - number2}`);
break;
// and so on
}
let result = 0
if (operator === '+') result = number1 + number2
else if (operator === '-') result = number1 - number 2
alert(result)
Or use a switch
result = 0
switch (operator):
case '+':
result = number1 + number2
break
case '-':
result = number1 - number2
alert(result)
If your function doesn't need to return any value just just alert without return.

Create a calculation program that will be displayed by the browser

My program looks good to me but the retuned value is "undefinied" ... do you understand why?
function addition(nombreA,nombreB){
return nombreA + nombreB;
}
function soustraction(nombreA,nombreB){
return nombreA - nombreB;
}
function multiplication(nombreA,nombreB){
return nombreA * nombreB ;
}
function division(nombreA,nombreB){
return nombreA / nombreB ;
}
do {
var calculChoice = prompt("What do you want to do ?\n\n 1 - Addition\n 2 - Soustraction\n 3 - Multiplication\n 4 - Division");
}while(calculChoice != 1 && calculChoice != 2 && calculChoice != 3 && calculChoice != 4);
console.log(calculChoice);
do {
var premierNombre = prompt("entrez votre premier nombre");
var deuxiemeNombre = prompt("entrez votre second nombre");
} while (isNaN(premierNombre)||isNaN(deuxiemeNombre));
console.log(premierNombre,deuxiemeNombre);
switch(calculChoice) {
case 1:
var resultat = addition(premierNombre,deuxiemeNombre);
break;
case 2:
resultat = soustraction(premierNombre,deuxiemeNombre);
break;
case 3:
resultat = multiplication(premierNombre,deuxiemeNombre);
break;
case 4:
resultat = division(premierNombre,deuxiemeNombre);
break;
}
alert(`voici le résultat = ${resultat}`);
The switch statement will determine which calculation to perform by writing (1,2,3,4).
The first instruction (do while) allows you to enter the numbers 1,2,3,4. If the user does not write these numbers, the instruction executes again.
In the second statement (do while), if the user does not enter a number, it executes again.
Thank you for your time :)
prompt() function returns the result as a string, and not as a number. So you must convert each to integer using parseInt(number). If you don't do that, both your operator and the numbers are strings.
do {
var calculChoice = parseInt(prompt("What do you want to do ?\n\n 1 - Addition\n 2 - Soustraction\n 3 - Multiplication\n 4 - Division"));
} while(calculChoice != 1 && calculChoice != 2 && calculChoice != 3 && calculChoice != 4);
console.log(calculChoice);
do {
var premierNombre = parseInt(prompt("entrez votre premier nombre"));
var deuxiemeNombre = parseInt(prompt("entrez votre second nombre"));
} while (isNaN(premierNombre)||isNaN(deuxiemeNombre));
change your switch by:
switch(parseInt(calculChoice))) {
case 1:
var resultat = addition(premierNombre,deuxiemeNombre);
break;
case 2:
resultat = soustraction(premierNombre,deuxiemeNombre);
break;
case 3:
resultat = multiplication(premierNombre,deuxiemeNombre);
break;
case 4:
resultat = division(premierNombre,deuxiemeNombre);
break;
}
calculChoice is a string, and yu need parse to int
Resultat is also declared in the first switch statement case and it cant be used outside of that. You need to declare resultat before the switch statement.
let resultat=''
switch(calculChoice) {
case 1:
resultat = addition(premierNombre,deuxiemeNombre);
break;
case 2:
resultat = soustraction(premierNombre,deuxiemeNombre);
break;
case 3:
resultat = multiplication(premierNombre,deuxiemeNombre);
break;
case 4:
resultat = division(premierNombre,deuxiemeNombre);
break;
}

Javascript switch statement only triggering first case

a[2] is a random integer variable from 1 - 100. When it is less than than 33 it changes to red but when it is above 33 it stays black. Anyone got an idea why it ignores the last 2 cases?
<script type="text/javascript">
switch (a[2]) {
case < 33:
document.getElementByID('speechstat').style.color = "red";
break;
case >= 33 && <= 66:
document.getElementByID('speechstat').style.color = "blue";
break;
case > 66:
document.getElementByID('speechstat').style.color = "green";
break;
}
</script>
In JavaScript, switch statements look differently than what you've posted. For example, here's some documentation on switch statements on MDN.
If you want to check for ranges, you should check with regular if/else statements.
<script type="text/javascript">
var color;
// Check the possible value ranges.
if (a[2] < 33) { color = 'red'; }
else if (a[2] >= 33 && a[2] <= 66) { color = 'blue'; }
else if (a[2] > 66) { color = 'green'; }
document.getElementByID('speechstat').style.color = color;
</script>
In Javascript, you can't compare a variable with switch but you can do so indirectly as this post's answer shows: switch statement to compare values greater or less than a number
With a few edits and adding some html to check if everything works this is how you would do this in your case:
<!DOCTYPE html>
<html>
<body>
<p id="speechstat1"></p>
<p id="speechstat2"></p>
<p id="speechstat3"></p>
<script type="text/javascript">
var a = 34; //You can set this to whatever you want or a user's input
switch (true) {
case (a<33):
document.getElementById("speechstat1").innerHTML = "red works";
break;
case a>= 33 && a<= 66:
document.getElementById('speechstat2').innerHTML = "blue works";
break;
case a> 66:
document.getElementById("speechstat3").innerHTML = "green works";
break;
}
</script>
</body>
</html>
I put in .innerHTML just to show it works, in your case you can replace those
lines with whatever you want to make happen.
I changed Switch to switch
I changed .getElementByID to .getElementById Spelling matters!
If you are testing a variable for two conditions: case >= 33 <= 66: you
need to add the "and" operator case >= 33 **&&** <= 66:
I changed a[2] to a so it doesn't error out because it's not named
correctly
Overall it's easier to use if and else statements for something like this as Morgan Wilde mentioned.

highest and smallest number in javascript using only switch statement

i am wondering how to use switch statement to tell which is the highest and lowest number in javascript, without using math.max in my script, any help?
Pseudo-code only since it may be homework.
If it is, you should do some of the work yourself.
If it isn't you should be able to convert it to whatever language you want :-)
To work out the maximum and minimum of a and b:
def mymin(a,b): def mymax(a,b):
switch (a-b): switch (a-b):
case 0: case 0:
return a return a
default: default:
switch ((a-b)/abs(a-b)): switch ((a-b)/abs(a-b)):
case -1: case -1:
return a return b
default: default:
return b return a
It basically uses (a-b)/abs(a-b) which, assuming a and b are different will return -1 if b > a otherwise 1. You would get a divide-by-zero error if they were equal hence the outer switch to detect this first.
If you're looking for the minimum and maximum from a list, just set min and max initially to the first value in the list, then run through the list comparing each value with min and max and adjusting them accordingly:
def minAndMax(list):
min = first element in list
max = first element in list
for each element e in list:
min = mymin (min,e)
max = mymax (max,e)
return (min,max)
switch (true) {
case a > b:
min = b; max = a;
break;
case a < b:
min = a; max = b;
break;
case a == b:
// I know I could just use >= or <=
min = max = a;
}
Actually it's just uglier (or not?) form of if - else if - else statement.

Categories

Resources