I am trying to change the values of an object using function outside of that object, so that I can access those values later (in yet another objects).
I am new to programming, apologies if there is something wrong in my description or question.
For instance,
let myObject = {
startTime: '',
endTime: '',
newId: '',
set setStartTime (val) {
this.startTime = val
}
}
stopButton.addEventListener('click', () => {
const {startTime, endTime, newId} = myObject
myObject.setStartTime = new Date()
})
console.log(myObject.startTime)
So when I console log myObject.startTime - in the console its value is empty. Apparently, because it just logs the initial (unchanged value). Why does this happen, and how can I solve this?
when I console log 'myObject.startTime' - in the console its value is empty
Because your code when it loads at first time will show the initial value of myObject which is empty. After you click on stopButton will change but not log any thing, because console.log(myObject.startTime) outside of function, Solution, put console.log inside of click of stopButton.
var dateNow = null;//declare it globally here
stopButton.addEventListener('click', () => {
const {startTime, endTime, newId} = myObject
myObject.setStartTime = new Date()
dateNow = myObject.setStartTime;//<-- assign it value here
})
console.log(dateNow )//<-- call it outside of function here
if I can use that new value (generated inside a function) outside of that function?
Yes you can, just declare a variable globally (outside of function ) to hold the generated value inside click function; then you can call it outside of it.