Can you please tell me how to create a variable in JavaScript using a condition if it has not been previously declared?
For example:
if(!a){ a = 'test'; } In this case, the error in the console Uncaught ReferenceError: a is not defined
Can you please tell me how to create a variable in JavaScript using a condition if it has not been previously declared?
For example:
if(!a){ a = 'test'; } In this case, the error in the console Uncaught ReferenceError: a is not defined
console.log(this.a); if(!('a' in this)) { this.a = 'test'; } console.log(this.a); if it has not been previously announced
And if declared, but not assigned?
Write like this: if(a==undefined){ var a = 'test'; } if(a==undefined){ var a = 'test'; }
I incorrectly wrote in the comment and deleted that comment. The point is that before executing the code, the interpreter runs through the code previously in order to form an object-context for executing the code, to fill it. in this case, this context object is called Global , because the code is global. Regarding variables, first the variables declared through var are assigned the value undefined , and then during the processing of the code these values change to what the code stands for ( "test" ). If you look at your code
if(!a){ a = 'test'; }
, the interpreter did not see the var to the left of a = 'test' ; and the Global variable object ( VO ) with the variable a inside it was not entered into the context object Global . All variables are pre-entered into the variable object ( VO - variable object ) as undefined , if the interpreter "saw" before them var .
Here is a good article about the object-context of the code execution http://corporate.tuenti.com/en/dev/blog/functions-and-execution-contexts-in-javascript
I give you a plus, so that the minus block it)))
a==undefined will be an Uncaught ReferenceError exception : a is not defined when a is not declared, And using var inside if is meaningless, it is simpler to declare a variable before use. - Grundyvar a; then assigned - GrundySource: https://ru.stackoverflow.com/questions/565013/
All Articles
if (typeof a == 'undefined')- Alexey Shimansky