-2
app.get("/speak/:animal",function(req,res){

    var animal= String(req.params.animal);
    var animalSounds={
        pig: "Oink",
        cow: "Moo",
        dog: "Woof woof" 
    }
 var animalSound = animalSounds[animal]; //Working
 var animalSound = animalSounds.animal;  // Not working

 res.send(animalSound);
})

When I write object inside the third bracket that works fine, but when I defined after it didn't work. Why is it not working that way?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Because it is the wrong syntax? Read the langague specs and see waht the index (brackets) is for. – TomTom Mar 16 '20 at 07:58
  • Put your [mre] **as text**. But `animalSounds[animal]` is the same as `animalSounds.animal` only when `animal === "animal"`. – jonrsharpe Mar 16 '20 at 08:01
  • It's not clear why you thought dot notation *would* work here. See e.g. https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – jonrsharpe Mar 16 '20 at 08:07
  • In java Script , both dot notation and bracket system worked fine.So, i want to know why here not working it. – Abir Hasan Mar 16 '20 at 08:23
  • In your case, `animal` is a variable. You can use it in bracket notation because it is basically a string. However with the dot notation, the property must be a valid JavaScript identifier, which a string is not. In other words, `animalSounds["pig"]` works but not `animalSounds."pig"` Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors – 7hibault Mar 16 '20 at 08:27
  • # 7hibault , In 2nd line i converted it to string because before convert it also didn't work. But if i write var animalSound = animalSounds.pig/cow/dog; then it work fine. So, in this case, are pig / cow / dog not string? I am new at this. – Abir Hasan Mar 16 '20 at 08:41

1 Answers1

0

The [] syntax takes a string, so you can use it to access the pig, cow or dog properties based on animal's value. The . syntax does not use a string, it uses an identifier, and since there's not property called "animal", you'll get undefined.

Mureinik
  • 297,002
  • 52
  • 306
  • 350