*Very New Learner* Else If as a variable to show result in HTML?

Hello, I only have a few hours of learning and playing with JS so I imagine there is some easier way to write my code and accomplish what I want. Nevertheless, I hope there is an easy fix to my code without having to have someone explain a whole other method.

Anyway, I am playing around with else and if statments and also displaying those results on HTML.

Its super cheesy but its like a player attribute generator that compares the 3 attributes and determines the result of the player; average, superstar, hall of famer, all time great…

If I console log the results and run the script I get the desired results. So it seems that my code is functioning. Here is the else if part of the code…

if (playerRating > 80 && longevity > 80 && awareness > 80) {outcome= ‘All Time Great’}

else if (playerRating > 80 && longevity > 80) {outcome= ‘Hall of Famer’}

else if (playerRating > 80) {outcome= ‘Superstar’}

else {outcome= ‘Average Player’}

However, when I try to display the results in HTML… the script code displays the attributes as I desired… but when it comes to displaying the “outcome” it only displays when the result is an average player…

Here is the HTML…

<!---
 <h1 id="rating"> 
       <script>
    let rating = playerRating;
    document.getElementById("rating").innerHTML = 'My player rating is '+rating;
  </script>
  </h1>
<h1 id="awareness">  
   <script>
    let awarness = awareness;
    document.getElementById("awareness").innerHTML = 'My awarness is '+awareness;
  </script>
  </h1>

  <h1 id="longevity">  
   <script>
    let longevity = long;
    document.getElementById("longevity").innerHTML = 'My longevity is '+longevity;
  </script>
  </h1>

  <h1 id="result">  
   <script>
    let result = outcome;
    document.getElementById("result").innerHTML = 'My career outcome is '+result;
  </script>
  </h1>

 </div>


Is there something I am missing?  A simple fix.... is there a way to assign a variable name to an else if else statment like I am using?   

Again I am super new... I know nothing about functions or anything...   but I am willing to listen...

Hi,

There are a few things that could be improved in the code. Most noticeably that <h1> elements should be unique to a page (this isn’t the cause of your error, though) and the positioning of the <script> blocks.

Ideally, you want to place all JavaScript in one <script> block, just before the closing </body> tag.

Also, use a <span> to stick the results in, as this will simplify the JavaScript and will mean that anyone with JS disabled, will still see something displayed in the <h2> tags.

Here’s how that might be done:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Player rating</title>
  </head>

  <body>
   <h2>My player rating is <span id="rating"></span></h2>
   <h2>My awarness is <span id="awareness"></span></h2>
   <h2>My player longevity is <span id="longevity"></span></h2>
   <h2>My career outcome is <span id="result"></span></h2>

    <script>
      const playerRating = 100;
      const longevity = 100;
      const awareness = 100;
      let outcome;

      if (playerRating > 80 && longevity > 80 && awareness > 80) {
        outcome = 'All Time Great';
      } else if (playerRating > 80 && longevity > 80) {
        outcome = 'Hall of Famer';
      } else if (playerRating > 80) {
        outcome = 'Superstar';
      } else {
        outcome = 'Average Player';
      }

      document.getElementById('rating').innerHTML = playerRating;
      document.getElementById('awareness').innerHTML = awareness;
      document.getElementById('longevity').innerHTML = longevity;
      document.getElementById('result').innerHTML = outcome;
    </script>
  </body>
</html>

Does that do what you want?

Happy to discuss if you have any questions.

2 Likes

First, thank you so much for your response! I read it last night before going to bed and it gave me a lot to think about. Your code is so much more clean.

In the end, with your help, I got the results I was looking for. You invited me to ask some questions so I am going to take advantage of the oppurtunity. Agian, I am very new so I don’t want to overwhelm you with questions but let me ask a few.

In your example, you set a few of the viarables to constant but I didn’t mention that I had those variables set as random numbers. For example:

let awareness = Math.floor(Math.random() * 101);

My first question is, could/should I make the variable a const? Even though it generates a random number each time… the formula is constant…therefore, am I correct to assume that setting it to const is ok?

Second, I have been playing with HTML and CSS for a long time but only started to really learn it a few weeks ago. You stated that h1 elements should be unique to the page… I assume this is best practice and good for keeping the code clean and readable. I suppose I don’t really have a question about this; I just wanted to say thank you for the hint. Your comment made me research a little and it seems I need to better learn about block level and inline level elements and when and where to use them.

Additoinally, are you familiar with codecademy’s workspace setup? I believe it is referred to as a live editor; i.e. I can run the html, css, js and then see the results. What is a similar site that you would recommend for practicing in? Bonus points if the site host the page so that I can share it…

Last question. When I was implementing your code I realized that the main source of my problem was caused by the fact that I was doubling up on the script. I had the script inside the html but additionally I had a script pointing to the js file i.e. <script src='script.js'></script> also contianing the code.

Everything was great after erasing the script from the js file and making the changes you suggested. However, when I tried placing all the script inside the js file and removing it from the html… the end result was blank.

Anwyay, I am rambling… I guess i need to learn more about what js code has to go in the html and what code can be in the script file… or however that works. Again… I only have a few hours of playing around and I am like on the 3rd lesson in codecademy.

Again, thank you so much…

1 Like

Hi,

Glad to hear you got it working :slight_smile:

