Is it safe?

Bigger projects mean more developers and more JavaScript. This added complexity makes it more likely that something, somewhere will go wrong. Even the best teams can write code with naming collisions. And even if you do remember to include all the required libraries, a temporary break in a network connection can leave a site without an important dependency. JavaScript can seem pretty intolerant to these sorts of issues, but with a little care, you can write code that anticipates and works around them.

Duplicating variable or function names is all too easy, especially when working with lots of other developers. But you can make this much less likely by wrapping your script in an immediately-invoked function expression (IIFE):

(function() {
    // code
})();

This creates a closure that limits the scope of the functions and variables inside. Therefore, the things you define can have the same name as other things used outside the IIFE without interfering with them.

An IIFE also makes it easy to manage external dependencies. Take a look at the following:

(function() {
    if (typeof jQuery === 'undefined') {
        return;
    }

    // code that requires jQuery
})();

The IIFE will return safely and without errors if jQuery doesn’t exist, perhaps because it failed to load. More importantly, other scripts outside the IIFE will continue to work. You can do this more than once in the IIFE or inside individual functions. And you can check for other things, such as jQuery plugins or the google object used by the Google Maps API:

(function() {
    if (typeof jQuery === 'undefined') {
        return;
    }

    // code that requires jQuery

    if (typeof jQuery.fn.pluginName === 'undefined') {
        return;
    }

    // code that requires a jQuery plugin
})();

Thinking about scope and broken dependencies means your script can exit cleanly when something goes wrong. Simply checking something is safe to use before trying to use it can save you a headache. It also means other scripts can keep running, leaving you with a more complete, functional site.