For each iteration print name not value

const varone    = 98
const vartwo    = 25
const varthree  = 9
const varfour   = 36

const someArray = [varone, vartwo, varthree, varfour];
someArray.forEach(element => {
  console.log(element);
});

The above will generate the value:
image

But instead, I wnat to print:

varone
vartwo
varthree
varfour

I am seeking help, How should I modify the code?

Variable names aren’t normally accessible from a programming standpoint.

You would need to store the variables as properties of an object.

> const vars = {
      varone: 98,
      vartwo: 25,
      varthree: 9,
      varfour: 36
  };
> const varEntries = Object.entries(vars);
> varEntries.forEach(function ([key, value]) {
    console.log(key);
  });

varone
vartwo
varthree
varfour
1 Like

Thanks, sir, I knew this, but sir, those numerical values are not constant and are coming dynamically. Compare those variables with date/hours/minutes/seconds of a current date.

I tried this:

const varone    = 98
const vartwo    = 25
const varthree  = 9
const varfour   = 36

const convertArray = {varone:varone, vartwo:vartwo, varthree:varthree, varfour:varfour};
console.log(convertArray)
const varEntries = Object.entries(convertArray);
varEntries.forEach(function ([key, value]) {
  console.log(key, value);
});
const convertArray = {varone:varone, vartwo:vartwo, varthree:varthree, varfour:varfour};

Can be written in shortform :slight_smile:

const convertArray = {varone, vartwo, varthree, varfour};
1 Like

Thanks.

This is the final code:

var varone    = 98
var vartwo    = 25
var varthree  = 9
var varfour   = 36

const convertArray = {varone, vartwo, varthree, varfour};
console.log(convertArray)
const varEntries = Object.entries(convertArray);
varEntries.forEach(function ([key, value]) {
  console.log(key, value);
  if (value < 10) {
	  console.log(value = "0" + value); 
	  console.log(key, value);
  }
});

console.log("Values of original variables varone, vartwo, varthree, varfour are: " + varone+ "," , vartwo + "," , varthree + "," , varfour + "," );

The key value pairs in an array are updating, but the actual variable’s value is not updating, what should I do next so that the actual values of the original var/const gets updated.

Logic: A coming soon counter clock was build here. But the one with “1” numeric digit out of Days/Hours/Minutes/Second used to distort the CSS as compared to other which have “2” numeric digit. So I was planning to concatenat one “0”(to make one digit numeric two digit) as pointed by @Archibald in this discussion.

Another option @codeispoetry is String.prototype.padStart()

const nums = [ 98, 25, 9, 36 ]

