1

If I have a variable in the <script> tags of an HTML document; lets call it example.

How can I access example in my JavaScript file?

<!DOCTYPE html>
<head>
	<link rel="stylesheet" type="text/css" href="css/example.css">
	<link rel="icon" href="https://www.example.com/icon.png">
	<title>Exsample</title>
</head>
<body>
	<script>
		var example = "example"
	</script>
</body>

0

3 Answers 3

4

Scripts loaded with <script> elements (type=module aside) all share the same JS environment.

A variable created in the global scope by one will be available in all the others.

The only other proviso is that you can't access a variable before you create it.

<script>
    var example = 1;
</script>
<script>
    console.log(example);
</script>

There is no difference between scripts where the script is loaded via src and those with the script provided inline.

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

3 Comments

So I could write var jsexample = example? @Quentin
In the example above, imagine that the second script block is an external file and not loaded using type="module". You would just access the global variable from the external file that was created in the HTML page.
@T54 — You can do anything you like with example, including copying its value to a new variable like that.
1

You should be able to access it through window.example. If example is declared in a function, you won't be able to access it. Your external script must also appear after the variable declaration (or you can use the defer option on the script):

console.log(window.example);
<script>var example = 'example';</script>

4 Comments

There's no need to explicitly access the window object.
@Quentin There is, but only in "use strict" mode.
@JamieBirch — Not even in strict mode. That bans the implicit creation of globals. It doesn't ban the reading of globals nor does it ban the explicit creation of them with var (or let or const).
@Quentin You're right it can be left out. I just prefer leaving it in to make global access more explicit (as it can be confusing and should be avoided where possible).
1

Nowadays in 2023, using ES2022, you can access your JS variable in HTML document from an external JavaScript file as following :

//in your test.js file
const myVar = `John DOE`
export default {myVar}

then in your HTML file

<script type="module">
    import myVar from 'test.js';
    console.log(`myVar=` + myVar)
</script>

the console returns the following result:

▶ {myVar: 'John DOE'}

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.