0

How you can make a variable from an array of characters in Javascript.

chars = ["a","b","c","d"];
chars[1],chars[0],chars[2] = "Hellow world";
alert(bac); // Hellow world
15
  • 3
    Why would you want to do that? Variable/dynamic variables are usually considered bad coding practice. Why not use a map instead? Commented Nov 19, 2016 at 1:30
  • You can't. You can set properties on an object, though. (You could eval, I suppose, but please don't.) Commented Nov 19, 2016 at 1:30
  • 1
    What are you actually trying to achieve? Commented Nov 19, 2016 at 1:30
  • 2
    The problem is that you want to do something that isn't a good idea. So the question is why you want to do so we can suggest a better solution. "i'm using this for obfuscation" Why don't you use an existing tool for obfuscating your code? Commented Nov 19, 2016 at 1:41
  • 1
    "but if you search for that variable in javascript code you will not find it" - Who do you think will be searching through your code? And why? Commented Nov 19, 2016 at 1:56

2 Answers 2

3

There is no need for eval or map:

var chars = ["a", "b", "c", "d"];
window[chars[1] + chars[0] + chars[2]] = "Hellow world";
console.log(bac); // Hellow world

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

1 Comment

That's a property on an object, which is what I said, no?
1

This is absolutely not a good practice. Only do it for fun. No professional work uses code like this.

That said:

chars = ['a', 'b', 'c']
eval("window." + chars.join('') + " = 'Hello World'")
alert(abc)

Yep.

2 Comments

No reason to use eval here, you can just use [] notation.
Haha true. I wonder why I thought of using eval. Well, @Arvind got it simpler

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.