Categories
JavaScript Answers

How to Detect Arrow Key Presses in JavaScript?

Sometimes we need to detect the arrow key presses in our JavaScript web apps.

In this article, we’ll look at how to detect arrow key presses in JavaScript.

Use the keyCode Property

We can listen to the keydown event and get the keyCode property from the event object.

For instance, we can write:

document.onkeydown = (e) => {  
  e = e || window.event;  
  if (e.keyCode === 38) {  
    console.log('up arrow pressed')  
  } else if (e.keyCode === 40) {  
    console.log('down arrow pressed')  
  } else if (e.keyCode === 37) {  
    console.log('left arrow pressed')  
  } else if (e.keyCode === 39) {  
    console.log('right arrow pressed')  
  }  
}

to assign the keydown event handler function to the document.onkeydown property.

This lets us listen to the keydown event on the HTML document.

Then we can get the keyCode property from the e event object to see which key is pressed.

38 is the code for the up arrow.

40 is the code for the down arrow.

37 is the code for the left arrow.

And 39 is the code for the right arrow.

Also, we can use the addEventListener method to add the keydown event listener:

document.addEventListener('keydown', (e) => {  
  e = e || window.event;  
  if (e.keyCode === 38) {  
    console.log('up arrow pressed')  
  } else if (e.keyCode === 40) {  
    console.log('down arrow pressed')  
  } else if (e.keyCode === 37) {  
    console.log('left arrow pressed')  
  } else if (e.keyCode === 39) {  
    console.log('right arrow pressed')  
  }  
})

Use the key Property

Also, we can use the key property from the event object to the key that’s pressed as a string instead of a number.

For instance, we can write:

document.onkeydown = (e) => {  
  e = e || window.event;  
  if (e.key === 'ArrowUp') {  
    console.log('up arrow pressed')  
  } else if (e.key === 'ArrowDown') {  
    console.log('down arrow pressed')  
  } else if (e.key === 'ArrowLeft') {  
    console.log('left arrow pressed')  
  } else if (e.key === 'ArrowRight') {  
    console.log('right arrow pressed')  
  }  
}

We compare the key property value against the string names for the keys.

Also, we can use addEventListener method to add the key down listener by writing:

document.addEventListener('keydown', (e) => {  
  e = e || window.event;  
  if (e.key === 'ArrowUp') {  
    console.log('up arrow pressed')  
  } else if (e.key === 'ArrowDown') {  
    console.log('down arrow pressed')  
  } else if (e.key === 'ArrowLeft') {  
    console.log('left arrow pressed')  
  } else if (e.key === 'ArrowRight') {  
    console.log('right arrow pressed')  
  }  
})

Conclusion

We can detect arrow key presses by listening to the keydown event.

And in the event listener, we can either check the key or keydown properties of the event object to see which key is pressed.

Categories
JavaScript Answers

How to Remove the Last Item from a JavaScript Array?

Removing a last item from the JavaScript array is something that we’ve to do sometimes with our code.

In this article, we’ll look at how to remove the last item from a JavaScript array.

Array.prototype.splice

We can use the JavaScript array’s splice method to remove the last item from the array.

For instance, we can write:

const array = [1, 2, 3]
array.splice(-1, 1)
console.log(array)

We call splice with -1 to remove the last item from the array.

And 1 specifies that remove one item.

Then array is [1, 2] .

Array.prototype.pop

We can call the pop method to remove the last item from the array.

It returns the item that’s been removed.

To use it, we can write:

const array = [1, 2, 3]
const popped = array.pop()
console.log(popped, array)

We call pop on array to remove the last item from array .

And we assigned the removed item to popped .

So popped is 3.

And array is [1, 2] .

Array.prototype.slice

Another array method we can use to remove the last item from an array is the slice method.

It returns an array with the start and end index.

For instance, we can write:

const array = [1, 2, 3]
const newArr = array.slice(0, -1);
console.log(newArr)

We call slice with the start and end index to return an array from the start index to the end index.

The item at the end index isn’t included, but the one in the start is included.

The number -1 means the index of the last item in the array.

Therefore, we get:

[1, 2]

as the value of newArr .

Array.prototype.filter

We can use the array filter method to return an array with items that meet the given condition.

Therefore, we can check if the item is in the last index of the array.

For instance, we can write:

const array = [1, 2, 3]
const newArr = array.filter((element, index) => index < array.length - 1);
console.log(newArr)

We pass in a callback to the filter method that returns index < array.length — 1 to return all the items with index less than array.length — 1 .

Therefore, we’ll get the same result for newArr as the previous example.

Conclusion

We can use JavaScript array methods to remove the last item from an array.

Categories
JavaScript Answers

How to Conditionally Add a Member to a JavaScript Object?

Sometimes, we want to conditionally add a member to a JavaScript object.

In this article, we’ll look at how to conditionally add a member to a JavaScript object.

Spread Operator

We can use the spread operator to spread an object into another object conditionally.

For instance, we can write:

const condition = true  
const obj = {  
  ...(condition && {  
    b: 5  
  })  
}  
console.log(obj)

