3 JavaScript Things I Just Learned That I Probably Should Have Already Known

Travis Prol
The Startup
Published in
3 min readDec 12, 2020

.toLocaleString, .toFixed, type=“search”

JavaScript is one of the most powerful programming languages. Because of that, it is very hard to learn every aspect of it and become a master. In my software engineering bootcamp, I learned the language very quickly, but I missed out on some of the built in functions Javascript offers.

.toLocaleString

I have used .toLocaleString to manipulate my data in two different ways. The first way is to format a date.

Let’s take a look at how .toLocaleString formats the following new date.

let date = new Date
date // => Sat Dec 10 2020 10:00:00 GMT-0500 (Eastern Standard Time)
let formattedDate = date.toLocaleString("en-US")
formattedDate = 12/10/2020, 10:00:00 AM

You can see that this built in JavaScript function formatted this date into a much more readable, and usable format. From here, we can then use a .slice to grab just the date, or just the time.

The "en-US" argument is a locale and it’s short code. Check out this stack overflow post for a list of locale codes.

The other way I have used .toLocaleString is to add commas to a large number to make it easier to read.

let number = 1000000000
let numberWithCommas = number.toLocaleString("en-US")
numberWithCommas // => "1,000,000,000"

It is important to note that .toLocaleString changes the datatype from a number, to a string.

typeof(number) // => "number"
typeof(numberWithCommas) // => "string"

.toFixed

Another function I have found useful, specifically while calculating percentages, is .toFixed. This function is used to limit the number of digits shown after the decimal place. .toFixed takes in 1 argument, the number of decimal places you want to display. If the argument is omitted, it defaults to 0.

let number = 0.12345
let noDecimal = number.toFixed() // => "0"
let twoDecimals = number.toFixed(2) // => "0.12"

This function also turns these numbers into strings.

typeof(noDecimal) // => "string"
typeof(twoDecimals) // => "string"

type=“search”

This last thing is not a function, but relates to building a search form. When building search forms, I always used type="text" and created a button to reset the input. If you use type="search", however, two additional features are automatically built into the form.

The first is a “X” appears at the end of the search bar after the user starts typing.

The user can click that “X” to clear out the form! This works with both static, and dynamic searches.

type="search" also gives the user the ability to use the “esc” key on their keyboard to clear out the search field. This also works with both static and dynamic searches.

--

--

Travis Prol
The Startup

Full Stack Web Developer 🧑🏻‍💻 Artists Who Code 🤓 Lets go Yanks ⚾️