Require in global scope or local scope?

What is the correct way to require a node module? Is it more accurate/understandable to declare the module in the global scope, or is it more accurate/understandable to declare the module in the local scope?

For example, which of these makes the most sense:

Global:

let dns = require('dns') // <-- Global scope declaration
function lookup(subdomain, domain){
    let fqdn
    if(subdomain == '@'){
        fqdn = domain
    } else {
        fqdn = `${subdomain}.${domain}`
    }
    dns.resolveTxt(fqdn, (err, records) => {
        if(records){
            console.log(records)
        } else {
            console.log("no recrods")
        }
    })
}

Local:

function lookup(subdomain, domain){
    let dns = require('dns') // <-- Local scope declaration
    let fqdn
    if(subdomain == '@'){
        fqdn = domain
    } else {
        fqdn = `${subdomain}.${domain}`
    }
    dns.resolveTxt(fqdn, (err, records) => {
        if(records){
            console.log(records)
        } else {
            console.log("no recrods")
        }
    })
}

Is it a matter of opinion? If so, my apologies and I will delete the question.

I am looking to improve my code so others can more easily understand it, and I think this question is relevant to that purpose, so it shouldn’t be considered an opinionated question.

79 thoughts on “Require in global scope or local scope?”

Leave a Comment