skip to Main Content

I have the following Javascript object:

data: {
  index: '',
  slides: '',
  timer: ''
}

I know index will be a number, slides will be an array of strings and timer will be the result of a setInterval.

Somewhere on my code I will have something like:

data: {
  index: 20,
  slides: ['s1', 's2'],
  timer: setInterval(() => this.data.index++, 10000)
}

Question

How should I initialise the object before knowing its values?

data: {
  index: 0,
  slides: [],
  timer: ????
}

Should I use the default value for each type?

2

Answers


  1. if timer will be the result of a setInterval() function, you should maybe initialize to 0 since setInterval() retrieves an id that represents the interval and you can use later to clear it, so its quite convinient to store it.

    chechk mdn!

    Login or Signup to reply.
  2. In terms of coding in JavaScript, it doesn’t really matter, that’s not going to harm your code in any possible way.

    However, for example, for code readability (i.e. everyone who is going to read the code after you), you can set index to 0 because you know it’s going to be a number, so everyone else can understand that it’s going to be a number.

    But, in other languages like TypeScript, it does really matter, that’s what TypeScript is all about.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search