Ayuda! codigo de golf

Cuéntanos qué está pasando:
Describe tu problema en detalle aquí.
Hola, tengo una cosnulta sobre el ejercicio de Codigo de Golf, entiendo la logica del Else If pero no entoy entendiendo a que se refiere en por ejemplos, la segunda indiacion <= -2. Alguien puede explicarme por favor :slight_smile:

   **Tu código hasta el momento**


const names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];

function golfScore(par, strokes) {
 // Only change code below this line
if(strokes === 1) {
 return names[0] ;
}else if (strokes <= par - 2) {
 return names[1];
}else if(strokes == par -1) {
 return names[2];
}else if (strokes === par) {
 return names[3];
}else if (strokes == par +1) {
 return names[4];
}else if (strokes == par +2) {
 return names[5];
}else if( strokes >= par + 3 ) {
 return names[6];
}else {
 return "Change Me";
 // Only change code above this line
}
}
golfScore(5, 4);
   **Información de tu navegador:**

El agente de usuario es: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

Desafío: Código de golf

Enlaza al desafío:

There is nothing magical about “else if” - it is just an “else” followed by an “if”.

Imagine you are trying to decide what to have for dinner.

if they have pizza
    get pizza

but what if they don’t have pizza?

if they have pizza
    get pizza
else
    get a sandwich

But what if they don’t have a sandwich either? Then we want to chain another “if” off of it.

 if they have pizza
    get pizza
 else (
    if they have a sandwich
        get a sandwich
    else
        ask the waiter to choose
)

Do you see how the second “if” is chained off of, subordinate, based on that first “else”? We can condense that to:

if they have pizza
    get pizza
else if they have a sandwich
    get a sandwich
else
    ask the waiter to choose

You could cheap chaining those on as long as you want.

Does that make sense?

1 Like

Another way to look at it is that an “if → else if → else” chain creates a test where it stops after the first one is true. There are other ways to accomplish this, but it is a common pattern.

Hola @casita41

Recuerda que en este desafío “strokes” son el número de golpes que hay antes de hacer un hoyo y “par” es un número promedio de golpes en cada hoy.

Resumiendo, ambas variables son numéricas. Sabiendo esto, hagamos un caso hipotético en el que tengamos estos parámetros: (4,1). El primero es para “par” y el segundo para “strokes”. Ahora vayamos con tu duda:

if( strokes <= par -2)

Transformando a los valores pasados quedaría algo así:

if( 1 <= 4 -2)

Aún no se puede realizar la verificación porque se debe ejecutar primero la resta:

if( 1 <= 2)

Esto sería la condición final a evaluar. Recuerda que siempre se ejecutan primero las operaciones y después se verifican las condiciones.

Hola Kevinsmith Muchas Gracias por tu explicación me resultó muy útil, mi duda se enfocaba más, en porqué el ejercicio plantea una cuenta a resolver, en el caso del 4 -2 o la expresión para - 1.
Tengo un refuerzo de la lógica del If ELSE :blush:

Cool. Was your question answered or do you need more help on this?

Hola @EusojB20 Creo que mi confusión estaba más en las operaciones, me olvidé que primero se resuelven y después de avalúan, y tampoco le encontraba sentido en si porque se plantea una operacion. Muchas gracias por la ayuda genial :blush:

1 Like

Creo que no es necesario otra explicacion, muchas gracias.

1 Like

Have a look at what @EusojB20 wrote.

I’ll give it a try, if I understand your question.

For something like this:

}else if (strokes <= par - 2) {

it is asking, “is the number stored in strokes less than or equal to the value in par minus 2?” It will do the math for par - 2 first (because of order of operations), and then make a comparison.

To put that in terms of JS, let’s five some values.

var strokes = 3;
var par = 4;

strokes <= par - 2 // false

Why is it false? JS substitutes in those variable values, so it is equivalent to this:

3 <= 4 - 2

this reduces to:

3 <= 2

that is false.

Let’s consider another possibility:

var strokes = 2;
var par = 4;

strokes <= par - 2 // true

JS substitutes in those variable values, so it is equivalent to this:

2 <= 4 - 2

this reduces to:

2 <= 2

that is true.

Does that help?

1 Like

Hola, si eso aclara todo, ya no tengo dudas con este ejercicio Muchas Gracias por explicarme :slight_smile:

2 Likes