*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

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.