Is it safe to assume non-undefined state of component property if it gets its value synchronously in ngOnInit?

It's a very basic question, so I indeed have been trying to seek the answer to it in SO, but it's eluded me in some arcane way.

@Component({
  selector: 'my-comp',
  template: `{{bar.length}}`,
  styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
  bar: string;
  
  ngOnInit() {
    this.bar = 'foo';
  }
}

What I'm doing here is nothing more than a synchronous initialization of the variable bar inside the ngOnInit() method. The component's template assumes that the bar is not undefined and does not use an elvis operator ({{bar?.length}}).

I know it's all a bad practice to omit undefined-checking as long as we get a varable value through some asynchronous things (subscribe() and so on), but is it OK in this case?


Solution 1:

First of all, it's a good practice to initialize your properties (@Inputs or not). This way, you can guarantee that they will have values when the template is rendered, if a parent component does not pass anything at first.

The way your code is written right now wouldn't really cause an error in the template because you only change bar's value in onInit and nowhere else. However, down the line, your code might become more complex and bar might become "empty" (null or undefined) at some point. If you don't remember to put a guard in your template, it might throw an error during runtime. So it's a good practice to first make sure that a variable exists before you call any of its properties in the template.

In a nutshell: it's OK to leave it as it is right now, but it's safer if you put some guards in the template to avoid any future runtime errors.