Is JavaScript undefined really undefined?

Tram Ho

Greeting

Hi everyone, today I will bring you an article about undefined in javascript. Is it really the undefined one you already know or not? Let’s find out!

Main problem

As you know, undefined in javascript means that when using a variable that has not been defined or a void function does not return a value. For example:

What is confusing

So what if we defined a variable “undefined”? ? )) With current browsers, undefined is readonly ie we will not redefine it. For example:

As in the above example, we cannot redefine the variable undefined because it is readonly. So how to define it. Have a look at the following example.

Have you seen the magic here? ? At first we cannot define the scope as global, but with the local scope of a function, we can still redefine it. Try it with another example. Within scope is an if conditional structure

summary

As I mentioned above, in the local scope of a certain function, undefined can completely become a variable of value. That means that.

  • Make sure you don’t name the variable undefined anywhere.
  • If possible, use void instead of undefined to compare.
  • In the project, use linter: Eslint, Tslint, … to limit this.
  • In case it is imperative to use undefined to compare values, you can assign variable undefined to “undefined” to make sure undefined is “undefined”. ? ))))

Thank you for taking the time to read your article. I wish you have a good working day and study.

Share the news now

Source : Viblo