We use the && operator to return the object only when condition is true .

If the object is returned then it’ll be spread into obj .

And so we get:

{b: 5}

as a result.

Instead of using the && operator, we can also use the ternary operator by writing:

const condition = true  
const obj = {  
  ...(condition ? {  
    b: 5  
  } : {})  
}  
console.log(obj)

We return an empty object when condition is false instead of null .

Object.assign

Also, we can use the Object.assign method to merge an object into another object.

For instance, we can write:

const condition = true  
const obj = Object.assign({}, condition ? {  
  b: 5  
} : null)  
console.log(obj)

We have the condition check in the 2nd argument of the Object.assign method.

We return the object only when condition is true .

Otherwise, null is returned.

Since condition is true , we have the same result for obj .

Conclusion

We can add properties to an object conditionally with the spread operator or the Object.assign method.

We can use the ternary operator or && operator to specify what to add given the condition.

Categories
JavaScript Answers

How to Get a Subset of a JavaScript Object’s Properties?

Sometimes, we may want to get a subset of JavaScript properties from an object.

In this article, we’ll look at ways to get a subset of JavaScript object’s properties to a place where we can use them.

Object Destructuring

The shortest and easiest way to get a subset of a JavaScript object’s properties is to use the object destructuring syntax.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const {
  a,
  b
} = object
const picked = {
  a,
  b
}
console.log(picked)

We have an object with properties a , b , and c .

To get the properties, we can destructure them to assign them to their own variables.

We did that with:

const {
  a,
  b
} = object

Now a is assigned to object.a .

And b is assigned to object.b .

Then we can put them into another object with:

const picked = {
  a,
  b
}

And so picked is:

{a: 1, b: 2}

We can also do destructuring in function parameters.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const pick = ({
  a,
  b
}) => ({
  a,
  b
})
const picked = pick(object);
console.log(picked)

to create a pick function that returns an object with the a and b properties destructured from the object parameter.

So when we call pick with object , we get that picked is the same as before.

Lodash

We can also use Lodash’s pick method to return an object with the given properties.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = _.pick(object, ['a', 'b']);
console.log(picked)

We call pick with the object to extract properties from.

And the array has the property name strings we want to get.

So picked is the same as the other examples.

Array.prototype.reduce

We can use the JavaScript array reduce method to get the properties from an object and put them into another object.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = ['a', 'b'].reduce((resultObj, key) => ({
  ...resultObj,
  [key]: object[key]
}), {});
console.log(picked)

We call reduce on the [‘a’, ‘b’] array which are the property name strings for the properties we want to get from object .

resultObj has the object with the picked properties.

key has the key we want to get from the array.

We return an object with resultObj spread and the key with its corresponding value appended to the end of it.

The 2nd argument of reduce is an empty object so we can spread the properties into it.

And so picked has the same result as before.

Conclusion

We can get a subset of the properties of JavaScript wit destructuring assignment, array reduce , or the Lodash pick method.

Categories
JavaScript Answers

How to Convert a Set to an Array in JavaScript?

Sometimes we use a set to create a data structure that doesn’t have duplicate elements.

But we’ve to convert them to an array so we can work with them more easily.

In this article, we’ll look at ways to convert a JavaScript set to a JavaScript array.

Array.from

The Array.from static method lets us convert any iterable object into an array.

JavaScript sets are iterable objects, so we can use them to do the conversion.

For instance, we can write:

const array = Array.from(new Set([1, 2, 3]));
console.log(array)

to convert a set to an array.

We pass in the set straight into the Array.from method to do the conversion.

Therefore, array is:

[1, 2, 3]

Spread Operator

Another way to convert a set to an array is to use the spread operator.

The spread operator lets us spread any iterable object into an array.

Therefore, we can write:

const array = [...new Set([1, 2, 3])];
console.log(array)

Therefore, we get the same result as before.

Set.prototype.forEach

A JavaScript set has a forEach method that lets us iterable through all the entries in the set.

It takes a callback that has the item we’re iterating through as the parameter and we can do anything with it in the body.

For instance, we can write:

const set = new Set([1, 2, 3])
const array = [];
set.forEach(v => array.push(v));
console.log(array)

to get the same result as before.

We call array.push to append the set item v to the array .

Set.prototype.values and Spread Operator

A JavaScript set also has the values method that returns an iterator with all the values of the set.

So we can spread the iterator into an array with the spread operator.

For example, we can write:

const set = new Set([1, 2, 3])
const array = [...set.values()]
console.log(array)

to spread the values in the iterator returned by set.values into array .

And so we get the same result as before.

for-of Loop

Since a JavaScript set is iterable, we can loop through the entries with the for-of loop.

And in the loop body, we can call push to append the set item into the array.

To do that, we write:

const set = new Set([1, 2, 3])
const array = [];
for (const v of set) {
  array.push(v)
}
console.log(array)

And we get the same result as before.

Conclusion

There’re many ways we can use to convert a set into an array.

Since JavaScript sets are iterable objects, we can use things like the spread operator, for-of loop, Array.from , etc. to do the conversion.