Create a variable using a parameter

Let’s say I wanted to create a function that makes a variable, like here:

function createVariable(var) {
var = ""
console.log(var)
}

This would give me an error. Any way to bypass this?

var is a keyword, you can’t name the variable var

Oops, sorry, I just meant that as an example (I didn’t actually write that). If it was var_, then what would the issue be?

Should work, however, you then have an anti-pattern. Creating a variable to exists outside its intended scope is a bad practice.

Thanks for the help. However, I get an error message for some reason. “Identifier ‘var_’ has already been declared”.

Could you post the actual code? All of it? That might help me narrow down the problem

If you have:

function someFunc(someParam){
 let someParam = "this";//you could use let, const or var to throw an error
}

You will get an error saying that someParam is already defined. That is because it is “defined” as a function argument, so you don’t need to use a keyword to reassign it.


<html>
	<title>Hello world!</title>
<body>
	<script>
		function create(var_) {
		let var_ = ""
		document.write((var_))
		}
		create(variable1);
	</script>
</body>
<html>

That makes sense. Any way to bypass this error?

var_ is the parameter, so then you can’t re-declare this variable within the body of the function. you can re-assign the variable, but then don’t use let. let, var and const are only used when declaring a variable.

I cover that in my answer. But why would you want to re-assign the parameter?

As an easier way to create an unassigned variable. Instead of typing it out every time, I can call the function, with the parameter as the variable I want to create.