If conditional works without using {}

Hello! I have a question related to the using of {} when using a setter, as I showed below:

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  _numOfSensors: 15,
  get numOfSensors(){
    if(typeof this._numOfSensors === 'number'){
      return this._numOfSensors;
    } else {
      return 'Sensors are currently down.'
    }
  },
  set numOfSensors (num){
    if(typeof this._numOfSensors === 'number' && num >= 0){
      this._numOfSensors = num;
    }
    else {
      return 'Pass in a number that is greater than or equal to 0'
    }
  }
};
robot.numOfSensors = 100;
console.log(robot.numOfSensors);

The exercise above works fine, but even if I don’t place the { after the if it also works.
Why???

Thx!

This is due to the way if statements work in Javascript. If statements will always work on exactly the next statement. {} are used as a block statement, in other words you are treating everything within the {} as a single code statement.
When an if statement runs in the code, it checks the conditions and if true, runs the next statement in the code. If this is more than one code statement, then the {} are required to make this function as “one statement” so to speak. However if you only need one code statement to run then {} is not required, as it will run the next statement regardless. The same is true of else statements.

Generally I prefer to always use {} as it keeps things grouped nicely and legible, but if you prefer without it then there’s no harm in you using it as a single statement, in this case either:

if(typeof this._numOfSensors === 'number' && num >= 0) 
   this._numOfSensors = num;
else 
   console.log('Pass in a number that is greater than or equal to 0')
if(typeof this._numOfSensors === 'number' && num >= 0) this._numOfSensors = num;
else console.log('Pass in a number that is greater than or equal to 0')

or the one you have in your snippet. It’s really your choice, I would always go with the one that’s most readable for me, but that comes down to preference really.

TL;DR, Running an if statement without {} is perfectly fine for 1 code statement, but {} is required for more than 1.

1 Like

Great! I thought that too but I wanted to be sure!

Thx!