Shorthand if statement for property initialization in Javascript

241 Views Asked by At

To make my code cleaner I do the following in a javascript file:

var _weight;

function getWeight(){
    _weight || InitializeWeight();

    // do some stuff

    return _weight;
}

function InitializeWeight(){
    _weight = 3;
}

JSHint throws an error on shorthand statements like these "_weight || InitializeWeight()":

Expected an assignment or function call and instead saw an expression.

So I check if it is undefined, call this method.

Is this realy wrong? It works perfectly.

How do I write this statement without having JSHint throw up on me?

1

There are 1 best solutions below

0
Nicolò On

You can use the expr option:

/*jshint expr: true */

var _weight;

function getWeight(){
    _weight || InitializeWeight();

    // do some stuff

    return _weight;
}

function InitializeWeight(){
    _weight = 3;
}