How can developers ensure cross-browser compatibility and handle differences in JavaScript support among various browsers?

To ensure cross-browser compatibility and handle differences in JavaScript support among various browsers, developers can use feature detection rather than browser detection. This involves checking if a specific feature is supported by the browser before using it in the code. This approach allows developers to write code that works across different browsers without relying on user-agent strings or browser-specific hacks.

<script>
    if (window.localStorage) {
        // Code that uses localStorage
    } else {
        // Fallback code for browsers that do not support localStorage
    }
</script>