JavaScript Variable Change Value

In this tutorial we will learn How To Change Variable Value in JavaScript. We can use JavaScript function to change the variable value by reassigning it a new value. We can also do this outside of function.


HTML Code is given below, in this code we have a paragraph tag to display the new value of the variable.

<!DOCTYPE html>
<title>JavaScript Variable Change Value</title>
<p id="output"></p>    
<script src="script.js"></script>    

JavaScript Code

Take a look at the JavaScript code, in this code we have a variable with value = 100. This value is then changed to 200 inside a user defined function.

Function is then called to change the value. Value will not change without the function call because a JavaScript function is only executed on function call.

getElementById() method is used to select the paragraph tag and innerHTML property is used to display the changed value of variable.

var variable = 100;

function changeValue()
  variable = 200;
document.getElementById('output').innerHTML = variable;

Variable declared outside function is global variable.

Variable declared inside function is local variable.

We can also do this without function.

var variable = 100;
variable = 200; //simple reassignment
document.getElementById('output').innerHTML = variable;


Video Tutorial

Watch video tutorial on How To Change Variable Value with JavaScript.

How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color JavaScript Change li Text JavaScript Remove id from Element Check If id Exists in JavaScript How To Delete Table Row by id in JavaScript Update Textarea value in JavaScript Change Variable Value in JavaScript Uncheck Radio Button Dynamically JavaScript Check Radio Button Dynamically JavaScript JavaScript Check if Radio Button is Checked or Not Change h1 Tag Text with JavaScript