Cast to Array

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28190{{"`Cast to Array`"}} javascript/data_types -.-> lab-28190{{"`Cast to Array`"}} javascript/arith_ops -.-> lab-28190{{"`Cast to Array`"}} javascript/comp_ops -.-> lab-28190{{"`Cast to Array`"}} end

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.

Other JavaScript Tutorials you may like