console.log(
    nums.map((num) => num.toString().padStart(2, '0')
)
// ['98', '25', '09', '36']

or maybe as a utitlity function

const nums = [ 98, 25, 9, 36 ]

const padZeros = (num, pad = 2) => num.toString().padStart(pad, '0')

console.log(nums.map(padZeros))
//  ['98', '25', '09', '36']
1 Like

This seems to be magical, let me explore further, Thanks.

Regarding the last line

console.log(nums.map(padZeros))

As opposed to doing something like this

console.log(nums.map((num) => padZeros(num, 2)))

The following article from Professor Frisby’s Mostly Adequate guide is particularly useful. I know I found it enlightening at the time of reading :slight_smile:

1 Like

That’s a good point. What I found useful is to think of the second one as just passing through the num value, without doing anything else. The number 2 as the second argument is already the default value of the function, so the 2 might as well not be there.

console.log(nums.map((num) => padZeros(num)))

Nothing else is being done in regard to the num value, it’s just being passed through to the padZeros function. When that happens it’s like an onion shell, where the function surrounding the call to the padZeros function can be peeled off and removed, leaving us with just the padZeros function being more directly used instead.

console.log(nums.map(padZeros))
2 Likes

Need to scrap the above padZeros, it’s flawed!!

const nums = [ 98, 25, 9, 36, 5, 9 ]

console.log(nums.map(padZeros))
// ['98', '25', '09', '036', '0005', '00009']

Stupid of me. The second argument passed by map, the index is being passed in as the second argument to padZeros the padding. I know this stuff and am now kicking myself. Another example of this is trying something like

nums.map(parseInt)
//  [98, NaN, NaN, NaN, NaN, NaN]

In that instance the index is being passed to the radix

Lets have another go. lol

We could just do a pad to two function

const nums = [ 98, 25, 9, 36, 5, 9 ]

const padToTwo = (num) => num.toString().padStart(2, '0')

console.log(nums.map(padToTwo))
// ['98', '25', '09', '36', '05', '09']

Or if a little more adventurous a bit of manual currying

const nums = [ 98, 25, 9, 36, 5, 9 ]

// curry function
const padZeros = (pad) => (num) => num.toString().padStart(pad, '0')

const padToTwo = padZeros(2)
console.log(nums.map(padToTwo))
// ['98', '25', '09', '36', '05', '09']

const padToThree = padZeros(3)
console.log(nums.map(padToThree))
// ['098', '025', '009', '036', '005', '009']

Sorry about that.

2 Likes

There is no need to add a preceding zero digit. For the CSS of the <div> elements insert:

  width: 90px;
  text-align: center;

BTW: You need to consider how this would display on small smartphones.

2 Likes

This modification ensured that digits will always remain two in number:

document.querySelector(".day").innerHTML      = String(nDays).padStart(2, '0');
document.querySelector(".hours").innerHTML    = String(nHours).padStart(2, '0');
document.querySelector(".minutes").innerHTML  = String(nMins).padStart(2, '0');
document.querySelector(".seconds").innerHTML  = String(nSecs).padStart(2, '0');

I find that it helps to move duplication off elsewhere. For example, to have a separate twoDigits() function.

function twoDigits(value) {
  return String(value).padStart(2, '0');
}
document.querySelector(".day").innerHTML      = twoDigits(nDays);
document.querySelector(".hours").innerHTML    = twoDigits(nHours);
document.querySelector(".minutes").innerHTML  = twoDigits(nMins);
document.querySelector(".seconds").innerHTML  = twoDigits(nSecs);
1 Like

Hi there @Paul_Wilkins
There was another discussion here. The solution was given by @PaulOB, but he was also looking for alternative methods.

I was trying to build something that when 30% of the conetent height is traversed: something should happen: Bottom to top Pop appear, for example.

Key was when scroll has moved 30% of the content height, Intersection observer should do its job.

@PaulOB has designed the finbal working solution, but he was also looking for some alternative elegant way. If you can invest sometime, and have any other way to approach the same solution with more optimized code.

Thanks for the callout - I don’t think that I would do things any other way there.

2 Likes

I would be inclined to do a regular expression replace.

document.querySelector(".day").innerHTML      = nDays.replace(/^\d$/,"0" + nDays) ;
document.querySelector(".hours").innerHTML    = nHours.replace(/^\d$/,"0" + nHours) ;
document.querySelector(".minutes").innerHTML  = nMins.replace(/^\d$/,"0" + nMins) ;
document.querySelector(".seconds").innerHTML  = nSecs.replace(/^\d$/,"0" + nSecs) ;
1 Like

Just having a play here, but presuming you have HTML something like this

<ul class='countdown'>
    <li class='days'></li>
    <li class='hours'></li>
    <li class='minutes'></li>
    <li class='seconds'></li>
</ul>

Going off what you were working with at the top, I would look at using a loop.

const padZeros = (pad, num) => String(num).padStart(pad, '0')

const days = 98
const hours = 22
const minutes = 9
const seconds = 5

// [time, padding]
const times = [
  [days, 3], [hours], [minutes], [seconds]
]

document
    .querySelectorAll('.countdown li')
    .forEach((timeSpan, i) => {
      const [currTime, padding = 2] = times[i]
      timeSpan.textContent = padZeros(padding, currTime)
    })

In the above I am making use of Array destructuring and a default value for padding if none is given.

1 Like

Or

const padZeros = (pad, num) => (String(num).padStart(pad, '0'))

const days = 98
const hours = 22
const minutes = 9
const seconds = 5

// [time, padding]
const times = { days, hours, minutes, seconds }

Object
  .entries(times)
  .forEach(([timeSpan, currTime]) => {
      document
          .querySelector(`.countdown .${timeSpan}`)
          .textContent = padZeros(
              (timeSpan === 'days') ? 3 : 2, currTime
          )
  })

1 Like