Jump to content

How to convert if to switch statement in JavaScript? (beginner JavaScript)

Go to solution Solved by RockSolid1106,
2 hours ago, c0d0ps said:

Hi thanks for answer,

as noted in my (second) previous comment even on machineActive=true  it shows Your Score is 75 and not the console log for 

  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

screenshot

  Hide contents

-snip-

 

Console log will log the text to the *console*. What you want to do is set the value of the paragraph element, for which variables have already been defined near the end of the code. All you need to do is set the value of the variable "response" to the text.

console.log("That's a great score, you really know your stuff.";);
// to
response = "That's a great score, you really know your stuff.";

 

 

 

2 hours ago, c0d0ps said:
  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

break should also have the same indentation as the rest of the block in the case.

Corrected:

2 hours ago, c0d0ps said:
  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
      break;

 

 

After all the changes, your code should look like this:

let response;
let score = 75;
let machineActive = true;

  switch (machineActive) {
  case score <= 0 || score >= 100:
      response = "This is not possible, an error has occurred.";
      break;

  case score >= 0 && score <= 19: 
      response = 'That was a terrible score — total fail!';
      break;

  case score >= 20 && score < 39:
      response = 'You did a passable job, not bad!';
      break;

  case score >= 40 && score < 69:
      response = 'You did a passable job, not bad!';
      break;

  case score >= 70 && score < 89:
     response = "That's a great score, you really know your stuff.";
      break;

  case score >= 90 && score < 100:
      response = 'What an amazing score! Did you cheat? Are you for real?';
      break;

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

 

Spoiler

image.png.a6f9386c8d2c066c53d7480c5a20ae0b.png

 

Hi I'm using a .html and .js file

Languages: HTML, CSS, JavaScript
Level: Beginner

 

Problem:

I'm guessing switch statements don't work with if else statements?

 

Updated to bring more clarity

To underline the point of the exercise here:

the goal is to convert if else statements to a switch version of the statement (like noted in my under "JavaScript" headline).

Not necessarily using an if else statement (which I tried to do) in a switch statement.

 

JavaScript

See updated code further down

Spoiler
let response;
let score = 75;
let machineActive = false;
function setScore() {
  let choice = select.value;

  switch (machineActive) {
  case choice1:
    if (score <= 0 || score >= 100) {
      response = "This is not possible, an error has occurred.";}

  case choice2:
      if (score >= 0 && score <= 19) {
      response = "That was a terrible score — total fail!";}

  case choice3:
    if (score >= 20 && score < 39) {
      response = "You did a passable job, not bad!";}

  case choice4:

    if (score >= 40 && score < 69) {
      response = "You did a passable job, not bad!";}

  case choice5:
    if (score >= 70 && score < 89) {
      response = "That's a great score, you really know your stuff.";}

  case choice6:
    if (score >= 90 && score < 100) {
      response = "What an amazing score! Did you cheat? Are you for real?";}

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

 

if-else Code from last exercise that i'm converting to a switch statement

Spoiler
        let response;
        let score = 75;
        let machineActive = false;

        if (machineActive === false) {
            response = "Switch the machine on.";}

        if (score <= 0 || score >= 100) {
            response = "This is not possible, an error has occurred.";}

        if (score >= 0 && score <= 19) {
            response = "That was a terrible score — total fail!";}

        if (score >= 20 && score < 39) {
            response = "You did a passable job, not bad!";}

        if (score >= 40 && score < 69) {
            response = "You did a passable job, not bad!";}

        if (score >= 70 && score < 89) {
            response = "That's a great score, you really know your stuff.";}

        if (score >= 90 && score < 100) {
            response = "What an amazing score! Did you cheat? Are you for real?";}

        // Add your code here

        // Don't edit the code below here!

        section.innerHTML = ' ';
        let para1 = document.createElement('p');
        let para2 = document.createElement('p');

        para1.textContent = `Your score is ${score}`;
        para2.textContent = response;

        section.appendChild(para1);
        section.appendChild(para2);

 

Updated code:

Spoiler
let response;
let score = 75;
let machineActive = false;

  switch (machineActive) {
  case score <= 0 || score >= 100:
      console.log("This is not possible, an error has occurred.");
  break;

  case score >= 0 && score <= 19: 
      console.log('That was a terrible score — total fail!');
  break;

  case score >= 20 && score < 39:
      console.log('You did a passable job, not bad!');
  break;

  case score >= 40 && score < 69:
      console.log('You did a passable job, not bad!');
  break;

  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

  case score >= 90 && score < 100:
      console.log('What an amazing score! Did you cheat? Are you for real?');
  break;

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

Why a switch statement here? This seems perfectly handled with just if statements, since I don't see the logic in first choosing the score category to compare in.

 

Otherwise, something like this may work: https://stackoverflow.com/questions/5464362/javascript-using-a-condition-in-switch-case

Crystal: CPU: i7 7700K | Motherboard: Asus ROG Strix Z270F | RAM: GSkill 16 GB@3200MHz | GPU: Nvidia GTX 1080 Ti FE | Case: Corsair Crystal 570X (black) | PSU: EVGA Supernova G2 1000W | Monitor: Asus VG248QE 24"

Laptop: Dell XPS 13 9370 | CPU: i5 10510U | RAM: 16 GB

Server: CPU: i5 4690k | RAM: 16 GB | Case: Corsair Graphite 760T White | Storage: 19 TB

Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, tikker said:

Why a switch statement here? This seems perfectly handled with just if statements, since I don't see the logic in first choosing the score category to compare in.

 

Otherwise, something like this may work: https://stackoverflow.com/questions/5464362/javascript-using-a-condition-in-switch-case

Test your skills: Conditionals - Learn web development | MDN (mozilla.org)

I am doing the mozilla online course - javascript exercise

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, c0d0ps said:

Problem:

I'm guessing switch statements don't work with if else statements?

You're using switch statements wrong.

 

First, your cases need to be values, not just words. The switch statement takes the value in the parenthesis and jumps to the case matching that value (or default if there isn't one).

 

var temp = 2;

switch(temp) {
    case 1: return "one";
    case 2: return "two";
    case 3: return "three";
    default: return "I give up."
}

// this would return the value "two".

 

Second, using a switch with a boolean is pointless (and probably not within specification); just use if-else if that's the case.

 

var temp = false;

switch(temp) {
    case true: return "true";
    case false: return "false";
    default: return "wat?" // can't ever get here
}

// is exactly the same as

if (temp) {
    return "true";
} else {
    return "false";
}

 

Main System (Byarlant): Ryzen 7 5800X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 16GB G.Skill DDR4 3200MT/s CAS-14 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 960 PRO 512GB / 4× Crucial MX500 2TB (RAID-0) | Corsair RM750X | Mellanox ConnectX-3 10G NIC | Inateck USB 3.0 Card | Hyte Y60 Case | Dell U3415W Monitor | Keychron K4 Brown (white backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB RAM (soldered) | Vega 6 Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi (all-around awesome machine)

 

Proxmox Server (Veda): Ryzen 7 3800XT | AsRock Rack X470D4U | Corsair H80i v2 | 64GB Micron DDR4 ECC 3200MT/s | 4x 10TB WD Whites / 4x 14TB Seagate Exos / 2× Samsung PM963a 960GB SSD | Seasonic Prime Fanless 500W | Intel X540-T2 10G NIC | LSI 9207-8i HBA | Fractal Design Node 804 Case (side panels swapped to show off drives) | VMs: TrueNAS Scale; Ubuntu Server (PiHole/PiVPN/NGINX?); Windows 10 Pro; Ubuntu Server (Apache/MySQL)


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s CAS-22 | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / Seagate 1.5TB HDD | Corsair CX450M | Viewcast Osprey 260e Video Capture | Mellanox ConnectX-2 10G NIC | LG UH12NS30 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Camera: Sony ɑ7II w/ Meike Grip | Sony SEL24240 | Samyang 35mm ƒ/2.8 | Sony SEL50F18F | Sony SEL2870 (kit lens) | PNY Elite Perfomance 512GB SDXC card

 

Network:

Spoiler
                           ┌─────────────── Office/Rack ────────────────────────────────────────────────────────────────────────────┐
Google Fiber Webpass ────── UniFi Security Gateway ─── UniFi Switch 8-60W ─┬─ UniFi Switch Flex XG ═╦═ Veda (Proxmox Virtual Switch)
(500Mbps↑/500Mbps↓)                             UniFi CloudKey Gen2 (PoE) ─┴─ Veda (IPMI)           ╠═ Veda-NAS (HW Passthrough NIC)
╔═══════════════════════════════════════════════════════════════════════════════════════════════════╩═ Narrative (Asus USB 2.5G NIC)
║ ┌────── Closet ──────┐   ┌─────────────── Bedroom ──────────────────────────────────────────────────────┐
╚═ UniFi Switch Flex XG ═╤═ UniFi Switch Flex XG ═╦═ Byarlant
   (PoE)                 │                        ╠═ Narrative (Cable Matters USB-PD 2.5G Ethernet Dongle)
                         │                        ╚═ Jesta Cannon*
                         │ ┌─────────────── Media Center ──────────────────────────────────┐
Notes:                   └─ UniFi Switch 8 ─────────┬─ UniFi Access Point nanoHD (PoE)
═══ is Multi-Gigabit                                ├─ Sony Playstation 4 
─── is Gigabit                                      ├─ Pioneer VSX-S520
* = cable passed to Bedroom from Media Center       ├─ Sony XR65A80K (Google TV)
** = cable passed from Media Center to Bedroom      └─ Work Laptop** (Startech USB-PD Dock)

 

Retired/Other:

Spoiler

Laptop (Rozen-Zulu): Sony VAIO VPCF13WFX | Core i7-740QM | 8GB Patriot DDR3 | GT 425M | Samsung 850EVO 250GB SSD | Blu-ray Drive | Intel 7260 Wifi (lived a good life, retired with honor)

Testbed/Old Desktop (Kshatriya): Xeon X5470 @ 4.0GHz | ZALMAN CNPS9500 | Gigabyte EP45-UD3L | 8GB Nanya DDR2 400MHz | XFX HD6870 DD | OCZ Vertex 3 Max-IOPS 120GB | Corsair CX430M | HooToo USB 3.0 PCIe Card | Osprey 230 Video Capture | NZXT H230 Case

TrueNAS Server (La Vie en Rose): Xeon E3-1241v3 | Supermicro X10SLL-F | Corsair H60 | 32GB Micron DDR3L ECC 1600MHz | 1x Kingston 16GB SSD / Crucial MX500 500GB

Link to comment
Share on other sites

Link to post
Share on other sites

Switch only really makes sense if you have a finite list of concrete values to compare against (e.g. something like an enum). Your current if-statement includes things like

if (score <= 0 || score >= 100) {

which is not a finite list(1). Meaning you'd have to write something like:

switch (score) {
   case (smallest possible negative number):
   
   case -3:
   case -2:
   case -1:
   case 0:
   case 100:
   case 101:
   case 102:
   case 103:
   
   case (largest possible positive number):
       // logic you want to execute in this case
}

 

1) Technically the list is finite, because e.g. 32/64/… bit integers only have so many values… but that's still a ton of values you don't want to include in a switch statement.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

What is the original assigment? I think there is some confusion, are you supposed to write code that "switches the machine on" or write code using a switch statement?

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, Alvin853 said:

What is the original assigment? I think there is some confusion, are you supposed to write code that "switches the machine on" or write code using a switch statement?

Conditionals 3

Spoiler

In this task you need to take the code you wrote for the second task, and rewrite the inner if...else if...else to use a switch statement instead.

Try updating the live code below to recreate the finished example:

Conditionals 2

 

Update:
TLDR 

the goal is to convert if else statements to a switch version of the statement (like noted in my under "JavaScript" headline).

Not necessarily using an if else statement (which I tried to do) in a switch statement.

I will work on better placing though thank you.

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

16 minutes ago, c0d0ps said:

Test your skills: Conditionals - Learn web development | MDN (mozilla.org)

I am doing the mozilla online course - javascript exercise

Hmm, nothing else besides the stackoverflow answer comes to mind then. It seems like a little bit of an odd example for switch statements to me.

Crystal: CPU: i7 7700K | Motherboard: Asus ROG Strix Z270F | RAM: GSkill 16 GB@3200MHz | GPU: Nvidia GTX 1080 Ti FE | Case: Corsair Crystal 570X (black) | PSU: EVGA Supernova G2 1000W | Monitor: Asus VG248QE 24"

Laptop: Dell XPS 13 9370 | CPU: i5 10510U | RAM: 16 GB

Server: CPU: i5 4690k | RAM: 16 GB | Case: Corsair Graphite 760T White | Storage: 19 TB

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, c0d0ps said:

Conditionals 3

  Hide contents

In this task you need to take the code you wrote for the second task, and rewrite the inner if...else if...else to use a switch statement instead.

Try updating the live code below to recreate the finished example:

Conditionals 2

  Hide contents

For this task you are given three variables:

  • machineActive — contains an indicator of whether the answer machine is switched on or not (true/false)
  • score — Contains your score in an imaginary game. This score is fed into the answer machine, which provides a response to indicate how well you did.
  • response — begins uninitialized, but is later used to store a response that will be printed to the output panel.

You need to create an if...else structure that checks whether the machine is switched on and puts a message into the response variable if it isn't, telling the user to switch the machine on.

Inside the first, you need to nest an if...else if...else that puts appropriate messages into the response variable depending on what the value of score is — if the machine is turned on. The different conditional tests (and resulting responses) are as follows:

  • Score of less than 0 or more than 100 — "This is not possible, an error has occurred."
  • Score of 0 to 19 — "That was a terrible score — total fail!"
  • Score of 20 to 39 — "You know some things, but it\'s a pretty bad score. Needs improvement."
  • Score of 40 to 69 — "You did a passable job, not bad!"
  • Score of 70 to 89 — "That\'s a great score, you really know your stuff."
  • Score of 90 to 100 — "What an amazing score! Did you cheat? Are you for real?"

Try updating the live code below to recreate the finished example. After you've entered your code, try changing machineActive to true, to see if it works.

Yeah that's a very bad example for switch statements, the only way I could see this working is by extracting the first digit, but I'm pretty sure this is not the intended solution:

 

switch(Math.floor(score/10)) {
  case 0:
  case 1:  
    response = "That was a terrible score --- total fail!";
    break;
  case 2:
  case 3:
    response = "You know some things, but it\'s a pretty bad score. Needs improvement.";
    break;
  .
  .
  .
  default: 
    response = "This is not possible, an error has occured."
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, Alvin853 said:

Yeah that's a very bad example for switch statements, the only way I could see this working is by extracting the first digit, but I'm pretty sure this is not the intended solution:

 

SNIP

So this is what I came up with thanks to the stack overflow linked above.

Spoiler
let response;
let score = 75;
let machineActive = false;

  switch (true) {
  case score <= 0 || score >= 100:
      response = "This is not possible, an error has occurred.";

  case score >= 0 && score <= 19: 
      response = "That was a terrible score — total fail!";

  case score >= 20 && score < 39:
      response = "You did a passable job, not bad!";

  case score >= 40 && score < 69:
      response = "You did a passable job, not bad!";

  case score >= 70 && score < 89:
      response = "That's a great score, you really know your stuff.";

  case score >= 90 && score < 100:
      response = "What an amazing score! Did you cheat? Are you for real?";

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

Unfortunately it says "machine is not on" even when change let machineActive = false; to true

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, c0d0ps said:

So this is what I came up with thanks to the stack overflow linked above.

  Hide contents
let response;
let score = 75;
let machineActive = false;

  switch (true) {
  case score <= 0 || score >= 100:
      response = "This is not possible, an error has occurred.";

  case score >= 0 && score <= 19: 
      response = "That was a terrible score — total fail!";

  case score >= 20 && score < 39:
      response = "You did a passable job, not bad!";

  case score >= 40 && score < 69:
      response = "You did a passable job, not bad!";

  case score >= 70 && score < 89:
      response = "That's a great score, you really know your stuff.";

  case score >= 90 && score < 100:
      response = "What an amazing score! Did you cheat? Are you for real?";

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

Unfortunately it says "machine is not on" even when change let machineActive = false; to true

You'll need to add "break" statements after each of your response assignments, as it is doing what you want it to do but then also executing the default statement, setting your response to the default one. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#what_happens_if_i_forgot_a_break

Link to comment
Share on other sites

Link to post
Share on other sites

10 minutes ago, mikat said:

You'll need to add "break" statements after each of your response assignments, as it is doing what you want it to do but then also executing the default statement, setting your response to the default one. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#what_happens_if_i_forgot_a_break

Thank you

This is the code after fixing the no break problems and exchanging response to console.log();

 

Only problem is nothing shows up besides "Your score is 75."

Spoiler
let response;
let score = 75;
let machineActive = false;

  switch (machineActive) {
  case score <= 0 || score >= 100:
      console.log("This is not possible, an error has occurred.");
  break;

  case score >= 0 && score <= 19: 
      console.log('That was a terrible score — total fail!');
  break;

  case score >= 20 && score < 39:
      console.log('You did a passable job, not bad!');
  break;

  case score >= 40 && score < 69:
      console.log('You did a passable job, not bad!');
  break;

  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

  case score >= 90 && score < 100:
      console.log('What an amazing score! Did you cheat? Are you for real?');
  break;

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

15 minutes ago, c0d0ps said:

Thank you

This is the code after fixing the no break problems and exchanging response to console.log();

 

Only problem is nothing shows up besides "Your score is 75."

  Hide contents
let response;
let score = 75;
let machineActive = false;

  switch (machineActive) {
  case score <= 0 || score >= 100:
      console.log("This is not possible, an error has occurred.");
  break;

  case score >= 0 && score <= 19: 
      console.log('That was a terrible score — total fail!');
  break;

  case score >= 20 && score < 39:
      console.log('You did a passable job, not bad!');
  break;

  case score >= 40 && score < 69:
      console.log('You did a passable job, not bad!');
  break;

  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

  case score >= 90 && score < 100:
      console.log('What an amazing score! Did you cheat? Are you for real?');
  break;

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

 

The formatting is off (not a problem atm but it's better to start right), you replaced the response assignments with console.log and the machine is off, your console.log's were not ending up in the paragraph but in the console, and because the machine was off only the first "an error has occured" message was being logged to the console.
 

let response;
let score = 75;
let machineActive = true;

switch (machineActive) {
  case score <= 0 || score >= 100:
    response = 'This is not possible, an error has occurred.';
    break;

  case score >= 0 && score <= 19: 
    response = 'That was a terrible score — total fail!';
    break;

  case score >= 20 && score < 39:
    response = 'You did a passable job, not bad!';
    break;

  case score >= 40 && score < 69:
    response = 'You did a passable job, not bad!';
    break;

  case score >= 70 && score < 89:
    response = "That's a great score, you really know your stuff.";
    break;

  case score >= 90 && score < 100:
    response = 'What an amazing score! Did you cheat? Are you for real?';
    break;

  // include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';
}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

 

Link to comment
Share on other sites

Link to post
Share on other sites

20 hours ago, mikat said:

The formatting is off (not a problem atm but it's better to start right), you replaced the response assignments with console.log and the machine is off, your console.log's were not ending up in the paragraph but in the console, and because the machine was off only the first "an error has occurred*" message was being logged to the console.
 

SNIP

Hi thanks for answer,

as noted in my (second) previous comment even on machineActive=true  it shows Your Score is 75 and not the console log for 

  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

screenshot

Spoiler

image.png.54961ea7a1dcf86fa2b60fb952541c20.png

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, c0d0ps said:

Hi thanks for answer,

as noted in my (second) previous comment even on machineActive=true  it shows Your Score is 75 and not the console log for 

  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

screenshot

  Hide contents

-snip-

 

Console log will log the text to the *console*. What you want to do is set the value of the paragraph element, for which variables have already been defined near the end of the code. All you need to do is set the value of the variable "response" to the text.

console.log("That's a great score, you really know your stuff.";);
// to
response = "That's a great score, you really know your stuff.";

 

 

 

2 hours ago, c0d0ps said:
  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
  break;

break should also have the same indentation as the rest of the block in the case.

Corrected:

2 hours ago, c0d0ps said:
  case score >= 70 && score < 89:
      console.log("That's a great score, you really know your stuff.");
      break;

 

 

After all the changes, your code should look like this:

let response;
let score = 75;
let machineActive = true;

  switch (machineActive) {
  case score <= 0 || score >= 100:
      response = "This is not possible, an error has occurred.";
      break;

  case score >= 0 && score <= 19: 
      response = 'That was a terrible score — total fail!';
      break;

  case score >= 20 && score < 39:
      response = 'You did a passable job, not bad!';
      break;

  case score >= 40 && score < 69:
      response = 'You did a passable job, not bad!';
      break;

  case score >= 70 && score < 89:
     response = "That's a great score, you really know your stuff.";
      break;

  case score >= 90 && score < 100:
      response = 'What an amazing score! Did you cheat? Are you for real?';
      break;

// include as many cases as you like

  default:
    response = 'The machine is turned off. Turn it on to process your score.';}

// Don't edit the code below here!

section.innerHTML = ' ';
let para1 = document.createElement('p');
let para2 = document.createElement('p');

para1.textContent = `Your score is ${ score }.`;
para2.textContent = response;

section.appendChild(para1);
section.appendChild(para2);

 

Spoiler

image.png.a6f9386c8d2c066c53d7480c5a20ae0b.png

 

1 hour ago, LAwLz said:

I am getting pretty fucking sick and tired of the "watch something else" responses. It's such a cop out answer because you could say that about basically anything, and it doesn't address the actual complaints. People use it as some kind of card they pull when they can't actually respond to the criticism raised but they still feel like they need to defend some company/person. If you don't like this thread then stop reading it. See how stupid it is? It's basically like telling someone "shut the fuck up". It's not a clever responsive, it doesn't address anything said, and it is rude. 

 

 

bruh switch to dark mode its at the bottom of this page

VPN Server Guide

Link to comment
Share on other sites

Link to post
Share on other sites

I'm pretty sure that this is a (horrific, IMO) abuse of a switch statement. I'm not 100% sure, but I think this is how this is evaluating:

var temp = true;
var num = 2;

switch(temp) {
    case num == 1: return "one";
    case num == 2: return "two";
    case num == 3: return "three";
    default: return "wat?";
}

becomes

switch(true) {
    case false: return "one";
    case true: return "two"; // returns "two"
    case false: return "three";
    default: return "wat?";
}

which means if you're not careful about your logic, setting temp to false will return the first "wrong" answer in the switch, not the default value.

 

I feel like two layers of nested ifs would be easier to read and debug:

var temp = false;
var num = 2;

if (temp) {
    if (num == 1) { return "one"; }
    else if (num == 2) { return "two"; } // returns "two", easier to follow how we got here conditionally.
    else if (num == 3) { return "three"; }
    else { return "wat?"; }
}

 

Main System (Byarlant): Ryzen 7 5800X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 16GB G.Skill DDR4 3200MT/s CAS-14 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 960 PRO 512GB / 4× Crucial MX500 2TB (RAID-0) | Corsair RM750X | Mellanox ConnectX-3 10G NIC | Inateck USB 3.0 Card | Hyte Y60 Case | Dell U3415W Monitor | Keychron K4 Brown (white backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB RAM (soldered) | Vega 6 Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi (all-around awesome machine)

 

Proxmox Server (Veda): Ryzen 7 3800XT | AsRock Rack X470D4U | Corsair H80i v2 | 64GB Micron DDR4 ECC 3200MT/s | 4x 10TB WD Whites / 4x 14TB Seagate Exos / 2× Samsung PM963a 960GB SSD | Seasonic Prime Fanless 500W | Intel X540-T2 10G NIC | LSI 9207-8i HBA | Fractal Design Node 804 Case (side panels swapped to show off drives) | VMs: TrueNAS Scale; Ubuntu Server (PiHole/PiVPN/NGINX?); Windows 10 Pro; Ubuntu Server (Apache/MySQL)


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s CAS-22 | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / Seagate 1.5TB HDD | Corsair CX450M | Viewcast Osprey 260e Video Capture | Mellanox ConnectX-2 10G NIC | LG UH12NS30 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Camera: Sony ɑ7II w/ Meike Grip | Sony SEL24240 | Samyang 35mm ƒ/2.8 | Sony SEL50F18F | Sony SEL2870 (kit lens) | PNY Elite Perfomance 512GB SDXC card

 

Network:

Spoiler
                           ┌─────────────── Office/Rack ────────────────────────────────────────────────────────────────────────────┐
Google Fiber Webpass ────── UniFi Security Gateway ─── UniFi Switch 8-60W ─┬─ UniFi Switch Flex XG ═╦═ Veda (Proxmox Virtual Switch)
(500Mbps↑/500Mbps↓)                             UniFi CloudKey Gen2 (PoE) ─┴─ Veda (IPMI)           ╠═ Veda-NAS (HW Passthrough NIC)
╔═══════════════════════════════════════════════════════════════════════════════════════════════════╩═ Narrative (Asus USB 2.5G NIC)
║ ┌────── Closet ──────┐   ┌─────────────── Bedroom ──────────────────────────────────────────────────────┐
╚═ UniFi Switch Flex XG ═╤═ UniFi Switch Flex XG ═╦═ Byarlant
   (PoE)                 │                        ╠═ Narrative (Cable Matters USB-PD 2.5G Ethernet Dongle)
                         │                        ╚═ Jesta Cannon*
                         │ ┌─────────────── Media Center ──────────────────────────────────┐
Notes:                   └─ UniFi Switch 8 ─────────┬─ UniFi Access Point nanoHD (PoE)
═══ is Multi-Gigabit                                ├─ Sony Playstation 4 
─── is Gigabit                                      ├─ Pioneer VSX-S520
* = cable passed to Bedroom from Media Center       ├─ Sony XR65A80K (Google TV)
** = cable passed from Media Center to Bedroom      └─ Work Laptop** (Startech USB-PD Dock)

 

Retired/Other:

Spoiler

Laptop (Rozen-Zulu): Sony VAIO VPCF13WFX | Core i7-740QM | 8GB Patriot DDR3 | GT 425M | Samsung 850EVO 250GB SSD | Blu-ray Drive | Intel 7260 Wifi (lived a good life, retired with honor)

Testbed/Old Desktop (Kshatriya): Xeon X5470 @ 4.0GHz | ZALMAN CNPS9500 | Gigabyte EP45-UD3L | 8GB Nanya DDR2 400MHz | XFX HD6870 DD | OCZ Vertex 3 Max-IOPS 120GB | Corsair CX430M | HooToo USB 3.0 PCIe Card | Osprey 230 Video Capture | NZXT H230 Case

TrueNAS Server (La Vie en Rose): Xeon E3-1241v3 | Supermicro X10SLL-F | Corsair H60 | 32GB Micron DDR3L ECC 1600MHz | 1x Kingston 16GB SSD / Crucial MX500 500GB

Link to comment
Share on other sites

Link to post
Share on other sites

21 hours ago, RockSolid1106 said:

Console log will log the text to the *console*. What you want to do is set the value of the paragraph element, for which variables have already been defined near the end of the code. All you need to do is set the value of the variable "response" to the text.

 

 

 

break should also have the same indentation as the rest of the block in the case.

Corrected:

 

 

After all the changes, your code should look like this:

 

Thank you that worked great, except for machineActive = false

I get this error code, = true still works like it should though and I don't know why

Spoiler

image.png.6ed7fbaf16b1559331de5d6a34681660.png

Summarizing:
For this specific exercise it is better to define response because of the pre stated paragraph.

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

21 hours ago, AbydosOne said:

I'm pretty sure that this is a (horrific, IMO) abuse of a switch statement. I'm not 100% sure, but I think this is how this is evaluating:

becomes

which means if you're not careful about your logic, setting temp to false will return the first "wrong" answer in the switch, not the default value.

 

I feel like two layers of nested ifs would be easier to read and debug:

 

The exercise was to use a switch statement not if else statements but yes I am more comfortable with if else statements from my high school days.

I am still new to the whole switch thing.

This exercise is part of the mozilla course of javascript called conditionals 3

 

I think you missed the part where I added break; but yes it was needed. 

The code wasn't read properly by the computer without it.

I will try to remember that.

 

I appreciate pedantics as much as anyone (even if I don't know much about programming) but I think you're exaggerating about the whole abusing.

Coding in bliss is not abuse it is me taking the stairs and falling down and hurting my ankles.

Not worse than that. 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×