简体   繁体   中英

node.js using a function before it is defined

I want to ask a question about the order of code in a node.js file.

I have the following code from a Udemy lesson regarding user authentication using passport.js .

// CREATE - add new campgrounds to DB
router.post("/", isLoggedIn, function(req, res) {
    // get data from form and add to campgrounds array
    var name = req.body.name;
    var image = req.body.image;
    var desc = req.body.description;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var newCampground = {name: name, image: image, description: desc, author:author}
    // Create a new campground and save to database
    Campground.create(newCampground, function(err, newlyCreated) {
        if(err) {
            console.log(err);
        }
        else {
            console.log(newlyCreated)
            res.redirect("/campgrounds")
        }
    })
    // redirect as a GET request
})

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect("/login");
}

and I was a bit confused here. I defined the function isLoggedIn after the route above it and I used the middleware to determine whether the following code should be executed in the line

router.post("/", isLoggedIn, function(req, res) {

This is against the principles of other languages I have learnt, including HTML and Python where any code being used must be explicitly defined before its use, including spreadsheets and variables.

Why does the code still function even though the function isLoggedIn is declared after my router.post POST route?

Functions declarations are hoisted in JavaScript, so they're moved to the top of their scope, that's why you can use them without any problem.

You can read more about hoisting here: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

This is due to 'hoisting' in javascript.

"Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Inevitably, this means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local."

https://scotch.io/tutorials/understanding-hoisting-in-javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM