While reading in a JSF book, the author implements a map that serves as a namespace in which he defines some JavaScript functions.
The map is implemented like this:
if (!com) var com = {}
if (!com.example) {
com.example= {
myFunction: function(data) {
// some code here
}
}
}
I searched to understand that syntax but didn't succeed, could someone explain to me what does !com means ? how can we check a variable if it's not already declared?
if (!com) checks to see if com is a falsey value. if (com) checks to see if it's a truthy value so you can see that the ! reverses the test.
In your specific code example:
if (!com) var com = {};
the code is checking to see if the com variable is defined and initialized yet. If it has not been initialized, it's value will be undefined which is a falsey value which will cause this code to then initialize it.
In Javascript, there are many falsey values and undefined is one such falsey value. The falsey values are:
null
""
false
NaN
0
undefined
See this article for more info on falsey/truthy.
One thing you have to be careful of is that if (com) or if (!com) may cause a reference error in some situations. The safest way to test if a variable has been defined and initialized is this:
if (typeof com === "undefined")
because this will not cause an error in any circumstances.
Or, a common design pattern for namespaces is this:
var com = com || {};
This will define and initialize com as a namespace object if it doesn't already exist with a truthy value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With