Home > Enterprise >  Why should we not explicitly assign undefined to a variable in javascript?
Why should we not explicitly assign undefined to a variable in javascript?

Time:01-03

I have heard it in some videos and blogs that we should not assign undefined to a variable in JavaScript explicitly in our code, instead we should use null. Why though?

CodePudding user response:

My conclusion is that undefined, lets us know that a variable has not been initialized yet, if we initialize it in our code and then make it undefined at a later stage, then it would lose its purpose hence we should use null, instead.

There can be a case, in which your logic dictates that if you get an undefined variable then the flow should be different than the case wherein you get null.

CodePudding user response:

Undefined indicates a very specific use case. It means that the value is not initialized, and you don't know what the value is. The problem is you would not want to get "undefined" as an output while working with your code unless it indicates a problem that is tied up to the lack of assignment. Null, NaN, and empty values all indicate the lack of a value rather than the lack of assignment, which is usually the desired behavior.

  • Related