2

This is my code:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <p>
     <script>
        document.write(smsCount)  // i want to get "1" 
       </script>
    </p>
  </body>
</html>

My script.js:

function sameer()  {
    console.log('function working');
    var smsCount = 1;
  }

sameer(); 

How to access variable which is located in my function name sameer.

1
  • 3
    make it window.smsCount = 1; Commented Mar 8, 2018 at 9:20

2 Answers 2

2

Declare smsCount outside the function in a global scope to get it accessed using document.write:

var smsCount;
function sameer()  {
    console.log('function working');
    smsCount = 1;
  }

sameer(); 

document.write(smsCount);

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

Comments

1

How to access variable which is located in my function name sameer.

You can't since visibility of sameer is limited to inside the function in which its declaration is.

Either make it visible to window (topmost level)

window.smsCount = 1;

Or, don't associate any var, let or const with it, its scope will keep propagating to the parent level till it is declared or it will be added to global scope

smsCount = 1;

Or return the value

function sameer()  {
    console.log('function working');
    var smsCount = 1;
    return smsCount;
  }

var smsCount = sameer(); 

7 Comments

how to make work this in inside one html file that means two <script tags> instead of separated script.js file?
This should work for both scenarios two <script tags> or separated script.js file.
can you make any fiddle? please its not working for me!
Can you be more specific about the error you get and what you tried?
instead of using script.js if i put this in function code inside new script tag inside my html, its showing undefined!
|

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.