Categories
JavaScript Answers

How Create an Associative Array or Hash in JavaScript?

In many programming languages, associative arrays let us store key-value pairs in our JavaScript app.

In this article, we’ll look at how to create associative arrays or a hash with JavaScript.

Create Associate Arrays with Objects

One way to create associative arrays is with JavaScript objects.

This is because we can remove JavaScript object properties dynamically.

The property name is the key and the value is the value.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2
console.log(dictionary)

to create the dictionary object with properties a and b .

dictionary is {a: 1, b: 2} .

We can also put property names in square brackets as strings.

For instance, we can write:

const dictionary = {}
dictionary['a'] = 1
dictionary['b'] = 2
console.log(dictionary)

This lets us add property names dynamically in our code.

Then to iterate through the object, we can use the Object.keys , Object.values or Object.entries methods.

Object.keys returns an array of keys of an object.

Object.values returns an array of values of an object.

Object.entries returns an array of array of key-value pairs of an object.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const key of Object.keys(dictionary)) {
  console.log(key, dictionary[key])
}

Then we get:

a 1
b 2

from the console log.

key has the key that’s being iterated through with the for-of loop.

We can loop through the values with Object.values :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const value of Object.values(dictionary)) {
  console.log(value)
}

So we get:

1
2

from the console log.

And we can loop through the key-value pairs with Object.entries :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const [key, value] of Object.entries(dictionary)) {
  console.log(key, value)
}

We destructure the key and value from the array being iterated through to get the key and value.

And so we get:

a 1
b 2

Since Object.keys , Object.values or Object.entries methods return arrays, we can get the length with the length property of what they return.

Maps

ES6 comes with the Map constructor to let us create associative arrays or hashes.

For instance, we can use it by writing:

const map = new Map()
map.set('a', 1)
map.set('b', 2)

We call the set method with the key and value respectively to add the entry.

Then we can iterate through it with the for-of loop since it’s an iterable object:

for (const [key, value] of map) {
  console.log(key, value)
}

We can use the get method with the key to getting the value for the given key:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.get('a'))

We pass in 'a' to return 1, which is what we have on the map.

To get the size, we use the size property:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.size)

And the console log should show 2.

Conclusion

We can create an associative array or hash with JavaScript objects with maps.

Categories
JavaScript Answers

How to Format a Number with Exactly Two Decimal Places in JavaScript?

Formatting a number with exactly 2 decimal places is something that we’ve to do sometimes with JavaScript.

In this article, we’ll look at how to format a number with exactly 2 decimal places with JavaScript.

Number.prototype.toFixed

The JavaScript number’s toFixed method lets us return a string version of the number rounded to 2 decimal places.

For instance, we can write:

console.log((10.888).toFixed(2))

Then we get:

'10.89'

from the console log.

Intl.NumberFormat Constructor

The Intl.NumberFormat constructor also lets us round a number to 2 decimal places.

For instance, we can write:

const formatter = new Intl.NumberFormat('en-US', {  
  minimumFractionDigits: 2,  
  maximumFractionDigits: 2,  
});  
console.log(formatter.format(10.888))

We use the Intl.NumberFormat constructor with a few arguments.

The first argument is the locale we want to use the format the number.

The 2nd argument is an object with the minimumFractionDigits and maximumFractionDigits properties to set the min and max number of decimal places the formatted number would have.

It returns an object with the format method with the number we want to format.

Then the console log should log '10.89' as we expect.

Conclusion

We can use the toFixed method or the Intl.NumberFormat constructor to format decimal numbers to 2 decimal places with JavaScript.

Categories
JavaScript Answers

How to Check or Uncheck a Checkbox with JavaScript?

Sometimes we may want to check or uncheck a checkbox with JavaScript programmatically in our web apps.

In this article, we’ll look at how to check or uncheck a checkbox with JavaScript.

Set the checked Value of the Checkbox Element

One way to check or uncheck a checkbox with JavaScript is to set the checked property value of the HTML checkbox element.

For instance, we can write the following HTML:

<button id='check'>
  check
</button>
<button id='uncheck'>
  uncheck
</button>
<input type='checkbox' id='checkbox'>

Then we can write the following JavaScript to add click listeners to the check and uncheck buttons so we can check and uncheck the checkbox respectively:

const checkBtn = document.getElementById("check")
const uncheckBtn = document.getElementById("uncheck")
const checkbox = document.getElementById("checkbox")

checkBtn.addEventListener('click', () => {
  checkbox.checked = true
})

uncheckBtn.addEventListener('click', () => {
  checkbox.checked = false
})

In the first 3 lines, we get the elements with getElementById .

Then we call addEventListener with the 'click' string to add a click listener.

And then we pass in callbacks to set the checked property to true and false respectively.

true will check the box and false will uncheck it.

Click the Checkbox Element

Another way to toggle the checkbox is to click the checkbox input itself with the click method.

For instance, we can write the following HTML:

<button id='toggle'>
  toggle
</button>
<input type='checkbox' id='checkbox'>

Then we can add a click listener to the toggle button to click the checkbox by writing:

const toggleBtn = document.getElementById("toggle")
const checkbox = document.getElementById("checkbox")

toggleBtn.addEventListener('click', () => {
  checkbox.click()
})

We call the checkbox.click method to click the checkbox.

Set the checked Attribute with the setAttribute and removeAttribute Methods

We can add or remove the checked attribute with the setAttribute and removeAttrbute methods respectively.

