Can somebody help with a simple JavaScript problem:

I’m trying to right a function that takes a wind speed in knots and converts it to Beaufort scale. (
Why doesn’t my code work?


I have edited this post’s title to refer to the correct language.

Quite right. Thanks.

This still isn’t working, perhaps I need to to use and IF ELSE instead.

Looks like the current code is also always setting beaufort to 12 at the end anyway.

add default before the default statement (beaufort = 12) so that it is an else, and make sure it is inside of the switch statement at the bottom.

I am still learning this language but just taking quick look, I would do if and else if nested statements. It might not be as efficient as other methods, but its what I would do with the limited knowledge that I have taken in. The code would look something like this

   var knots = 3;
var beaufort
$("#windSpeed").html(knots + " knots");
$("#beaufort").html(" 1test");

function getBeaufort(knots) {
if (knots < 1) {
} else if (knots > 1 < 4) {
} else if (knots > 4 < 20) {
} else if (knots > 3) {
} else {

Of course you would need more if and else if statements there to cover the broad range of numbers but its a basic approach that should work

1 Like

with such repetetive if and else, it’s more efficient to use a switch statement fyi

Not necessarily you are just testing for the wrong thing in your switch statement. Instead of checking for a range, you can check if an expression evaluates to true.


var knots = 3;

$("#windSpeed").html(knots + " knots");

function getBeaufort(knots) {
  var beaufort;
  switch(true) {
    case knots < 1:
      beaufort = 0;
    case knots < 4:
       beaufort = 3;

If the expression is true then the beaufort will be set to the case

1 Like

Awesome. Thanks for your help.

It’s so easy (when you know how!).

Result here:

Looks great! Love what you did with the UI

Thanks for the positive comments iRoachie. :slight_smile: