Thursday, October 9, 2025
HomeLanguagesJavascriptTensorflow.js tf.variable() Function

Tensorflow.js tf.variable() Function

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It helps developers to develop ML models in JavaScript, and use ML directly in the browser or in Node.js.

The tf.variable() function is used to create a new variable with the provided initial value.

Syntax:

tf.variable(initialValue, trainable, name, dtype)

Parameters:

  • initialValue: The initial value of the tensor from which the new variable will be initialized.
  • trainable: It is an optional parameter. It is of boolean type if true optimizers are allowed to update the variable and if false optimizers are not allowed to update it.
  • name: It is also an optional parameter. It is of string type. It is used for the name of the variable used as a unique ID.
  • dtype: It is also an optional parameter. If it is passed as the argument the intialValue will be changed to the specified dtype.

Return Value: This function returns tf.variable.

Example 1:

Javascript




// Creating and initializing a new variable
var val = tf.variable(tf.tensor2d(
    [8, 2, 5, 6],
    [2, 2]
));
 
// Printing the tensor
val.print()


Output:

Tensor
   [[8, 2],
    [5, 6]]

Example 2:

Javascript




// Creating and initializing a new variable
var val = tf.variable(tf.tensor([1, 2, 5, 6]));
 
// Printing the tensor
val.print()


Output:

Tensor
   [1, 2, 5, 6]

Example 3:

Javascript




// Creating and initializing a new variable
const x = tf.variable(tf.tensor([1, 2, 3]),
    true,"gfg",'complex64');
 
// Printing the tensor
x.print();


Output:

Tensor
   [1 + 0j, 2 + 0j, 3 + 0j]

Reference: https://js.tensorflow.org/api/latest/#variable

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32345 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6714 POSTS0 COMMENTS
Nicole Veronica
11877 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11940 POSTS0 COMMENTS
Shaida Kate Naidoo
6834 POSTS0 COMMENTS
Ted Musemwa
7094 POSTS0 COMMENTS
Thapelo Manthata
6789 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS