JavaScript undefined Check in Go


Sometimes we need to check if something exists or not in JavaScript. For example, old browsers may not support localStorage API, so we need to check before we use. In this post, we will show you how to do undefined check in Go/GopherJS.

Test if It's Undefined

Use localStorage as example, we will check if it is undefined in the browser.

JavaScript

if (window.localStorage === undefined) {
  console.log("Your browser does not support localStorage API");
} else {
  console.log("Your browser supports localStorage API");
}

Open your console and you will know if your browser support it or not.

GopherJS

GopherJS provides js.Undefined Object for undefined test. The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

if js.Global.Get("localStorage") == js.Undefined {
      println("Your browser does not support localStorage API")
} else {
      println("Your browser supports localStorage API")
}

Run Code on GopherJS Playground

The full code example of this post is on my GitHub.

For real-world example, see [3].


References:

[1][Golang] undefined Test in GopherJS
[2][Golang] Test if Item Exist in Web Storage by GopherJS
[3][GopherJS] Setting Implementation via JSON and Web Storage (localStorage)
[4][GopherJS] null Test
[5][GopherJS] HTML Web History API Example