Reputation: 2827
Following a nodejs course(NodeJS in Action - manning's book) I saw this piece of code
// create server
var server = http.createServer(function(request, response){
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
} else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3000, function(){
console.log('Server listening on port 3000.');
});
My question is about the variable "filePath". It is being initialized to false, but later it takes string values.
The editor I use (Visual Studio Code) shows me a warning:
Type 'string' is not assignable to type 'boolean'
My knowledge of javascript is not so deep, but I know it is loosely typed. So here is my question.
Is this initialization to false because of something? Any reaston to do so? Is my editor's warning wrong...? Or just the author's common practice.
Upvotes: 1
Views: 1232
Reputation: 707376
There is no reason for the initialization to false
and it is not even a good practice in this case.
This line:
var filePath = false;
can just be safely changed to this:
var filePath;
This can be done because the if/else in the following statement is guaranteed to initialize filePath
one way or the other.
And, I would agree, it's very odd to initialize it to a meaningless boolean value too that doesn't even have an appropriate meaning for the context. It's not even just being over cautious - it's just wrong. It appears that someone thought all declared values should be immediately initialized (which is not the case at all because in Javascript undefined
is a perfectly meaningful initial value in some contexts) so they just picked some value to assign to it.
Your editor is providing a warning that it's an unusual situation for you to abruptly switch types in a single variable. It isn't technically an error in Javascript (in other words, it's allowed), but it also could be an indicator of a coding mistake so that's all your editor is telling you.
Upvotes: 3