Search code examples
javascriptnode.jstilde

Why do the author use a tilde before file?


I'm learning node and express programming and find a very good example at: https://github.com/madhums/node-express-mongoose-demo

But I find a line and not fully understand.

// Bootstrap models
var models_path = __dirname + '/app/models';
fs.readdirSync(models_path).forEach(function (file) {
    if (~file.indexOf('.js')) require(models_path + '/' + file)
})

On the 4th line before file, there is a tilde( ~ )operator. I consult the javascript book, and it just says it's a bitwise NOT.

Why author use tilde here? If not using tilde, can I have other way to express the same thing?

Thank you!


Solution

  • Tilde is the bitwise not operator. The .indexOf() method returns the index of the found match in a string (or in an array) or -1 if the substring was not found.

    Because 0 == false tilde may be used to transform -1 in 0 and viceversa:

    > ~1
    -2
    > ~0
    -1
    > ~-1
    0
    

    ~file.indexOf('.js') is equivalent to file.indexOf('.js') === -1 or file.indexOf('.js') < 0. The last two examples are more clear to understand that the first one.