-1

So I coded this function expecting to create a variable, but it throw me an error

function createMyName(){
  var Myname = 'something';
  console.log(Myname); //something
}
console.log(Myname) //⚠ Myname is not defined
  • 1
    This is really a poor question. As many, I'm sure, will point out you can use window for your global variables, but I'd have to ask why you'd ever want to do that. It's a very good example of an [anti-pattern](https://medium.com/swlh/javascript-antipatterns-globals-and-variables-ec6229793b37). An more likely that question has already been asked on SO. – Erik Philips May 28 '21 at 03:06
  • 1
    Does this answer your question? [Define a global variable in a JavaScript function](https://stackoverflow.com/questions/5786851/define-a-global-variable-in-a-javascript-function) – Erik Philips May 28 '21 at 03:06

1 Answers1

2

You need to define the variable outside the function than change it inside the function when defining the function use global like the following

global.myGlobalVariable = "Value 1";

function myFunction(){
   myGlobalVariable = "Value 2";
}

it would be changed as a global variable

Moussa Bistami
  • 929
  • 5
  • 15