1

i want to create a variable like this in javascript

variable1.varible2.variable3 = "Hi Its working";
alert(variable1.varible2.variable3);
7
  • 2
    I don't know whether or not this is even possible, but even if it is, why would you want to do this? This could lead to seriously unreadable code, since variable1.something can now mean multiple things. Commented Apr 21, 2019 at 14:43
  • I need to add the third also Commented Apr 21, 2019 at 14:44
  • this is what i actually want my previous code var mockwindow = {}; mockwindow.location = "replacedurl.com/document"; alert(mockwindow.location); I want to add the third like alert(mockwindow.location.href) Commented Apr 21, 2019 at 14:45
  • I agree with Tim. This is where you usually have an object with another object exposed. For example you could have a car object with an engine object with a type as property. Then you could write Car.engine.type = "V8 Turbo" Commented Apr 21, 2019 at 14:46
  • 1
    that's not a variable, it's setting an object property. That is, if you already have an object called variable1, which has a property variable2 that holds another object, then you can set a property called variable3 on it with that code. But it doesn't, and can't, assign to a new variable. The . character is not legal in a JS identifier. Commented Apr 21, 2019 at 14:52

3 Answers 3

1

You cannot have . in variable names.

You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.

If you really want the variable1.varible2.variable3 to return value "Hi Its working". You can use objects.

let variable1 = {
  variable2:{
    variable3:"Soemthing"
  }
}
console.log(variable1.variable2.variable3)

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

Comments

0

you cant use . for the name of a variable but you can do this with objects:

let person = {
  name: {
    first: 'john',
    last: 'snow'
  },
  eyes: {
    color: 'black'
  }
}
console.log(person.name.first); //john

Comments

0
var car = new Object();
car.type = "Fiat";
car.model = "500";
car.color = "white";
car.engine = {type:"V8", fuel:"diesel"}
console.log(car)

window.alert(car.engine.type) 

Then you could write Car.engine.type = "V8 Turbo"

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.