At work, I recently ran into a scenario where we were capturing a user's date of birth (DOB). This information is collected in 3 fields day, month, and year. If your DOB is January 7, 1962, people were inputting 1 for the month, 7 for the day, and 1962 for the year. This sounds good but our back-end database required both the month and day to be 2 digits. So I needed to find a way to add a leading zero for both of these fields.
Starting Data
let month = 1;
let day = 7;
My simple solution in one line is:
month = `0${month}`.slice(-2)
Let's walk through this code. This combines 0
with the value the user inputs for their month. Then it takes the right two digits and assigns this to the month.
But what if the user inputs the value 10
for their month? It still works. It will combine 0 with 10 to produce 010
and then it takes the right two digits which is 10
.
Let's Connect
Thanks for reading my article today. If you like my content, please consider buying me a coffee ☕.
An object is frequently used to store data. Sometimes you end up with multiple data objects that you need to combine their contents. In this article, I will show you several ways to merge objects in JavaScript.
Format of an Object
An Object is a collection of key-value pairs. Let's take a look at this simple object:
const customer = {
name: 'Jennifer',
age: 60
}
Both name
and age
are the keys
of the object. The key name
has a value
of Jennifer
and the key age
has a value
of 60
.
[continue reading…]
In yesterday's article, I showed you two ways to format your output to the console in JavaScript. If you have not read it, check it out here.
Today I wanted to show you another console command: console.trace()
.
console.trace()
The console.trace() method outputs a stack trace to the Web console.
Here is an example of how to use this:
function foo() {
function bar() {
console.trace();
}
bar();
}
foo();
In the console, the following trace will be displayed:
bar
foo
<anonymous>
Let's Connect
Thanks for reading my article today. If you like my content, please consider buying me a coffee ☕.
If you have been a programmer for more than a day, then you have used a console.log
to display data. You may want to see the value of data while your programming running or you may be trying to troubleshoot a problem. Sometimes the data displayed in the console can be a challenge to read. I will show you some methods to make the display of the data more readable.
The biggest challenge in using a console.log is when you want to display data that is an array or an object. By default, this data does not display very well in the console.
[continue reading…]
In this article, I will show you how to create a toggle to display items in a grid from a list. This will be using basic JavaScript skills with no external code or libraries. We will be using CSS Grid.
What We Will Be Creating
[continue reading…]