JavaScript doesn’t really have the concept of true constants. You have the following possibilities to declare a variable:

  • var - this is the ES5 way (if you don’t know what ES5 / ES6 is, you should look this up)
  • let is (normally) used if you are reassigning the variable — i.e. declaring it with one value (or no value), then assigning it a different value elsewhere in the program. As JavaScript has block scope, in my example we initialize the outcome variable outside of the if...else block, so that it is visible within it.
  • const is used if the variable is not reassigned. Most people talk about “constant variables” not constants.
  • if you don’t use any of the above you have an implicit global variable that can be changed from anywhere in the program. This is not normally what you want.

Whether the value you assign to awareness is a random number or not makes no difference. The real question is do you assign a different value to this variable elsewhere in your program?

// This is fine
const awareness = Math.floor(Math.random() * 101);

But:

// Uncaught TypeError: invalid assignment to const
const awareness = Math.floor(Math.random() * 101);
awareness = 100;

In which case you would do:

// Also fine
let awareness = Math.floor(Math.random() * 101);
awareness = 100;

I’m not familiar with Codecademy’s workspace setup, however, there are a number of similar sites around. The one I use when I need to throw together a quick demo is CodePen. JSFiddle is ok, too. If you need a full-blown editor in your browser (where you can install npm packages, run server-side code, work in different files etc) you can use CodeSandbox.

It is important that you reference the external JavaScript file in the correct position. Here’s how to move the JS from my previous example into a separate file:

index.js

const playerRating = 100;
const longevity = 100;
const awareness = 100;
let outcome;

if (playerRating > 80 && longevity > 80 && awareness > 80) {
  outcome = 'All Time Great';
} else if (playerRating > 80 && longevity > 80) {
  outcome = 'Hall of Famer';
} else if (playerRating > 80) {
  outcome = 'Superstar';
} else {
  outcome = 'Average Player';
}

document.getElementById('rating').innerHTML = playerRating;
document.getElementById('awareness').innerHTML = awareness;
document.getElementById('longevity').innerHTML = longevity;
document.getElementById('result').innerHTML = outcome;

Now, we can reference it like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Player rating</title>
  </head>

  <body>
    <h2>My player rating is <span id="rating"></span></h2>
    <h2>My awarness is <span id="awareness"></span></h2>
    <h2>My player longevity is <span id="longevity"></span></h2>
    <h2>My career outcome is <span id="result"></span></h2>

    <script src="index.js"></script>
  </body>
</html>

This should work as before.

The best place to put any JavaScript is at the bottom of the page, just before the closing </body> tag, however you’ll sometimes see tutorials that tell you to put it in the <head> section of the document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Player rating</title>
    <script src="index.js"></script>
  </head>

  <body>...</body>
</html>

This won’t work in our case, as when the JavaScript is parsed, it will try to reference elements that are not yet present on the page. If you want to keep it in the head, you’ll need to tell the JavaScript to only execute when the DOM is ready:

document.addEventListener('DOMContentLoaded', function () {
  const playerRating = 100;
  ...
  document.getElementById('result').innerHTML = outcome;
}, false);

Now this will work as before.

As a final tip, if you are not sure why your JavaScript is not running, you can always check the console in your browser’s developer tools to see any error messages (usually accessed by pressing the F12 key).

You might like to give this a quick read:

2 Likes

HTML actually has an hierarchy of elements on the page. H1 is for main title of the page near the top, if it has one. In your case, it would be the name of the form or test. If you have two tests with their own names, they would use H2 for their names.
The body copy would fall within p tags: < p>body copy here< /p>.

More complex hierarchies exist. Here’s a page that covers the semantic use of the headings: https://www.semrush.com/blog/semantic-html5-guide/

1 Like

I would additionaly note that you allowed to change the content of const variable (while you don’t reassign it completely), so things like this will work:

const list = ['foo']
list.push('bar')

const dict = { foo: 1 }
dict.bar = 2
1 Like

Re using let or const, there is a difference.
For example:

const $id = id =>  document.getElementById(id);

Saves a lot of typing eg.

let key =  $id('key_A');

but

let input = "A";
let key = $id('key_' + input);

That fails, generates an error.
So I needed to use let instead of const.
Took me a while to work that out.

@dennisjn Sorry I’m confused.

<body>
    <div id='key-01'></div>

<script>
    const getElemById = (selector) => document.getElementById(selector)

    const num = '01'
    const key = getElemById('key-' + num)

    console.log(key) // <div id="key-01"></div>
</script>
</body>

edit:

With regards let and const, personally my preference is to use const throughout. It safeguards against accidental re-assignment and also it’s about keeping code consistent — var, lets and consts throughout could be confusing.

If the label/variable does need to be re-assigned, for instance a counter, then that is where I would use let.

Silly example

let pi = 3.142

function dessert() {
  pi = 'apple pie' // accidental global assignment
  return pi
}

console.log(dessert()) // apple pie

// Thanks to calling 'dessert' pi is now 'apple pie' so this fails with NotANumber
console.log('Area of circle is ' + (pi * (10 ** 2))) // Area of circle is NaN

Try the same with const

const pi = 3.142

function dessert() {
  pi = 'apple pie' // accidental global assignment
  return pi
}

console.log(dessert()) // TypeError: Assignment to constant variable
1 Like

I am embarrassed, I can only assume I have been a victim of the browser not uploading the edited version of the file.
Fix the problem in the calling code but the edits aren’t run and then change the function expression and the edited code is used.
Had the same problem with async functions. When changed to let the function worked. I have now changed them to const and everything still works.
I should have verified that the const was causing the error.

Don’t be mate. I was wondering if there was a context to it that I was missing. We learn by our mistakes … hopefully :smiley:

I hear that! :wink:

1 Like