JavaScript null Check in Go
Sometimes we need to check if an value/object/variable in JavaScript is null. For example, querySelector for elements will return null if nothing found, or event state in the callback of history API is null in some cases. In this post we will show you how to do null check in Go/GopherJS.
Table of Content
Test if Variable is null
querySelector method will return first element which matches the selector, or return null if nothing found. Here we have an empty HTML document without any meaningful elements. We will query for an non-existing element with id=foo via querySelector method. The query will return null and we will check for it.
JavaScript
var f = document.querySelector("#foo");
if (f === null) {
console.log("querySelector #foo returns null");
} else {
console.log("querySelector #foo returns element");
}
Open your console and you will see querySelector #foo returns null.
GopherJS
The above code in Go/GopherJS is as follows:
import (
"github.com/gopherjs/gopherjs/js"
)
f := js.Global.Get("document").Call("querySelector", "#foo")
if f == nil {
println("querySelector #foo returns null")
} else {
println("querySelector #foo returns element")
}
Run Code on GopherJS Playground
The full code example of this post is on my GitHub.
For real-world example, see [2].
References:
[1] | [GopherJS] null Test |
[2] | [GopherJS] HTML Web History API Example |
[3] | [Golang] undefined Test in GopherJS |
[4] | [Golang] Test if Item Exist in Web Storage by GopherJS |
[5] | [GopherJS] Setting Implementation via JSON and Web Storage (localStorage) |