Skip to main content

Grouping properties together

In the previous lesson we have seen how to store information in variables. We continued our journey in calculating the discounted prices of snacks of questionable nutrition score and ended up with the following code:

const originalPriceOfNachos = 50;
const originalPriceOfSoda = 20;
const discountOfNachos = 10;
const discountOfSoda = 20;

function getDiscountedPrice(price, discount) {
  return price * (100 - discount) / 100;
}

const priceOfNachos = getDiscountedPrice(originalPriceOfNachos, discountOfNachos);
const priceOfSoda = getDiscountedPrice(originalPriceOfSoda, discountOfSoda);

console.log('The price for the nachos is', priceOfNachos);
console.log('The price for the soda is', priceOfSoda);

console.log(
  'The total for the nachos and the soda is',
  priceOfNachos + priceOfSoda
);
Toggle Console Output
  • 'The price for the nachos is'45
  • 'The price for the soda is'16
  • 'The total for the nachos and the soda is'61

This would probably give the itch to experienced programmers. But we are not there yet and we absolutely have a lot of to cover in our journey.

The problem starts at the very beginning, where we declare the four variables:

const originalPriceOfNachos = 100;
const originalPriceOfSoda = 30;
const discountOfNachos = 20;
const discountOfSoda = 50;

Imagine adding a third product:

const originalPriceOfNachos = 100;
const originalPriceOfSoda = 30;
const originalPriceOfWater = 10;
const discountOfNachos = 20;
const discountOfSoda = 50;
const discountOfWater = 10;

Please stop! What about the following:

const nachos = {
  price: 100,
  discount: 20
};

const soda = {
  price: 30,
  discount: 50
};

function getDiscountedPrice(price, discount) {
  return price * (100 - discount) / 100;
}

const priceOfNachos = getDiscountedPrice(nachos.price, nachos.discount);
const priceOfSoda = getDiscountedPrice(soda.price, soda.discount);

console.log('The price for the nachos is', priceOfNachos);
console.log('The price for the soda is', priceOfSoda);

console.log(
  'The total for the nachos and the soda is',
  priceOfNachos + priceOfSoda
);
Toggle Console Output
  • 'The price for the nachos is'80
  • 'The price for the soda is'15
  • 'The total for the nachos and the soda is'95

[insert Drake meme here] Now we are talking! The output of the program stayed the same again, but we introduced a new syntax that helped us group information together.

Objects in JavaScript

We just went from storing four numbers in four different variables, i.e:

const originalPriceOfNachos = 100;
const originalPriceOfSoda = 30;
const discountOfNachos = 20;
const discountOfSoda = 50;

to just two variables, nachos and soda:

const nachos = {
price: 100,
discount: 20
};

const soda = {
price: 30,
discount: 50
};

These two are your first two JavaScript objects. An object is a collection of related data and/or functionality. For now we'll deal with data only.

Good to know
  • price and discount are the object keys or properties;
  • we'll refer to them as key or properties in an interchangeable manner;
  • each object key holds a value, in this case the numbers coming after the colon (:);
  • the list of key / value pairs should be comma separated;
  • an object can have as many key / value pairs as you want;
  • you can access the value for a given key with the dot notation - e.g. nachos.price, nachos.discount;
  • in order to use the dot notation, you have to know the name of the variable containing the object, and the name of the key you are interested in.

Reading object values

Object represent composite pieces of information. Let's have a break from our sodas and practice this new syntax a little.

const user = {
  firstName: 'Jane',
  lastName: 'Doe',
  email: 'jane@doe.com',
  age: 35
};

console.log('My name is', user.firstName, user.lastName);
console.log('I am', user.age, 'years old');
console.log('Feel free to write me at:', user.email);
Toggle Console Output
  • 'My name is Jane Doe'
  • 'I am 35 years old'
  • 'Feel free to write me at: jane@doe.com'

We created an object with four properties (firstName, lastName, email and age) and stored it into a variable called user.

Right after that we logged some information from the user with the aid of the dot notation,
i.e. {name of the object variable}.{name of the key we need}.

Note

Object theory in JavaScript goes way beyond this. But key/value definition and dot notation is their main purpose and what you should get used to from the very beginning.

