Categories
JavaScript Answers

How to Add a New Array Elements at the Beginning of an Array in JavaScript?

Adding a new array element to the beginning of an array is something that we’ve to sometimes in our JavaScript apps.

In this article, we’ll look at how to add new array elements at the beginning of an array in JavaScript.

Array.prototype.concat

One way to add an element to the beginning of a JavaScript array is to use the concat method.

We call concat with a new array with the element we want to add.

Then we pass in the existing array as the argument.

For instance, we can write:

const array = [1, 2, 3]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array)
console.log(newArray);

We have the array array that we want to add a new first element to.

newFirstElement is the first element we want to add.

To do this, we create a new array with newFirstElement in it.

Then we call concat with array to concatenate array to the new array we created.

A new array with both of them combined is returned, so newArray is [4, 1, 2, 3] .

Array.prototype.unshift

The unshift method available with JavaScript arrays is specially made to add an element to the beginning of an array.

The addition of the element is done in place, so the array it’s called on is mutated.

For instance, we can write:

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

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

Spread Operator

We can use the spread operator to add elements from one array to another by making a copy and putting the items in the new array.

For instance, if we have:

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

Then all the items from array are spread into the newArray .

Therefore, newArray is [4, 1, 2, 3] .

Array.prototype.splice

Another way to add an element to the beginning of an array is to use the splice method.

splice changes an array it’s called in place.

For instance, we can write:

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

We call splice with the index of array we want to change in the first argument.

The 2nd argument is the number of elements we want to remove starting from the index we specified in the first argument.

And the last argument is the element we want to insert before the index we have in the first argument.

Therefore, array should be [4, 1, 2, 3] .

Conclusion

We can use array methods or the spread operator to add items to the beginning of an array with JavaScript.

Categories
JavaScript Answers

How to Convert a String to an Integer in JavaScript?

Converting a string to an integer in JavaScript is something that we may have to do sometimes.

In this article, we’ll look at how to convert a string to an integer with JavaScript.

The Number Function

We can use tyhe Number function to convert an integer string into an integer.

For instance, we can write:

const num = Number("1000")  
console.log(num)

Then num is 1000.

The parseInt Function

The parseInt function also lets us convert an integer string into an integer.

It takes the number string and the base of the number we’re converting respectively.

For instance, we can write:

const num = parseInt("1000", 10);  
console.log(num)

Then we get the same result as the previous example.

Unary Plus Operator

The unary plus operator also converts a string to an integer.

So we can put the + operator right before the integer to convert it to a number.

For instance, we can write:

const num = +"1000"  
console.log(num)

and get the same result.

Math.floor

The Math.floor method rounds a number down to the nearest integer.

It also accepts a number string, so we can pass it into the Math.floor method, and it’ll return the integer rounded down to the nearest integer.

For instance, we can write:

const num = Math.floor("1000.05")  
console.log(num)

And we get that num is 1000.

Math.round

The Math.round method also lets us round a number.

The rule for rounding is that if the fractional portion of the argument is bigger than 0.5, then the argument is rounded to the next highest integer in absolute value.

Otherwise, it’ll be rounded to the nearest integer with the lower absolute value.

It also takes a string and will do the conversion to a number before rounding.

For instance, we can write:

const num = Math.round("1000.05")  
console.log(num)

The parseFloat Function

The parseFloat function lets us convert a floating point number string into a number.

It also works with converting integer strings into integers.

For instance, we can write:

const num = parseFloat("1000")  
console.log(num)

Conclusion

There are many ways to convert an integer string to an integer with JavaScript.

Categories
JavaScript Answers

How to Get the Selected Value from a Dropdown List using JavaScript?

Getting the selected value of a dropdown is something that we’ve to sometimes in JavaScript.

In this article, we’ll look at how to get the selected value from a dropdown with JavaScript.

Get the Selected Value from a Dropdown List

To get the selected value from a dropdown list, we can get the select element.

Then we can use the value property to get the value of the value attribute of the selected option element.

For instance, if we have the following HTML:

<select>
  <option value="1">apple</option>
  <option value="2" selected>orange</option>
  <option value="3">grape</option>
</select>

Then the 2nd option element is selected since we have the selected attribute added to it.

So we can write:

const select = document.querySelector("select");
const selectedChoice = select.value;
console.log(selectedChoice)

to get the select element with document.querySelector .

Then we get the value of the value attribute of the select option element with the value property.

And then we should see that selectedChoice is 2.

Get the Text of the Selected Option Element from a Dropdown List

We can also get the text of the select option element from a dropdown list.

To do that, we write:

const select = document.querySelector("select");
const value = select.options[select.selectedIndex].value;
const text = select.options[select.selectedIndex].text;
console.log(value, text)

assuming we have the same HTML code as before.

We get the select element with document.querySelector .

Then we get all the options in an object with the select.options property.

select.selectedIndex has the index of the selected option element.

The value property has value of the value attribute of the selected element.

And text property has the text of the option element in the selected element.

Therefore, value is 2 and text is 'orange' .

Watch for Changes

We can listen to the change event of the dropdown to watch for changes in the choice of the selected item.

For example, if we have the same select element of the previous 2 examples, we can write:

const select = document.querySelector("select");
select.addEventListener('change', (event) => {
  const {
    value,
    text
  } = event.target.options[event.target.selectedIndex]
  console.log(value, text)
})

We get the select element as we did before.

Then we get the options from the event.target.options .

And we can access the index of the selected choice with the event.target.selectedIndex .

Then we can get the value of the value property with the value property.

And text gets the text content of the selected item in the option element.

Conclusion

We can get the selected option element from the select element with the value property, which has the value of the value attribute of the selected option element.

We can also get all the options with the options property.

selectedIndex gets the index of the selected option element.

Categories
JavaScript Answers

How to Check if a JavaScript Variable Exists?

JavaScript variables may be declared without setting a value for them.

They can also be set to undefined .

In this article, we’ll look at how to check if a JavaScript variable is initialized or whether it’s undefined .

The typeof Operator

One way to check if a JavaScript variable exists is to use the typeof operator.

For instance, we can write:

let x;  
console.log(typeof x === 'undefined')

If x isn’t initialized, then it’s the same as setting it to undefined .

So typeof x returns 'undefined' .

Therefore, the console.log returns true .

Falsy Check

We can also check if a variable is falsy to see if it’s a falsy value, which includes undefined , null , '' (empty string), 0, NaN , or false .

Truthy value is any value other than those values.

For instance, we can write:

let x;  
console.log(Boolean(x))

Then console log logs false since x is uninitialized, so it’s undefined .

And since Boolean converts any falsy value to false , that’s what we get.

Equivalently, we can use !! to do the same thing:

let x;  
console.log(!!(x))

Conclusion

We can use the typeof operator or the Boolean function to check if a variable is initialized or not.

Categories
JavaScript Answers

How to Check if a Variable is a String in JavaScript?

Checking if a variable is a string is something that we’ve to do a lot in JavaScript since JavaScript variables can store data of any type.

In this article, we’ll look at how we can check if a variable is a string in JavaScript.

The typeof Operator

The JavaScript typeof operator is useful for checking if a variable is a string.

For instance, we can write:

const booleanValue = true;
const numericalValue = 123;
const stringValue = "abc";
const stringObject = new String("abc");
console.log(typeof booleanValue)
console.log(typeof numericalValue)
console.log(typeof stringValue)
console.log(typeof stringObject)

We use the typeof operator before variables to check what they return.

The first console.log should log 'boolean' .

The 2nd console.log should log 'boolean' .

The 3rd console.log should log 'string' .

And the 4th console.log should log 'object' .

We shouldn’t use the String constructor since it doesn’t return the type we expect for a string.

Instead, we should always use string literals.

toString

We can use a string’s toString method to check if it’s a string.

For instance, we can write:

const booleanValue = true;
const numericalValue = 123;
const stringValue = "abc";
const stringObject = new String("abc");

const isString = (x) => { return Object.prototype.toString.call(x) === "[object String]" } console.log(isString(booleanValue)) console.log(isString(numericalValue)) console.log(isString(stringValue)) console.log(isString(stringObject))


We call `toString` from the `Object.prototype` with the parameter `x` and see if it returns `'[object String]'` .

If `x` is a string, then its `toString` method inherited from `Object.prototype` should return `'[object String']` .

Therefore, the first 2 console logs log `false` .

And the last 2 logs `true` .

### **Lodash**

Lodash has a `isString` method to check if a variable is a string.

For instance, we can write:

const booleanValue = true; const numericalValue = 123; const stringValue = "abc"; const stringObject = new String("abc");

console.log(_.isString(booleanValue))
console.log(_.isString(numericalValue))
console.log(_.isString(stringValue))
console.log(_.isString(stringObject))
```

It works with both string literals and string wrapper objects, so the first 2 console log log `false` .

And the last 2 log `true` .

### Conclusion

There are many ways to check whether a JavaScript variable holds a string.

One way is to use the `typeof` operator. The other to check the return result of `toString` .

Lodash also has the `isString` method to check if a variable is a string.