Categories
JavaScript Answers

How to Unpack an Array into Separate Variables in JavaScript?

Oftentimes, we want to unpack JavaScript array entries into their own variables.

In this article, we’ll take a look at how to unpack a JavaScript array into separate variables with JavaScript.

Use the Destructuring Syntax

We should use the JavaScript array destructuring syntax to unpack JavaScript array entries into their own variables.

For instance, we can write:

const [x, y] = ['foo', 'bar'];
console.log(x);
console.log(y);

Then we assign 'foo' to x and 'bar' to y .

So x is 'foo' and y is 'bar' .

We can assign an array directly to variables on the left side.

For instance, we can write:

const arr = ['one', 'two'];
const [one, two] = arr;

We assign 'one' to one and 'two' to two .

Also, we can set a default value in case a value isn’t assigned to the variable.

To do this, we write something like:

const [one = 'one', two = 'two', three = 'three'] = [1, 2];
console.log(one);
console.log(two);
console.log(three);

We assign default values to one , two and three with the assignment statements on the left side.

So one is 1, two is 2, and three is 'three' .

three is 'three' since there’s no array entry assigned to it.

Conclusion

We can unpack JavaScript array entries into their own variables easily by using the destructuring syntax.

Categories
JavaScript Answers

How to Fix the “document.getElementByClass is not a function” Error in JavaScript?

Sometimes, we may run into the “document.getElementByClass is not a function” error in the console when we run our JavaScript code.

In this article, we’ll look at how to fix the “document.getElementByClass is not a function” error in our JavaScript code.

The Correct Method Name is document.getElementByClassName

The correct method name for the method that we use to get the elements with a given class name is the document.getElementByClassName method.

For instance, if we have the following HTML:

<div class='text'>
  foo
</div>
<div class='text'>
  bar
</div>
<p>
  baz
</p>

Then we can get all the elements with the class attribute set to text by writing:

const texts = document.getElementsByClassName("text");
console.log(texts)

We call document.getElementsByClassName with the class attribute value for the elements we want to select.

Therefore texts is an HTMLCollection object with the divs with the class text in it.

Conclusion

To get all the elements with the given class attribute value, we use the document.getElementsByClassName method.

There is not document.getElementsByClass method in the browser.

This will stop us from running into the run into the “document.getElementByClass is not a function” error when we run our JavaScript code.

Categories
JavaScript Answers

How to Check Variable Equality Against a List of Values in JavaScript?

Sometimes, we’ve to check variable equality against a list of values in JavaScript.

In this article, we’ll look at how to check variable equality against a list of values in JavaScript.

Use the Array.prototype.indexOf Method

We can use the JavaScript array’s indexOf method to check if a value is included in the list of values in the array.

For instance, we can write:

let foo;
//...
if ([1, 3, 12].indexOf(foo) > -1) {
  //...
}

We have the foo variable and we check if foo is 1, 3 or 12 by putting those values in an array and then call the indexOf method of the array with foo .

Then if it returns a number bigger than -1, we know foo is one of the values listed in the array.

Use the Array.prototype.includes Method

Another array method we can use to check if a variable is one of the values in a list is to use the includes method.

For instance, we can write:

let foo;
//...
if ([1, 3, 12].includes(foo)) {
  //...
}

We call includes the way we call indexOf .

If includes returns true , then we know foo is one of the values in the array.

Conclusion

We can put the list of values we want to check in an array and then use the includes or indexOf method to check if the variable is in the array.

Categories
JavaScript Answers

How to Create Enums in JavaScript?

Enums are entities that are containers for a list of constants.

There’s no native enum data type in JavaScript.

However, we can create our own JavaScript enums.

In this article, we’ll take a look at how to create enums with JavaScript.

Create an Object with Symbol Values and Freeze it

To create an enum object in JavaScript, we can create an object with symbol property values.

For instance, we can write:

const Colors = Object.freeze({  
  RED: Symbol("Colors.RED"),  
  BLUE: Symbol("Colors.BLUE"),  
  GREEN: Symbol("Colors.GREEN")  
});  
console.log(Colors.RED)  
console.log(Colors.BLUE)  
console.log(Colors.GREEN)

We create an object with the RED , BLUE and GREEN properties.

Then we set their values to symbols.

Symbols are primitive values that can be used as unique identifiers.

We create a symbol with the Symbol function.

Every symbol created with the Symbol function is unique even if we pass in the same argument to the symbol function, so:

Symbol("Colors.RED") === Symbol("Colors.RED")

is false .

We then call Object.freeze on the object to prevent the object from being frozen.

Once an object is frozen, we can’t add or change existing properties in the object.

Then we can access them like we can do within the console log statements.

Conclusion

We can create enums easily with JavaScript by creating an object with symbol values.

Then we can freeze the object with Object.freeze to prevent changes on the object.

Categories
JavaScript Answers

How to Render HTML Inside a Text Area with JavaScript?

Sometimes, we want to render HTML inside a text area.

In this article, we’ll look at how to render HTML content inside a text area.

Render Content in a contenteditable Div

An HTML text area can’t render HTML.

However, we can make a div’s content editable with the contenteditable attribute.

Therefore. we can use an editable div as we do with a text area but with HTML content.

For instance, we can write the following HTML:

<div class="editable" contenteditable="true"></div>
<button class="bold">toggle red</button>
<button class="italic">toggle italic</button>

Then we can style it with the following CSS:

.editable {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  padding: 5px;
  resize: both;
  overflow: auto;
}

And then we can get the buttons and change the text when we click on them:

const bold = document.querySelector('.bold')
const italic = document.querySelector('.italic')
const editable = document.querySelector('.editable')

const toggleRed = () => {
  const text = editable.innerHTML;
  editable.innerHTML = `<p style="color:red">${text}</p>`;
}

const toggleItalic = () => {
  const text = editable.innerHTML;
  editable.innerHTML = `<i>${text}</i>`;
}

bold.addEventListener('click', toggleRed);
italic.addEventListener('click', toggleItalic);

We make the div editable with the contenteditable attribute set to true .

We select all the elements we added with document.querySelector .

Then we have the toggleRed function that gets the existing innerHTML from the editable div.

Then we add a p element with color style set to red.

Likewise, we have the toggleItalic function to get the innerHTML from the editable div.

Then we wrap the i tag around the text.

The CSS just sets the width, border, padding, and overflow styles for the editable div.

Now when we click on toggle red and toggle italic, we see the corresponding styles applied to the text we typed into it.

Conclusion

We can render HTML in an editable div instead of a text area if we want to add a box where we can edit rich text.