0

HTML file :

<HTML>

<HEAD>

  <Title>Testing</Title>
 </HEAD>
   <Body>
 <script src="Test.js" language="JavaScript" type="Text/JavaScript" >
      CreateVariables();
 document.write(glVarMsg3);

</script>

</Body>

</HTML>

.js file:

function CreateVariables()
glVarMsg3="Global variable";

Friends please inform me what is the issue in this script? why i can't be able to access variable from .js file?

3 Answers 3

2

Firstly, that's invalid syntax for declaring a function. You need braces:

function CreateVariables() {
    glVarMsg3="Global variable";
}

Secondly you can either set an src or script content, but not both. So you'd need:

<script src="Test.js"></script>
<script>
    CreateVariables();
    console.log(glVarMsg3);
</script>

A good place to start would be this MDN article on functions. Additionally, I hope this is just for learning/testing as the use of document.write and global variables in this way is discouraged.

Sign up to request clarification or add additional context in comments.

7 Comments

Still this is no calling the Variable :-(
That's because if you declare a variable inside a function it's a local variable.
@ravb79 No. Declared without a var, it's implicitly declared at global scope. Please see updated answer
Okay, but shouldn't you just always use var when declaring a variable, as in from a best practice standpoint?
@ravb79 Depends on the requirements, but generally yes - as highlighted in the last sentence in my answer.
|
1

Just define your variables in global.js outside a function scope:

// global.js

var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file

function testGlobal () {
    alert(global1);
}

Comments

0

first just import

<script src="Test.js">
</script>

after use

<script>
   CreateVariables();
   document.write(glVarMsg3);
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.