14

How can I use a variable of one in another in javascript?

4 Answers 4

17

If the two script tags are on the same page, any variable declared outside of the scope of a function is global to the page.

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

Comments

10

Make it global;

script1.js

 var foobar = "O HAI";

script2.js

  alert(foobar);

1 Comment

I assume all the downvotes here are because we didn't say "Don't use global variables"? Or some other reason?
6

If the two script tags are on the same page, any variable declared outside of the scope of a function is global to the page. However, it does matter which script is loaded first for some applications.

Comments

0

When you declared a variable inside a <script> , you can access it anywhere simply by using this:

var myValue= window.yourProperty;

1 Comment

@andreas I edited answer. It was too summery, thanks for notice.

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.