Tensorflow.js tf.util.assert() Function
Tensorflow.js is an open-source library that is being developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The .util.assert() function is used to assert that the stated expression in the function as a parameter is true. And if it not true then an error is thrown along with the message stated in the method.
Syntax:
tf.util.assert(expr, msg)
Parameters: This function accepts the following two parameters.
- expr: It is the expression which is to be asserted and it is of type Boolean.
- msg(() => string): It is a function that returns the stated message when the expression is not true and an error is thrown. Here, a function is utilized for performance reasons.
Return Value: It returns void.
Example 1: When the stated expression is true.
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Defining a constant xconst y = 5; // Calling util.assert() method and// printing outputtf.util.assert(y === 5, (msg) => {}); console.log("Successfully Executed, No Error Occurred")console.log("Condition True") |
Output:
Successfully Executed, No Error Occurred Condition True
Example 2: When the stated expression is false and an error is thrown.
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Defining a constant x and// all the parametersconst y = 3.6;var exp = (y == 3.0)var msg = 'value of y is not 3.6'; // Calling util.assert() method and// printing outputvar z = tf.util.assert(exp, msg);console.log("true"); |
Output:
throw new Error(typeof msg === 'string' ? msg : msg()); Error: value of y is not 3.6
Reference: https://js.tensorflow.org/api/latest/#util.assert