Yes and no: the boolean type

We have stored strings and numbers in our objects so far, that works great for quantities and descriptive properties. What about saving if a user has verified account? One could depict this in a string, but there are more practical ways of handling this.

const user = {
  firstName: 'Jane',
  lastName: 'Doe',
  email: 'jane@doe.com',
  age: 35,
  isVerified: true
};

console.log('My name is', user.firstName, user.lastName);
console.log('I am', user.age, 'years old');
console.log('Feel free to write me at:', user.email);
if (user.isVerified) {
  console.log('My account is verified!');
}
Toggle Console Output
  • 'My name is Jane Doe'
  • 'I am 35 years old'
  • 'Feel free to write me at: jane@doe.com'
  • 'My account is verified!'

We briefly encountered the true and false values when we logged some number comparisons expressions:

console.log('2 > 3', 2 > 3);
console.log('2 < 3', 2 < 3);
Toggle Console Output
  • '2 > 3'false
  • '2 < 3'true

true and false are the only two possible values allowed by the boolean data type. They describe something that can have just two possible states, for example:

  • A user is either verified or not;
  • The sun is either shining or it is hiding behind clouds;
  • A person can be of major age or not in a specific jurisdiction;
  • An integer number is either even or odd.
Note

What is a data type?

In programming a data type is a collection or grouping of data values, usually specified by a set of possible values and a set of allowed operations on these values.

We already encountered the string type, made of the set of all possible words (regardless of them being meaningful or not!), and the number type, the set of all numbers (natural, integer, decimal). We have also seen some operations defined on the numerical space (sum, product, division).

We'll discuss thing more formally at the end of this section.

We fed the isVerified property of the user object as the condition of an if statement. Boolean values and conditional are really meant to work together!

See also that there is no else block following the if block. If we don't want to log anything in case the user is not verified, we don't have to provide an alternative behavior of our program.

In case we wanted though, we could do it:

const user = {
  firstName: 'Jane',
  lastName: 'Doe',
  email: 'jane@doe.com',
  age: 35,
  isVerified: false
};

console.log('My name is', user.firstName, user.lastName);
console.log('I am', user.age, 'years old');
console.log('Feel free to write me at:', user.email);
if (user.isVerified) {
  console.log('My account is verified!');
} else {
  console.log('Chances are that I am not the real', user.firstName, user.lastName);
}
Toggle Console Output
  • 'My name is Jane Doe'
  • 'I am 35 years old'
  • 'Feel free to write me at: jane@doe.com'
  • 'Chances are that I am not the real Jane Doe'

See how now just the else branch is executed, since user.isVerified is false.

Flipping the question

We are checking if the user is verified. What if we want to check if the user is not verified?

const user = {
  firstName: 'Jane',
  lastName: 'Doe',
  email: 'jane@doe.com',
  age: 35,
  isVerified: false
};

console.log('My name is', user.firstName, user.lastName);
console.log('I am', user.age, 'years old');
console.log('Feel free to write me at:', user.email);
if (!user.isVerified) {
  console.log('My account is not verified!');
}
Toggle Console Output
  • 'My name is Jane Doe'
  • 'I am 35 years old'
  • 'Feel free to write me at: jane@doe.com'
  • 'My account is not verified!'

The conditional expression changed to if (!user.isVerified). We prepended an exclamation mark to user.isVerified. The ! is called the negation operator and it is read "not". It takes whatever follows it, and flips its value to false if it was true and viceversa.

The negation operator works also with non boolean values. We'll see how when we'll cover conditional logic in a more formal way.

Note

Boolean values can appear not just as values for object keys, but as function call arguments and variable values as well:

function getClothes(isRaining) {
  if (isRaining) {
    return 'jacket';
  } else {
    return 't-shirt'
  }
}

const isRainingToday = true;
const isRainingTomorrow = false;

console.log("Given the weather of today, I'll wear a", getClothes(isRainingToday));
console.log("Given the weather of tomorrow, I'll wear a", getClothes(isRainingTomorrow));
Toggle Console Output
  • "Given the weather of todayI'll wear a jacket"
  • "Given the weather of tomorrowI'll wear a t-shirt"

Conclusion

WIP