Initialize Array With Values

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to initialize and fill an array with specific values in JavaScript. We will use the Array() constructor and the Array.prototype.fill() method to create and populate the array. By the end of the lab, you will have a deeper understanding of how to create and manipulate arrays 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-28395{{"`Initialize Array With Values`"}} javascript/data_types -.-> lab-28395{{"`Initialize Array With Values`"}} javascript/arith_ops -.-> lab-28395{{"`Initialize Array With Values`"}} javascript/comp_ops -.-> lab-28395{{"`Initialize Array With Values`"}} end

Function to Initialize an Array with Specified Values

To start practicing coding, open the Terminal/SSH and type node.

This function initializes an array with the specified values:

  • Use the Array() constructor to create an array of the desired length.
  • Use Array.prototype.fill() to fill it with the desired values.
  • If no value is specified, it defaults to 0.
const initializeArrayWithValues = (length, value = 0) =>
  Array(length).fill(value);

Example usage:

initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]

Summary

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

Other JavaScript Tutorials you may like