Cast to Array

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the castArray() function in JavaScript. The purpose of the lab is to understand how to convert a non-array value to an array with a single line of code. By the end of this lab, you will have a clear understanding of how to use the castArray() function to manipulate data structures in JavaScript.

Converting Values to Arrays in JavaScript

To convert a value into an array, use the castArray function provided below.

const castArray = (val) => (Array.isArray(val) ? val : [val]);

To use this function, pass the value you want to convert as the argument. The function will check if the value is already an array using Array.isArray(). If it is an array, the function will return it as-is. If it is not an array, the function will return the value encapsulated in an array.

Here's an example of how to use castArray:

castArray("foo"); // returns: ['foo']
castArray([1]); // returns: [1]

To start practicing coding in JavaScript, open the Terminal or SSH and type node.

Summary

Congratulations! You have completed the Cast to Array lab. You can practice more labs in LabEx to improve your skills.