Vlad Predescu
Vlad Predescu

Reputation: 1

I make two variables while using addition to result another value?

So what I am asking is to look at the example given and maybe you'll understand what I mean by that.

If I have:

var x = "cheese";
var y = "bread";
var z = x + y; ( I want z = "sandwich" ) 

I just wanna know if that is possible and if it is, how to do it? I am a noob so please excuse my question if it is too stupid.

Thank you for your time!

Upvotes: 0

Views: 43

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370629

One (silly) option, if you're in the global scope, would be to pre-define x and y as un-writable properties on window with the sand and wich values, such that proceeding to do

var x = "cheese";
var y = "bread";

later in the code would not actually change window.x and window.y:

Object.defineProperty(window, 'x', {
  value: 'sand',
  writable: false
});
Object.defineProperty(window, 'y', {
  value: 'wich',
  writable: false,
});



var x = "cheese";
var y = "bread";
var z = x + y;
console.log(z);

I don't think something like this would work anywhere other than on the global scope, otherwise var x = <something> would necessarily reassign x to the new value in that scope (or throw an error, for example, if x had been declared as a const or let)

Upvotes: 1

Related Questions