3

How to access same variable name inside function in javascript

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    var xyz = "World!";
    console.log("inside function: " + xyz) // output should be "Hello world!"
} abc();
1
  • How about only using console.log("inside function: " + xyz + " World!") inside the function without assigning any value to xyz. Commented Apr 4, 2016 at 6:10

4 Answers 4

3

Try :

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    var xyz = (window.xyz || "") +" " + "World!";
    console.log("inside function: " + xyz) // output should be "Hello world!"
} abc();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!! :) Anupam, such a quick reply. Got it
2

if you do not want to edit the value of xyz:

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    var abc = " World!";
    console.log("inside function: " + xyz + abc) // output should be "Hello world!"
} abc();

if you want to edit the value of xyz:

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc() {
    xyz += " World!";
    console.log("inside function: " + xyz) // output should be "Hello world!"
} abc();

1 Comment

Thank You!! Christopher. :)
2

Try with window. This will allow you to access globally declared variable.

var xyz = window.xyz ..

Comments

1

Why not just pass it as a parameter? There is absolutely no need to use a global variable.

var xyz = "Hello";
console.log("outside function: " + xyz)
function abc(xyz) {
    var xyzUpdated = xyz + "World!";
    console.log("inside function: " + xyzUpdated) // output should be "Hello world!"
} abc(xyz);

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.