Categories
JavaScript Answers

How to Add Colors in JavaScript Console Log Output?

To make console long output easier to see, we can add colors to JavaScript’s console log.

In this article, we’ll look at how to add colors to console log output in the browser dev console.

Add CSS Styles to Console Log Output

We can add CSS styles to console log output with the %c tag.

For instance, we can write:

console.log('%c hello world ', 'background: #222; color: #bada55');

We add the %c tag so that we can apply the CSS styles in the 2nd argument to the hello world text.

We set the background property to set the background color.

And we set the color property to change the text color.

The console.error Method

The console.error method lets us log things with a red background.

This lets us show data in more obvious ways.

For instance, we can write:

console.error("hello world");

to use the method.

The console.warn Method

The console.warn method lets us log things on a yellow background.

To use it, we write:

console.warn("hello world");

Bash Color Flags

Also, console.log lets us add Bash color flags to set the color of the text.

For instance, we can write:

console.log('x1B[31mhellox1B[34m world');

x1B[31 means red.

And x1B[34m is blue.

Also, we can set the background color of text by writing:

console.log('x1b[43mhighlighted');

x1b[43m sets the background color to yellow.

Conclusion

We can log colored text to the browser development console with various tricks.

Some console methods lets us change colors in various ways.

Categories
JavaScript Answers

How to Sort an Array of Integers Correctly with JavaScript?

Sorting an array of integers is something that we’ve to a lot in our JavaScript app.

In this article, we’ll look at how to sort an array of integers correctly in our JavaScript app.

Array.prototype.sort

The sort method lets us sort an array by passing in a comparator function.

To use it to sort numbers, we write:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => a - b);
console.log(sorted)

to do an ascending sort.

So sorted is [1, 2, 3, 4] .

The numbers will be swapper if the callback’s return value is positive, so we get them sorted in ascending order.

To sort in descending order, we just swap a and b in the expression we return:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => b - a);
console.log(sorted)

We must use sort with the callback so that we can compare the numbers.

Then sorted is [4, 3, 2, 1] .

If we don’t pass in a callback, then sort assumes that we’re sorting strings.

And it’ll try to sort items alphabetically.

We can just use Math.sign to return -1 for if an argument is a negative number, 0 if the argument is 0, and 1 if the number is positive.

So we can write:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => Math.sign(a - b));
console.log(sorted)

to sort ascending.

And:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => Math.sign(b - a));
console.log(sorted)

to sort descending.

Conclusion

To sort an JavaScript array with numbers correctly, we should pass in a comparator function to compare the numbers if we use sort .

Otherwise, it’ll assume that we’re sorting strings and will try to sort the items alphabetically.

Categories
JavaScript Answers

How to Remove All Child Elements of a DOM Node in JavaScript?

Removing all child elements from a DOM node is something that we’ve to do sometimes in JavaScript.

In this article, we’ll look at how to remove all child elements of a DOM node with JavaScript.

Clearing innerHTML

One way to remove all child elements of an element is to set the innerHTML property of the element to an empty string.

For example, if we have the following HTML:

<button>
  clear
</button>
<div>
</div>

Then we can write the following JavaScript to add the elements to the div.

And we can clear the items when we click the clear button:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  div.innerHTML = ''
})

We get the div and the button with document.querySelector .

Then in the for loop, we create the p elements and add them to the div.

And then we call addEventListener on the button with 'click' as the first argument to add a click listener.

Then in the callback, we set div.innerHTML to an empty string to clear its contents when we click the button.

Clearing textContent

Instead of clearing innerHTML , we can clear textContent instead.

To do this, we write:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  div.textContent = ''
})

We just switch innerHTML for textContent .

And the rest of the code is the same.

Looping to Remove every lastChild from the DOM

We can remove all the child elements of an element from the DOM with the removeChild method.

For instance, we can write:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  while (div.firstChild) {
    div.removeChild(div.lastChild);
  }
})

We have a while loop inside the click listener.

We check if there’re any firstChild elements within the div with div.firstChild .

If there’re, we call removeChuld to remove div.lastChild until there’re no firstChild left.

Looping to Remove every lastElementChild from the DOM

We can also remove every lastElementChild from an element.

To do this, we write:

