Question: I'm trying to access a global variable in two Javascript methods. The first one is supposed to write to the variable and the second one is supposed to read it.

I have the following code:

```
var selectedObj;
function first(){
    selectedObj = window.getSelection();
    alert(selectedObj);
}

function second(){
    alert(selectedObj);
}

```

So the user selects some text in an contenteditable textbox. When function first() runs, it does in fact display what was selected. So I know its value is going into the global variable selectedObj.

But before running function second(), the selected text becomes unselected. However, nothing happens that explicitly sets the value of selectedObj. Ergo, I would expect it to still retain the value of what was previously selected by the user.

But it doesn't. When the function second() runs, the alert is empty.

The alert won't be empty if the user **doesn't** deselect the text, so I know the global variable *can* work. But I need it to retain its value even if the user deselects the text.

How can I make this happen?

Answer: 
Like someone else suggested, setting it to a local variable (by value instead of reference) seems to work.

```js
var selectedObj;

function first() {
  let newSelection = window.getSelection().toString();
  selectedObj = newSelection;
  alert(selectedObj);
}

function second() {
  alert(selectedObj);
}
```

```html
Lorem ipsum yada yada
<button onclick="first()">First</button>
<button onclick="second()">Second</button>
```
as mentioned in question, before second() runs text becomes unselected causing selectedObj to set to empty value.

You should set the value of selectedObj if window.getSelection() !== ""