2

Say I declare a global JavaScript variable at the top of a JavaScript file to equal 0

i.e.

var jVar=0; 

Then I call a function in the JavaScript to set that variable to 1 ie.

function setVarToOne(){
    jVar=1;
}

If I then reload the page what will the variable equal before the setVarToOne function is called ?

Will the jVar keep the value it was set to in the function or will it be re-initialised to 0?

What I need to understand is, what happens to JavaScript variables when the page is reloaded?

Thanks

Kraylog
  • 7,383
  • 1
  • 24
  • 35
ben
  • 135
  • 1
  • 1
  • 8

6 Answers6

2

When you reload the page, everything in JavaScript will be lost and the code will execute like when you load the page for the first time.

That means, your variable will be initialized to 0, and when the function is called, the variable will be set to 1.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
2

When you reload the page the jVar will be set to 0; because you are initializing it at very first level var jVar=0; As your function is not called during reload. If you make a call to setVarToOne() then and only then your global variable value will get change.

You are also having options to set the value at localStorage

localStorage.setItem(id, value);
Anand Vaidya
  • 609
  • 2
  • 16
  • 41
  • Thanks, this is the information I needed, how to store a variable though a page reload – ben Dec 04 '17 at 09:03
1
var jVar=0;
document.write(jVar+'<br>');

function setVarToOne(){
    jVar=1;
}

setVarToOne();
document.write(jVar);

result: 1°document.write: 0 2°document.write: 1

every time you load/reload the page, the variable 'jVar' will be set to 0 then to 1

jsfiddle

Leo
  • 674
  • 5
  • 18
0

Your variable will be set to 0.

When you reload the page the whole script start running again from the beginning - thus running var jVar=0 first.

If you need to save your data you can use local storage, session storage, cookies or persist it on a server.

Take a look at this question that talks about persisting variables between page loads.

Nimrod Shory
  • 2,475
  • 2
  • 19
  • 25
0

It will be 0.

Javascript can't persist state in between 2 page loads by default. You could try first saving and then reading data from some store. Either by API call or by saving it to localStorage, cookie or some other data storage.

Mario Nikolaus
  • 2,346
  • 1
  • 21
  • 28
0

Global variables are variables which will be stored throughout the Session. When you want to store something beyond the session use PHP. You need PHP for the global variable to be stored. Copy your code and put it in a php file. In this file write this,

<?php
session_start();
$_SESSION['JVar'] = 0;
function setVarToOne(){
    $_SESSION['jVar'] = 1;
}

the variable will be stored in session all you have to do is pass that value to js by

echo "<script>var JVar = $_SESSION['jVar']</script>";
?>
omkaartg
  • 2,676
  • 1
  • 10
  • 21