For instance, if we have the following HTML:

<button id='check'>
  check
</button>
<button id='uncheck'>
  uncheck
</button>
<input type='checkbox' id='checkbox'>

Then we can add click listeners to the buttons to check and uncheck the checkbox by writing:

const checkBtn = document.getElementById("check")
const uncheckBtn = document.getElementById("uncheck")
const checkbox = document.getElementById("checkbox")
checkBtn.addEventListener('click', () => {
  checkbox.setAttribute('checked', 'checked')
})
uncheckBtn.addEventListener('click', () => {
  checkbox.removeAttribute('checked')
})

In the check button’s click listener, we call setAttribute to set the checked attribute to check the checkbox.

And in the uncheck button’s click listener, we call removeAttribute to remove the checked attribute to uncheck it.

Conclusion

To check or uncheck a checkbox with JavaScript, we can set the checked property of a checkbox.

ALso, we can call the click method to click the checkbox as if the user clicks it.

And we can also call setAttribute and removeAttribute to add and remove the checked attribute from the checkbox respectively.

Categories
JavaScript Answers

Using HTML5 Local Storage vs. Session Storage

With modern browsers, at least 2 kinds of client-side storage for small amounts of text data are provided.

One is local storage and the other is session storage.

They both have different uses in our JavaScript web apps.

In this article, we’ll look at the difference between them.

And we also look at how to use them in our JavaScript code.

Differences Between Local Storage and Session Storage

Local storage and session storage serve different purposes.

Local storage lets us store data until they’re deleted.

They stay with the domain.

And changes are available for all current and future visits to the site.

Session storage changes are only available per tab.

Changes that are made are only available in that tab until it’s close.

Once it’s closed the stored data is deleted.

Using Local Storage

To use local storage, we can call methods in the localStorage method to get and set data.

To add data, we call the localStorage.setItem method, which takes a string key and the corresponding value respectively.

Both the key and value should be strings.

If they aren’t strings, then they’ll be converted into strings.

To get data, we call localStorage.getItem with the key.

It returns the value corresponding to the given key.

And to clear all local storage data, we call localStorage.clear .

To remove a local storage item with the given key, we call localStorage.removeItem .

For instance, we can use it by writing:

localStorage.setItem('foo', 'bar')
console.log(localStorage.getItem('foo'))

'foo' is the key and 'bar' is the corresponding value.

We can remove an item with removeItem by writing:

localStorage.setItem('foo', 'bar')
localStorage.removeItem('foo')
console.log(localStorage.getItem('foo'))

getItem should return null since we removed the entry with key 'foo' .

And we can call clear to clear all local storage entries:

localStorage.setItem('foo', 'bar')
localStorage.clear()

Using Session Storage

To manipulate session storage, we just remove localStorage with sessionStorage .

So we can write:

sessionStorage.setItem('foo', 'bar')
console.log(sessionStorage.getItem('foo'))

to add an item into session storage with setItem

'foo' is the key and 'bar' is the corresponding value.

We can remove an item with removeItem by writing:

sessionStorage.setItem('foo', 'bar')
sessionStorage.removeItem('foo')
console.log(sessionStorage.getItem('foo'))

getItem should return null since we removed the entry with key 'foo' .

And we can call clear to clear all session storage entries:

sessionStorage.setItem('foo', 'bar')
sessionStorage.clear()

Conclusion

We can use local storage or session storage to store small amounts of text data.

Local storage data are saved until they’re deleted and are available throughout the site.

Session storage data are only available in the current tab and are deleted once the tab is closed.

Categories
JavaScript Answers

How to Delete First Character of a String in JavaScript?

Sometimes we need to remove the first character of a string with JavaScript.

In this article, we’ll look at how to remove the first character of a string with JavaScript.

String.prototype.substring

We can use the JavaScript string’s substring method to extract a substring from a string.

We pass in the start and end index arguments respectively.

The character at the start index is included, but the character at the end index isn’t.

The end index is optional.

If we don’t include it, then the end index is the length property value of the string.

For instance, we can write:

const str = "foobar";
const newStr = str.substring(1);
console.log(newStr)

Then newStr is 'oobar' .

String.prototype.slice

The JavaScript string’s slice method also lets us get a substring from a string.

It takes the same arguments and they’re used the same way as substring .

For instance, we can write:

const str = "foobar";
const newStr = str.slice(1);
console.log(newStr)

And we get the same result.

slice also takes negative indexes.

Index -1 is the index of the last character of a string, -2 is the index of the 2nd last character of a string, and so on.

So to call slice with negative indexes to extract the substring from the first character to the end of the string, we write:

const str = "foobar";
const newStr = str.slice(-str.length + 1);
console.log(newStr)

We multiply str.length by -1 and add 1 to that to get the index of the 2nd character of the string.

And so newStr is the same as the other examples.

Rest Operator

Since JavaScript strings are iterable objects, we can use the rest operator to get the characters other than the first in its own array.

For instance, we can write:

const str = "foobar";
const [firstChar, ...chars] = str
const newStr = chars.join('')
console.log(newStr)

We have the chars array which has an array of characters from str other than the first character.

Then we can call join with an empty string to join the characters back into a string.

And so newStr is the same as we have before.

Conclusion

We can use the substring and slice methods to extract a substring from a string that has the 2nd character to the end of the original string.

Also, we can use the rest operator to get all the characters other than the first characters and call join to join the characters back into a string.