const div = document.querySelector('div')
const button = document.querySelector('button')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  while (div.lastElementChild) {
    div.removeChild(div.lastElementChild);
  }
})

lastElementChild returns the last child element of the given element.

We can just call removeChild to remove all of them until there’s nothing left.

Conclusion

We can remove all the child elements of an element easily by setting innerHTML or textContent .

Also, we can remove the child elements one by one with removeChild .

Categories
JavaScript Answers

How to Find the Sum of an Array of Numbers with JavaScript?

Finding a sum of an array of numbers is something that we’ve to do a lot in our JavaScript apps.

In this article, we’ll look at how to find the sum of an array of numbers with JavaScript.

Array.prototype.reduce

The JavaScript array’s reduce method lets us get numbers from an array and add them up easily.

To do this, we write:

const sum = [1, 2, 3, 4].reduce((a, b) => a + b, 0)
console.log(sum)

We call reduce with a callback to help us add up the numbers.

a is the accumulated result, which is the partial sum.

And b is the item that we’re iterating through.

In the 2nd argument, we pass in 0 to set the initial result of a .

Therefore, sum is 10.

Lodash sum Method

Lodash has the sum method that is specially made to add up numbers in an array together.

For instance, we can write:

const array = [1, 2, 3, 4];
const sum = _.sum(array);
console.log(sum)

to call sum with the array number array.

Loop

We can use a for-of loop to loop through an array of numbers and add them up.

For instance, we can write:

const array = [1, 2, 3, 4];
let sum = 0
for (const a of array) {
  sum += a
}
console.log(sum)

We get number a from array and add them to sum .

Also, we can use a while loop to loop through the number array.

To do this, we write:

const array = [1, 2, 3, 4];
let sum = 0
let i = 0;
while (i < array.length) {
  sum += array[i];
  i++
}
console.log(sum)

Array.prototype.forEach

We can also use the forEach method to loop through the number array and add up all the numbers.

For example, we can write:

const array = [1, 2, 3, 4];
let sum = 0
array.forEach(a => {
  sum += a;
});
console.log(sum)

We call forEach with a callback.

Then in the callback, we get the value that’s being iterated through with the first parameter.

Then we add that value to the sum .

Conclusion

There’re several ways we can use to find the sum of the numbers in a number array with JavaScript.

One way is to use the reduce method.

Other ways include using the for-of loop, while loop, or forEach to loop through an array.

Categories
JavaScript Answers

How to Get a Random Item From a JavaScript Array?

Getting a random item from a JavaScript array is an operation that we’ve to do sometimes.

In this article, we’ll look at ways to get a random item from a JavaScript array.

Math.random

We can use the Math.random method to return a random index from an array.

Then we can use that to get an element from the array.

For instance, we can write:

const items = [1, 2, 3]
const item = items[Math.floor(Math.random() * items.length)];

Since Math.random returns a number between 0 and 1, we’ve to multiply the returned number by items.length to get an index.

Also, we’ve to use Math.floor to round the number down to the nearest integer to get an index.

Lodash

Lodash has various handy methods we can use to get a random item from an array.

The sample method lets us get a random item from an array.

For instance, we can write:

const items = [1, 2, 3]
const item = _.sample(items);
console.log(item)

We just pass in the array we want to get an item from as the argument.

Also, we can use the random method to pick a random number from 0 up to the given number.

For instance, we can write:

const items = [1, 2, 3]
const item = items[_.random(items.length - 1)]
console.log(item)

We just pass in the max number in the range we want to get.

Also, we can shuffle the entire array and pick the first item from the shuffled array.

To do this, we can use the shuffle method.

For example, we can write:

const items = [1, 2, 3]
const [item] = _.shuffle(items)
console.log(item)

We call shuffle with the items array to return a shuffled version of the items array.

Then we get the first item with destructuring.

Shuffle with sort

We can also shuffle arrays with sort .

For instance, we can write:

const items = [1, 2, 3]
const [item] = items.sort(() => 0.5 - Math.random())
console.log(item)

to shuffle the array by calling sort with a callback that returns a number between -0.5 and 0.5.

This lets us shuffle an array since items are swapped when the returned number is positive.

Conclusion

There’re several ways to get a random item from a JavaScript array.

We can either use native JavaScript methods.

Or we can use convenience methods from Lodash to help us.