Javascript return in function in object won't show alert box

381 views Asked by At

So basically i have this code which has a return in a function which should then display the returned variable "Price" but the alert box does not show. If i delete all code except alert it will. I can't find any misspelled words or pieces of code. Could you help me ?

<html>
<body>
    <script>
        var auto = {
            merk: 'BMW',
            model: 1,
            aantal deuren: 5,
            bouwjaar: 1990,
            prijs : 20000,

            price: function(){
            return this.prijs;
            }
        };
        var x = auto.price();
        alert(x);
    </script>
</body>

2

There are 2 answers

2
dfsq On

You have invalid property name in the object:

aantal deuren: 5,

If the property name is not valid identifier you need to wrap it in quotes:

var auto = {
    merk: 'BMW',
    model: 1,
    "aantal deuren": 5,
    bouwjaar: 1990,
    prijs: 20000,

    price: function () {
        return this.prijs;
    }
};
var x = auto.price();
alert("prijs");
0
ozil On

Use '' for 'aantal deuren': 5, or remove space from aantaldeuren: 5, object property