Faster, better AI-powered code reviews. Start your free trial!  
Faster, better AI-powered code reviews.
Start your free trial!

Get high quality AI code reviews

Javascript Global Function: A Comprehensive Guide

Table of Contents

JavaScript provides a set of useful global functions that can be called from anywhere in your code. These functions allow you to perform common tasks like encoding/decoding URLs, converting values, evaluating code, and more without needing to reference any specific object. In this comprehensive guide, we’ll take an in-depth look at what makes a function global in JavaScript and explore some of the most useful global functions provided.

What Makes a Function Global in JavaScript

For a function to be considered global in JavaScript, it must be defined in the global scope rather than inside another function or object. There are two main ways to define global functions:

Defined in the Global Scope

Functions defined in the global scope are not attached to any object and can be called from anywhere in your code. For example:

// Global scope
function myFunction() {
  // Function code
} 

// Call from anywhere
myFunction(); 

Since they are not bound to any object, these functions are essentially utility functions that can be easily reused.

Added to the Window Object

The window object is globally available in browser-based JavaScript environments. By adding functions as properties of window, you can effectively make them global:

// Add function to window object
window.myFunction = function() {
  // Function code 
};

// Function now global 
myFunction();

This approach allows you to organize your global functions under the window namespace rather than pollute the global scope.

Core Global Functions in JavaScript

JavaScript provides a core set of useful global functions for evaluation, URI encoding/decoding, and other common tasks:

Evaluation Functions

  • eval() – Evaluates a string as JavaScript code and executes it. This can be useful for dynamically executing code but also represents a security risk.
  • isFinite() – Determines if a value is a finite number. Safer than comparing to Infinity.
  • isNaN() – Checks if a value equates to NaN (Not-a-Number). Often used to validate numbers.
  • parseFloat() – Parses a string and returns a floating point number.
  • parseInt() – Parses a string and returns an integer.
// Evaluate code
eval("const a = 2; console.log(a);");

// Validate numbers
isFinite(123); // true
isNaN(123); // false 

// Parse strings  
parseFloat("12.34"); // 12.34
parseInt("12"); // 12

URI Encoding/Decoding Functions

  • decodeURI() – Decodes a URI by replacing escape sequences.
  • decodeURIComponent() – Decodes a URI component.
  • encodeURI() – Encodes a URI by escaping special characters.
  • encodeURIComponent() – Encodes a URI component.
// Encoding 
encodeURI("http://example.com/path/to/file.html");
// "http://example.com/path/to/file.html"

encodeURIComponent("path/to/file.html");
// "path%2Fto%2Ffile.html" 

// Decoding
decodeURI("http://example.com/path/to/file.html"); 
// "http://example.com/path/to/file.html"

decodeURIComponent("path%2Fto%2Ffile.html");
// "path/to/file.html"

Other Helper Functions

  • escape() – Deprecated – Encodes a string.
  • unescape() – Deprecated – Decodes an encoded string.
escape("abc123"); 
// "abc123"

unescape("abc123");
// "abc123"

Uses of Global Functions in Web Development

JavaScript’s global functions have some important uses in web development:

Cross-Browser Support

These functions are built into the language itself and are supported consistently across all major browsers without any dependencies. This makes them a good fallback option when newer methods fail or are unavailable.

Quick Encoding/Decoding

The URI encoding/decoding functions provide a quick and simple way to encode or decode strings for use in URLs and query parameters without needing to load an external library.

Eval Alternative

While safer eval alternatives like setTimeout or new Function() exist, eval() remains a quick way to parse and execute simple JavaScript code strings.

Examples of Global Functions in Action

Here are some practical examples of how JavaScript’s global functions can be used:

Validating Form Input

Use isNan() and isFinite() to validate numeric inputs:

// Validate form input
const num = parseFloat(form.input.value);
if (isNaN(num) || !isFinite(num)) {
  alert("Please enter a valid number");
} 

Encoding/Decoding Query Strings

Use the encoding functions when working with query strings:

// Encode string for query 
const query = encodeURIComponent(document.query); 

// Append to URL
const url = `${location.href}?q=${query}`; 

// Decode query on server
const query = decodeURIComponent(req.query.q);

Parsing User-Provided Code

Use eval() to dynamically execute user-provided code:

// Execute simple expression 
const input = "1 + 2";
const result = eval(input); // 3

Conclusion

JavaScript’s global functions provide a toolbox of useful utilities accessible from anywhere in your code. While newer methods exist for some functionality, these functions remain important for backwards compatibility and simple tasks. By mastering functions like eval(), isNaN(), encodeURI(), and others, you can write code that is cross-browser compatible, securely parse input, quickly manipulate strings, evaluate code, and more. Understanding the global scope and when to leverage its capabilities is an important part of JavaScript mastery.

Nisha Kumari

Nisha Kumari

Nisha Kumari, a Founding Engineer at Bito, brings a comprehensive background in software engineering, specializing in Java/J2EE, PHP, HTML, CSS, JavaScript, and web development. Her career highlights include significant roles at Accenture, where she led end-to-end project deliveries and application maintenance, and at PubMatic, where she honed her skills in online advertising and optimization. Nisha's expertise spans across SAP HANA development, project management, and technical specification, making her a versatile and skilled contributor to the tech industry.

Written by developers for developers

This article was handcrafted with by the Bito team.

Latest posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Top posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Related Articles

Get Bito for IDE of your choice