Working with Simple Data

What is Data?

The word "data" has different meanings in different contexts. In the programming world, "data" is a very broad concept that refers to all of the information in an application or website. Usually data is changeable, but this is not always the case.

In JavaScript there are a few types of data we have available to work with.

Here are some of the most basics types of data we will start with:

  1. Strings - Text

  2. Numbers - Numbers

  3. Booleans - True / false

There are other types of data you will learn about over time, but these are the most common and the ones we will learn about first.

Let's take a look at how to write an example of each with JavaScript.

// This is a string
const name = `Zac`;
// This is a number
const age = 100;
// This is a boolean
const loggedIn = false;

These examples are written in plain English and so can be understood even if you have no programming experience. However, each type of data does have formatting rules:

  1. Strings must be wrapped in quotations. Here we are using the backtick character (`) instead of single (') or double quotations (").

  2. Numbers should have no quotations around them. This tells JavaScript we have a number and not a string of text.

  3. Booleans normally have a value of either true or false. Later in the book, we will also learn that we can use 1 for true and 0 for false.

Data We Change and Data We DON'T Change

When we work with data, it's important to use unique names to store the data.

This unique name is called a variable:

// A variable "name" with a value of a string "Zac"
const name = `Zac`

There are two types of variables in JavaScript: variables whose data may change, and variables whose data is fixed.

If we know that data is not going to change, we name the variable using const for constant. If we have a piece of data that may need to change then we define it using let. The name letmeans we are "letting" the variable have a certain value for now, but it may change later.

// The value of siteName should not be changed
const siteName = `JS Bootcamp`;
// The value of loggedIn may change in the future
let loggedIn = false;

If you try to change value of a const variable, you will cause an error. As you become more experienced with JavaScript, you will learn some of exceptions to working with const. However, as a beginner, I recommend you only use a const when you don't need to change the value of a variable.

So, here is the basic rule:

  1. Use const by default.

  2. If you need to change the value, switch to let.

Logging Data in the Browser Console

Let's get started and write some Javascript!

As JavaScript beginners, one of the first things we learn use the console:

The console is a feature of web browsers that lets us log information we want from our JavaScript. The console gives you the ability to write, manage, and monitor JavaScript. It is also where errors will appear.

The code below is our first taste of writing JavaScript. This code shows how to log a variable out to the console:

// Create a simple variable to log to console.
const testing = `Some text to display`;
// The value of loggedIn may change in the future
console.log( testing );

Let's try logging out a variable. Follow these instructions:

  1. Copy and paste the code block below into a file named test.html

  2. Open test.html in your browser.

  3. If you're using Firefox, open the "Tools" menu and enable the "Web Inspector" feature. If you're using Chrome, go to "View" then "Developer" and open the "Developer Tools" feature.

  4. Look for the Console tab.

  5. You should see the value Some text to display logged out to the console.

<script>
// Create a simple variable to log to console.
const testing = `Some text to display`;
// The value of loggedIn may change in the future
console.log( testing );
</script>

If everything worked correctly, your Console tab will look like the image below:

It is important to get comfortable using this console.log() feature of JavaSscript. This is how we will test and display all our data when we are first starting off with JavaScript.

Other Ways to Display Data with Alert and Prompt

In addition to console.log() there are other ways we can display data with JavaScript, including these:

  1. alert()

  2. prompt()

The alert() approach will take data and display it in a browser alert window.

const alertMsg = `Alert test`;
// Displays the message in an alert box
alert( alertMsg );

Add this code to your test.html. Make sure this new code is placed just before the final </script> tag.

When you refresh the test.html page in your browser, you will see the effect shown below.

The prompt() approach will take data and display it in a browser alert window.

  • Section on alerting data

  • Section on confirming data

  • Section on getting data (via alert type box?)

Modifying Data

One of the coolest things about data types in JavaScript is that they come with built in options for modifying the data.

For example, we can take a string and search to see if it contains certain words.

Add this code to the bottom of your test.html file, just above the closing</script> tag.

// A basic string
const name = `Zac Gordon`
// Returns true if "name" contains "Zac" and false if it does not
const isZac = name.includes(`Zac`)
console.log( isZac )

When you look in the Console tab, you will see the word "true":

Let's look at another example: we could take a number and convert it to have a fixed number of decimal points. Add this code to the bottom of your test.html file, just above the closing</script> tag.

// Start with a number
const price = 99;
// Will give us "99.00"
const formattedPrice = price.toFixed(2)
console.log( formattedPrice )

When you look in the Console tab, you will see the number 99 is formatted to two decimal places:

There aren't actually many ways we can modify booleans, but one interesting thing we can do is convert a boolean data type to a string data type. In fact, many of the data types have the ability to convert from one type to the other. Add this code to the bottom of your test.html file, just above the closing</script> tag.

// Start with a boolean
const loggedIn = false
// Logs the boolean value of false
console.log( loggedIn )
// Logs a string with the value of "false"
console.log( loggedIn.toString() )

When you look in the Console tab, you will see that false is logged twice:

Later in the book, we'll show you some practical uses for this feature when we compare one data type to another with conditional statements.

Modifying Strings

Before we move forward, let's dig into some of the helpful ways we can manipulate strings.

Using Variables in Strings

One of the useful things we can do when we wrap our strings inside of backticks is use variables inside of our strings. This is only possible when we use backticks rather than single or double quotes, which also work when creating strings. Add this code to the bottom of your test.html file, just above the closing</script> tag.

// Create some variables
const firstName = `Zac`;
const lastName = `Gordon`;
// Use variables inside of a string
const welcomeMessage = `Hello ${firstName} ${lastName}! Welcome to the site!`;
// Logs out "Hello Zac Gordon! Welcome to the site!"
console.log( welcomeMessage );

When you refresh your test.html page, the image below shows what you'll see. This is something super handy, you will likely use a lot.

Searching Within Strings

There are some handy ways we can search within strings to find out information about them. In this next example, we'll see seven different ways to examine this phrase, "The Long Walk in the Woods".

This section of code is almost 40 lines long, so you may want to download it from INSERT-GITHUB-LINK-HERE

Because this code is long, let's start a new file. Add this code to a new file called modify.html. Don't forget to include the opening <script> tag and the closing </script> tag.

// Create a string for us to experiment with
const title = `The Long Walk in the Woods`;
// Gives us 26 - the total number of characters in string
console.log(title.length);
// Gets first character and the third character
// title.length is NOT zero indexed
// So we must subtract 1 to get the last character
const firstChar = title.charAt(0);
const thirdChar = title.charAt(2);
const lastChart = title.charAt(title.length - 1);
console.log(firstChar, thirdChar, lastChart);
// Returns true or false based on
// If the string starts or ends with
// Certain characters
// Will return true then false
const startsWithH = title.startsWith("T");
const endsWithPeriod = title.endsWith(".");
console.log(startsWithH, endsWithPeriod);
// Check if string contains "Woods"
// Will return true
const includesWoods = title.includes("Woods");
console.log(includesWoods);
// Check to see the first position a character appears
// Remember, it is zero indexed
const positionOfL = title.indexOf("L");
console.log(positionOfL);
// Converts a string to ALL CAPS
const titleUpperCase = title.toUpperCase();
console.log(titleUpperCase);
// Notice this loads out title unchanged!
console.log(title);

This next image shows what you'll see in the Console tab when you load modify.html in your browser. You will see the results from the seven different ways you examined the string:

One key thing to note is about this code is "zero indexing".

When we get the order of where characters appear, the first character starts with 0 instead of 1. This is called "zero indexing" and is a little confusing at first, but common in JavaScript.

When we call title.length it will give us a value of 26. However, due to zero indexing, to get the last character in a string, we need to pass 25, not 26. This is why we use title.length - 1 to get the last character in the string.

Also, when you use the indexOf() option, the value you get back is zero indexed. The empty space between "The" and "Long" is counted as a character.

All of these manipulations do not change the value of the original indexOf()string itself. To actually change the value of title we have to do the string manipulation and then must also save the new value as a new variable. In the examples above, we save new variables such as titleToUpperCase and positionOfL.

Changing Sections of Strings and Breaking Them Apart

At some point when working with strings you will want to break a string apart into smaller pieces. You may only want a certain part of a string or you might want to modify that string and then put it back together differently.

Here are some examples of ways we can break strings apart:

  • Replace a group of characters inside the string.

  • Take an excerpt from the string.

  • Split the string in sections.

Add this code to the bottom of your modify.html file, just above the closing</script> tag.

// Create a string for us to experiment with
const title = `The Long Walk in the Woods`;
// Replaces a grouping of characters in a string
// Logs "The Long Walk in the Park"
const parkTitle = title.replace("Woods", "Park");
console.log(parkTitle);
// Gets an excerpt based on character positions
// Logs "The" and "the Woods"
const slicedTitle = title.slice(0, 4);
const slicedAtEndTitle = title.slice(title.length - 9);
console.log(slicedTitle, slicedAtEndTitle);
// Splits a string into an Array (another data type)
// Splits based on any spaces " "
// Logs ["The", "Long", "Walk", "in", "the", "Woods"]
const wordsInTitle = title.split(" ");
console.log(wordsInTitle);
// Notice that title is still unchanged!
// Logs "The Long Walk in the Woods"
console.log(title);

This is what you should see when you refresh your modify.html file. There are three new results in the image, plus the very last line is confirmation that the original data is unchanged.

Here are some key things to note about these manipulations:

  • We can replace parts of strings with .replace(). In this example, we replaced "Woods" with "Park".

  • We can slice up strings based on character indexes, or starting and end points. Notice what happens if we leave off the endpoint as in the second slice() example - it automatically make the slice go all the way to the end of the string.

Combining Strings Together

Another common task is to combine strings together.

The simplest way to do this is with the plus sign (+). Add this code to the bottom of your modify.html file, just above the closing</script> tag.

const first = `Zac`;
const last = `Gordon`;
const full = first + last;
const fullWithSpaces = first + " " + last;
// Logs out "ZacGordon" and "Zac Gordon"
console.log( full, fullWithSpaces );

Refresh your modify.html file and you'll see that these two strings are combined:

By default, there will be no spaces between your strings. If you want to have spaces between your strings, you will need to combine the first string, plus an empty space, plus the other string.

We also have access to a handler helper called .concat() . This will accomplish the same thing as the code we just saw, only in a different way. Look at the code you added in the previous exercise and update the constants with this new code:

const full = first.concat( last );
const fullWithSpaces = first.concat( " ", last );

Refresh your modify.html file and you'll see that these two strings are combined, exactly as shown in the previous image.

As you will learn in programming, there are often several ways to accomplish the same thing. That is what we see here. At this point don't worry too much about when to use one approach versus the other - we just want to learn that different approaches are possible.

This next example shows that it is possible to build up a string during several steps:

// Create a string that will be changed using "let"
let message = "Hello,";
// Add to that string using "+="
message += " how are you?";
message += " Would you like to add anything?"
// Logs out "Hello, how are you? Would you like to add anything?"
console.log( message );

Refresh your modify.html file and you'll see this output:

Being able to manipulate strings is really useful. Hopefully the methods you've seen so far give you an idea of how you can work with strings in JavaScript.

Working with Numbers

When it comes to working with numbers, there are two things we want to learn:

  • How to format numbers

  • How to do math

Depending on what you build, you may have a lot of numbers in your code. These following techniques should help you get started doing more with numbers.

Add this code to a new file called numbers.html. Don't forget to include the opening <script> tag and the closing </script> tag.

Formatting Numbers

We looked a little at formatting numbers earlier, but here is a basic example again:

const num = 10;
const numAsPrice = num.toFixed(2);
// Logs out 10.00
console.log( numAsPrice );

When you load numbers.html in your console, this image shows what you will see:

Doing Basic Calculations

Earlier you saw that Javascript uses easy-to-read language so that you can understand what's going on, even if you're not a programmer. The same is true for math calculations. Add this code to your numbers.html file:

const a = 4;
const b = 3;
let c = "";
// Add
c = a + b;
console.log("a + b = " + c);
// Subtract
c = a - b;
console.log("a - b = " + c);

Refresh your browser and this image shows what you'll see in the console:

Here are three more examples for you to try. These should be added after the last code, but before the closing </script> tag.

// Multiply
c = a * b;
console.log("a * b = " + c);
// Divide
c = a / b;
console.log("a / b = " + c);
// Get remainder of division
c = a % b;
console.log("a % b = " + c);

Refresh your browser and this image shows what you'll see in the console:

Before we move on, it's worth noting that if you combine calculations together, they won't always run from left-to-right. Normal mathematics has a feature called "order of operations". This means that multiplication calculations are done before addition. Add this code to your numbers.html file before the closing </script> tag..

// This will return 20, not 60
const value = 10 + 2 * 5;
console.log(value);

If you wanted to return "60" from this data, you will need to add parentheses around the calculation you want to run first. Update the code you have just written so that it reads like this:

// This will return 60, not 20
const value = (10 + 2) * 5;
console.log(value);

Refresh the numbers.html file in your browser and this is what you'll see:

Converting Strings to Numbers

Occasionally we will get something in JavaScript that we think is a number, but is really a string. This is common when getting values from the page itself or from APIs.

If we try to do math with a string and a number, it will convert the number to a string and concatenate the results. Add this code to your numbers.html file before the closing </script> tag.

const numeral = 1;
const string = "2";
// This will log "12"
const result = numeral + string;
console.log(result);

Refresh the numbers.html file in your browser and this is what you'll see:

In order to get what we really want, we have to convert our string to a number first. Then our math operations will occur.

There are several ways to do this, but one of the simplest is using the Number() function. Update the code you just wrote using this new syntax:

const numeral = 1;
const string = "2";
// This will log 3
const result = numeral + Number(string);
console.log(result);

Refresh the numbers.html file in your browser and you will now see the correct result:

The Math Data Type

We have not talked about the Math data type yet in JavaScript, but it can be quite helpful when working with numbers. Let's show you a few of the things Math can do, starting with rounding operations. Add this code to your numbers.html file before the closing </script> tag.

// Set a number to work with
const pi = 3.14;
// Rounding operations
// 3
const rounded = Math.round(pi);
// 4
const roundedUp = Math.ceil(pi);
// 3
const roundedDown = Math.floor(pi);
console.log(
rounded,
roundedUp,
roundedDown,
);

This is the how the console log will now appear for your numbers.html file:

Let's try that once more with squaring operations. Add these new lines after the rounding operations:

// Squaring operations
// 9.7344
const squared = Math.pow(pi, 2);
// 1.7663521732655694
const squareRoot = Math.sqrt(pi);

You will also need to update the console output:

console.log(
rounded,
roundedUp,
roundedDown,
squared,
squareRoot
);

This is the how the console log will now appear for your numbers.html file:

As you dig in more to JavaScript you will likely come across more helpful Math operations like Math.min(), Math.max(), Math.sin(), Math.cos(), Math.tan().

Some Data is True or False

"Booleans" are a data type in JavaScript that can either have the value of true or false.

let loggedIn = true

In the example above, we can see that the user is logged in to the site.

Although this type of data is quite simple on its own, it allows us to do some powerful programming when we use it along with if else statements like this. Add this folliwjng code to a new file called boolean.html. Don't forget to include the opening <script> tag and the closing </script> tag.

let loggedIn = false
if ( loggedIn == false ) {
// Use it not logged in
console.log( `Please log in` )
} else {
// Use IS logged in
console.log( `Welcome user!` )
}

That boolean code will produce this output in your console:

Most JavaScript projects will involve boolean values and conditional checks in crucial places to determine what actions to take based on what is going on in the application.

More Complex Data Types

In addition to our basic strings, numbers and booleans we also have some more advanced data types that are essential for us to learn about.

Here are two more:

  1. Objects - Can have it's own variables

  2. Arrays - Collections data

This is what they look like in action:

// This is an object
const post = { id: 1, title: `Post Title` };
// This is an array
const postIds = [ 1, 2, 3, 4, 5 ];

We won't do anything more with these now, but do want you to know there are more than just the simple data types we are looking at currently.

However, now it's important to practice what we have learned and build a little project or two.

Next Steps

Now that we have learned about simple data types, let's look at some practice exercises in the next chapter that will help us really solidify what we have learned.