ben
ben

Reputation: 175

Global variable at top of the JavaScript file

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

Upvotes: 2

Views: 478

Answers (6)

Anand Vaidya
Anand Vaidya

Reputation: 649

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);

Upvotes: 2

Nimrod Shory
Nimrod Shory

Reputation: 2505

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.

Upvotes: 0

omkaartg
omkaartg

Reputation: 2787

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>";
?>

Upvotes: 0

Leo
Leo

Reputation: 680

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

Upvotes: 1

Racil Hilan
Racil Hilan

Reputation: 25351

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.

Upvotes: 2

Mario Nikolaus
Mario Nikolaus

Reputation: 2406

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.

Upvotes: 0

Related Questions