user2166695
user2166695

Reputation: 101

Why isn't a number type initialized to 0?

I have the following code in a service class:

count: number;

increment() {
  this.count++;
  console.log(this.count);
}

The log outputs NaN.

I'm wondering why it wouldn't initialize count to 0 when I specify a type in the declaration. I've replaced it with count = 0, but I'm just curious as to what the logic is behind it.

Upvotes: 2

Views: 8334

Answers (3)

Daniel Turcich
Daniel Turcich

Reputation: 1834

This doesn't have to do with Angular. JavaScript itself does not ever initialize a value when you define a variable, JavaScript will just allocate that variable as a variable as either an any type.

You're actually writing in TypeScript which of course is a Typed superset of JavaScript and all the

count: number;

is doing is allocating the variable count and designating it as the type number. You the developer have to Initialize the variable yourself because in many cases you don't want the variable to be initialized.

So for example in Vue there is the@Prop() decorator which you use to give access to data from a Parent Component to a child.

Example:

@Prop(String)
public title?: string

So here there is no reason for us to assign this variable a value seeing as it will be passed down from the parent component and rewrite this value.

There are many more cases where you don't want to initialize a variable with a value, do keep in mind that this can lead to undefined values which if you don't handle can be an issue. However if you use something like TSLint in Visual Studio Code or any other extendable editor you'll see when you need to handle that.

public exampleFunction() {
  // if you try and use title here it may be undefined
  if (!this.title) {
    return
  }
  // after you check to make sure that title is not undefined you can be sure it's safe to use it
}

All in all, having the language not automatically initialize a variable increases the writeability of the language and reduces unnecessary operations.

Upvotes: 1

Aragorn
Aragorn

Reputation: 5289

If you are coming from Java, you would expect a boolean variable to have a default value of false.

Similarly, in JavaScript too, default value does exist and that is the primitive value of undefined. TypeScript just uses JavaScript data types and doesn't change the behavior.

So, any variable that is defined and is not assigned will get defaulted to undefined (and NOT null; unlike in Java)

Read on MDN: https://developer.mozilla.org/en-US/docs/Glossary/Undefined

Upvotes: 0

Srdjan
Srdjan

Reputation: 582

It's undefined now. That's how javascript works, until you define a variable it's undefined...

In your case, if you want to start count from 0, just set variable value to 0...

Example: count: number = 0;

Upvotes: -1

Related Questions