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:
1 2 3 4 5 6 7 8 | const obj = {}; console.log(obj.name); // undefined function example() {} console.log(example()); // undefined console.log(void(0)); // undefined |
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:
1 2 3 4 5 | const undefined = 10; // SyntaxError let undefined = 10; // SyntaxError var undefined = 10; console.log(undefined); // undefined |
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.
1 2 3 4 5 6 7 | function myFunction() { const undefined = 10; console.log(undefined); } myFunction(); // 10; |
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
1 2 3 4 5 6 7 8 9 10 | if (true) { var undefined = 10; console.log(undefined); // undefined } if (true) { let undefined = 10; console.log(undefined); // 10 } |
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.