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();
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();
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();
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);
console.log("inside function: " + xyz + " World!")inside the function without assigning any value toxyz.