Objects, Arrays, and Functions with JavaScript

In this article, we’ll focus on three fundamental programming concepts with JavaScript - objects, arrays, and functions.

Objects

Objects – also known as “dictionaries” – are a way to store data. They consist of different, or the same, data types, such as variables containing strings, numbers, arrays, and functions (more on functions later in the article), that are called properties (i.e. they belong to the object, hence “property”) and methods when they’re contained within an object.

To create an object, it’s as simple as defining a variable: const pet = {}; It’s essentially the same thing as declaring a regular variable, only that we set it equal to the curly braces, and that’s our object. Our object is empty, so let’s add some properties! Within our object, we declare the properties, and everything else which will ‘belong’ to that object:

const pet = {
  name: "Punkie",
  type: "Cat",
  age: 5,
  friendly: true,
};
console.log(pet); // {name: "Punkie", type: "Cat", age: 5, friendly: true}

Pretty simple, no? We have multiple properties in our object, of different types of value. We have strings, a number, and a boolean value of true. If we wanted to access a specific property, we can do something like:

console.log(pet.name); // Punkie
console.log(pet.age); // 5

That is called dot notation, recognized by the ‘.’ above. We can also access our object’s properties with bracket notation:

console.log(pet["name"]); // Punkie
console.log(pet["age"]); // 5

We can also add more properties to our object with dot notation, or bracket notation:

// Adding properties with dot notation
pet.color = "Grey";
console.log(pet); // {name: "Punkie", type: "Cat", age: 5, friendly: true, color: "Grey"}
// Adding properties with bracket notation:
pet["color"] = "Grey";
console.log(pet); // {name: "Punkie", type: "Cat", age: 5, friendly: true, color: "Grey"}

We can change the value of properties:

pet.age = 6;

And we can delete properties:

delete pet.age;
Methods I

Methods are functions which are contained in an object. We can jump right into an example:

const pet = {
  name: "Punkie",
  type: "Cat",
  age: 5,
  friendly: true
  speak: function() {
    alert(this.name); // Punkie
  }
}
pet.speak() // Punkie

If it looks confusing, don’t worry, we’ll return to this later.

Arrays

Arrays are similar to objects, but we don’t have key-value pairs. They store data that we could use at a later time.

const array = [‘Pizza’, 3, 4, true];

The position of the elements in an array are called indexes. When we count the number of elements in the array, we start counting at index 0. So, if we were to ask our interpreter how many elements are in our above array: array.length; we’d get 4, as we’d expect. However, if you were to try accessing the array element ‘Pizza’, you would need to know that it is in index, or position 0. Counting our above array, we’d start at 0(‘Pizza’), 1(3), 2(4), and 3(true).

Accessing Array Properties

We need a way to actually use the data stored in our array. In order to use them, we need to be able to access them. It’s as simple as accessing our object properties! Focusing on the array above, let’s log pizza to the console:

array[0]; // 'Pizza'

Similar to changing our object’s values, we can do the same here with our array.

array[0] = "Hamburger";
console.log(array); // 'Hamburger', 3, 4, true;

And there we have the basics of objects and arrays. They’re not only useful in JavaScript, but virtually every programming language makes use of arrays and objects, as with a lot of material within this blog.

More on arrays

If you’d like to learn more about arrays, we’ve written an article going over some of the methods available on them, here.

Functions with JavaScript

Functions take in some data, do something with it, and return a value. You might remember functions from mathematics class. They’re not entirely different when we write them in our code.

Consider the square function:

f(x) = x^2

We’ll write that below in JavaScript.

Defining a function in JavaScript is pretty simple. We use the word “function”, followed by the function’s name, sort of like defining a variable, only that, with functions, we pass them arguments, or parameters, which are contained within parenthesis.

function foo(a, b) {
  return a * b;
}
foo(5, 5); // 25

In the function above, we defined a function foo, which takes in two arguments, a and b. In our function’s body(between the curly braces), we’re giving instructions to the function, and that is to simply return a times b. As you can see, when we pass some values to our function foo(5, 5), we’re going to get what we’d expect: 25. How does this work?

Well, imagine that we declared three variables: x, a, and b. x is a function, while a and b are undefined*. In lesson three, we learned that undefined simply means that a variable hasn’t yet received any data. When we pass in 5, 5, a and b become those numbers: return 5 * 5; Neat, right?

As for our squared function, we’d simply pass the function a single argument, like so:

function f(x) {
  return x * x;
}

f(5); // 25

Here, we’re simply returning a number x and multiplying it by itself. That’s not the only way to declare functions. We can also declare a variable, and assign it to a function, like so:

const x = function (a, b) {
  return a * b;
};

x(5, 5); // 25

We don’t have to actually pass anything to our function, we can leave the arguments empty, like so:

function greet() {
  alert("Hello");
}
greet(); // Hello

This function can be invoked without any user input by the use of a button. Say we have a button on a website, and we want to send that alert message when the button isclicked. First, we’d define our function as above, and then within the button, we’d add something called an “onclick” event, which waits for a user to click the button. Once clicked, our function will be called, alerting the “Hello” message.

Note: This isn’t how things are. If we were to try accessing a or b, we’d get a reference error. a and b are unique to that function, and we don’t have access to them outside of it. They’re called “local” variables. Global variables would be stored outside of a function block.

Methods II

We’ve mentioned methods briefly above. Methods are functions contained within an object.

const person = {
  name: "Sarah",
  age: 24,
  greet: function () {
    console.log(`Hello, ${this.name}!`);
  },
};
person.greet(); // Hello, Sarah!

We’ve declared a function a bit differently above than our previous two examples. Here, the function is a property of the object. We can call the function as per above with person.greet(), which logs the statement Hello, Sarah!

Using Functions

If you feel like experimenting with functions, you can try entering the code below in your console:

function greet() {
  const name = prompt("What is your name?");
  alert(`Hello, ${name}!`);
}

Above, we’ve declared a variable name and set it equal to a built-in function prompt(), which takes in a value (in our case, name), and stores it in the name variable. Below that line, we call another built-in function alert(), pass it the message “Hello”, and our name variable. If you’ve ran the code above, it wouldn’t work, it’s missing something, and that is our call to the function. We need to invoke our function. It’s simple, we just add greet() below the block of code* we already have.

function greet() {
  const name = prompt("What is your name?");
  alert(`Hello, ${name}!`);
}
greet(); // calls the function and runs the code.

*NOTE: A block of code, in this case, is just the code between our curly braces.

Conclusion and Further Reading

We didn’t really scratch the entire surface of these subjects. There’s so much more to explore, but hopefully, we’ve given you some fundamental knowledge about objects, arrays, and functions in JavaScript. If you’re thirsty for more, you can explore the MDN Documentation.

Can you make a small text-based game with the use of the material in this article?




comments powered by Disqus

Related Posts

The Great JavaScript Debate: To Semicolon or Not?

Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.

Read more

Hacktoberfest 2024: Get a Free JavaScript Today Sticker

October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.

Read more

Creating a Real Time Chat Application with React, Node, and TailwindCSS

In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.

Read more