lvarayut
lvarayut

Reputation: 15349

Jshint - Variable is already defined and missing semicolon of a javascript object

I defined a reason variable as javascript object inside a function, and then, use this object to define properties as following:

$scope.upsertReason = function() {
    var reason = {},
        reason.reasons = [],
        reason.scholarships = [];
}

I don't know why I always got the following error:

412 |            reason.reasons = [],
                       ^ 'reason' is already defined.
412 |            reason.reasons = [],
                       ^ Missing semicolon.
412 |            reason.reasons = [],
                       ^ Expected an identifier and instead saw '.'.
412 |            reason.reasons = [],
                       ^ Expected an assignment or function call and instead saw an expression.
412 |            reason.reasons = [],
                        ^ Missing semicolon.
413 |            reason.scholarships = [];
                                        ^ Expected an assignment or function

I have verified that I didn't define the reason variable anywhere else in the code. Any help would be appreciated.

Upvotes: 3

Views: 482

Answers (2)

aharris88
aharris88

Reputation: 3630

Like thefourtheye said, you can either do this:

var reason = {
    reasons: [],
    scholarships = []
};

Or if you want to do it all separately, you can do:

var reason = {};
reason.reasons = [];
reason.scholarships = [];

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239653

You cannot declare a property of an object with var statement, because var statement expects the variable names not to contain invalid characters. And . is definitely an invalid character for an identifier name. So, you cannot declare a new variable called reason.reasons or reason.scholarships.

You should declare reason like this

var reason = {
    reasons: [],
    scholarships = []
};

Upvotes: 6

Related Questions