Different Ways to Create JavaScript Arrays and Objects

2020-09-25 18:00:40 | #programming #javascript | Part 4 of 5

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

Now that we know how to declare values, we'll want to learn about how to work with collections of values and larger data sets. JavaScript provides an array (pun intended) of tools to order and structure our data, so we'll want to take advantage of them.

With arrays and objects, we begin to tap into the data-processing potential computers offer. At the end of the day, computer programs are a series of inputs and outputs, and understanding data is the key to harnessing this potential.

JavaScript Arrays

JavaScript arrays are useful when we need to store rows or records of data into collections. Because arrays can be indexed, ordered, and modified, our data is much easier to organize and access. Picture an array as a bookshelf, with books lined up from left to right, each at numbered position in the array. The first book, furthest to the left, is at position 0. The second book is at position 1, and so on. Having this structure in place, we can write programs to iterate through each item in the array until it locates what we're searching for.

Manually Creating a JavaScript Array

To create a JavaScript array, manually, we can write out a comma-separated list within square brackets, and store this list into a variable that we can reference, as needed. This is known as creating an array with the assignment operator (=).

var numbers = [2, 8, 4, 34, 9, 229];
console.log(numbers[0]);
console.log(numbers[3]);
console.log(numbers[numbers.length - 1]);

Now we have a numbers array where we can access elements by index (0,1,2....). We can even fetch the last element of the array with numbers.length - 1. We have to substract 1 from the total length of the array because the index begins at position 0 not 1. So while the total length of our numbers array is 6, the last element is at position 5. Fetching out of bounds will return undefined.

Did you know that strings are also arrays, and that you can fetch each character based on its position in the array?

var color = 'purple'; 
console.log(color[0]);

Dynamically Creating a Javascript Array

We can also create arrays, dynamically, by instantiating with the Array class. The following syntax instantiates 3 different arrays with 5 empty elements. We can then assign values, afterwards.

var arr1 = Array(5);
var arr2 = new Array(5);
var arr3 = Array.from({length: 5});
  
arr1[0] = 8;
arr1[1] = 10;
console.log(arr1[0]);

We can also clone arrays with the spread operator.

var numbers = [2, 8, 4, 34, 9, 229];
numbers2 = [...numbers];
console.log(numbers2);

We can add elements to an array with push(). This appends new values to the end of the array.

var numbers = [2, 8, 4, 34, 9, 229];
numbers.push(6);
numbers.push(19);
numbers.push(0);
console.log(numbers);

Or to the beginning of the array with unshift().

var numbers = [2, 8, 4, 34, 9, 229];
numbers.unshift(6);
numbers.unshift(19);
numbers.unshift(0);
console.log(numbers);

And remove elements from an array:

var numbers = [2, 8, 4, 34, 9, 229];

// Removes the first element
numbers.shift();
console.log(numbers);

// Removes the last element
numbers.pop();
console.log(numbers);

// Removes element by index position and how many to delete
numbers.splice(2, 1);
console.log(numbers);

Loops are also useful for dynamic array creation, but that will be covered in the next tutorial.

JavaScript Objects

JavaScript objects are also useful for storing data, but unlike an array which stores an ordered, indexed list of values/records, an object is meant to store one record or entity, and all the properties that go along with it.

Manually Creating JavaScript Objects

JavaScript objects have a different data structure than arrays. Rather than a list, surrounded by square brackets, we have a list of key value pairs surrounded by curly braces. We're free to customize the keys/properties and values to store whatever information we want to store about an entity.

var book = {
  title: 'Nineteen Eighty-Four',
  author: 'George Orwell',
  country: 'United Kingdom',
  published: '1949-06-08 00:00:00',
  pages: 328
}

Because an array is to a bookshelf, what an object is to a book, we can do the following:

var bookshelf = [{
  title: 'Nineteen Eighty-Four',
  author: 'George Orwell',
  country: 'United Kingdom',
  published: '1949-06-08 00:00:00',
  pages: 328
}, {
  title: 'Do Androids Dream of Electric Sheep?',
  author: 'Phillip K. Dick',
  country: 'United States',
  published: '1968-00-00 00:00:00',
  pages: 210
}];

We can also create an object, first, and then push it into the array, afterwards.

var bookshelf = [];

var book1 = {
  title: 'Nineteen Eighty-Four',
  author: 'George Orwell',
  country: 'United Kingdom',
  published: '1949-06-08 00:00:00',
  pages: 328
};

var book2 = {
  title: 'Do Androids Dream of Electric Sheep?',
  author: 'Phillip K. Dick',
  country: 'United States',
  published: '1968-00-00 00:00:00',
  pages: 210
};
  
bookshelf.push(book1);
bookshelf.push(book2);
console.log(bookshelf[1]);

Just like arrays, JavaScript objects come with their own useful functions. Here are a few that are related to object modification:

var record = {
  firstName: 'Hideki',
  lastName: 'Nakajima',
  dob: '1990-09-23',
  city: 'Tokyo'
}
  
// Delete an object key/property
delete record.dob;

// Add an object key/property
record.country = 'Japan';
  
// Add an object key/property dynamically
record['occupation'] = 'Engineer';

Javascript JSON

JSON stands for JavaScript Object Notation, and is simply a string representation of a JavaScript object, allowing us to easily transmit data between different types of servers and rest APIs. By conforming to the JSON standard, a service written with Python can receive and transmit a json payload from and to a C++ service. Each service can speak their own language, locally, but speak JSON when they need to transmit data across the internet.

var record = {
  firstName: 'Hideki',
  lastName: 'Nakajima',
  dob: '1990-09-23',
  city: 'Tokyo'
}

// Convert object to JSON
var payload = JSON.stringify(record);
  
// Convert JSON to object
JSON.parse(payload);

Conclusion

I hope you liked this tutorial, and learned a lot about structuring and organizing data. Future articles will cover how to process data, with speed and efficiency, so check back for the next chapter in this series.

If you're interested in making interactives and games, we recommend you take our Learn JavaScript While Building a Game Framework course, which teaches you JavaScript and ES6 while you build an HTML5 Canvas, physics-based framework, from scratch. You'll also learn drag and drop, mouse following, velocity, acceleration, friction, and many other useful functionality you can build interactives and games with. In addition, it compiles into a browser-compatible ES2015 build. Start making canvas applications, today.

Want To See More Exercises?

View Exercises View Courses

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Tell Us About Your Project









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

Contact