Javascript String Basics, How to Make and Edit Strings

Strings

Strings are sequences of characters. In the previous post, we saw how to open the Chrome devTool inspector panel. In the console tab, we can enter numbers and use the console as a basic calculator. When dealing with numbers in Javascript, we do not place quotes around them, but when entering strings, they must begin and end with a quotation mark. The quotation mark can be a single ' or a double " quotation mark. For example, to create a string with the text Hello World, type "Hello World" into the console then the return key to execute. This will cause the string "Hello
World"
to be repeated in the console. What’s happening here is the line is actually read in, then Javascript produces an actual string and then returns it. This returning of the string is what produces the second output of "Hello
World"
. The string is returned, but it is never saved, so it just vanishes in this example.

Declaring String Variables

Well, the previous example was not very useful – a string is created and then vanishes. To improve on this and do something a bit more useful, we need to save the string somehow. This is done by declaring a variable and the string as the variable’s value. Variables are declared with the keyword var followed by the variable name. For example, to declare a variable named myString, type var myString followed by enter. This will create a variable, yet the variable has no set value. The equal sign is used to set the variable’s value and the syntax to set a string value looks like variableName = “value”. So for our example, setting myString to Hello World, type myString = "Hello World" followed by enter. It is possible to combine the variable declaration and setting into one command like this var
myString = "Hello World"
.

Using Variables

OK, so the variable is declared and set, but it’s still not useful unless we can do something with the variable. Let’s declare one more variable named, myName and set it to “My name is ______” but go ahead and put your name there. So for me, it would look like var myName
= "My name is Matthew"
and then enter. Next, let’s put the two strings together. This is called concatenation. This is done using the + sign. Technically the + sign here is an operator, as it performs an operation. So putting the two together looks like myString + myName. Go ahead and try it. Well, that’s not quite correct – it returns “Hello WorldMy name is Matthew”. That’s pretty close, but some spacing would help us out. Let reassign (update) the myString variable. Let’s add a period and a space to it. This can be done by simply reassigning it as myString = "Hello World. ", but I’m lazy and don’t want to retype “Hello World” again. Instead, I can use a special operator call the concatenation operator which looks like +=. The += operator concatenates two string variables together and updates the first variable to the concatenated string. An example should help clear that explanation up. So continuing with our previous example, to update myString by adding a space and a period, we can simple use myString
+= " ."
. Don’t leave out those quotes! So if we did all that correctly we should be able to do myString
+ myName
ENTER and see “Hello World. My name is Matthew”.

Something neat

Let’s try something fun. In your Chrome devTools console, enter document.title = "Kittens". Now look at the top of the browser, and look at the tab title for the site. It now says Kittens. You just updated the document title with a new string.

So you now can “hack” and change the title of a website. Do you know any other string hacks? Leave a comment if you do.

How to Create Arrays and Lists in Javascript

In the previous post, we went over strings and variables, but we need methods to organize our strings and variables. If we were going to the grocery store, we would not write bananas on one piece of paper, bread on another, milk, eggs, cheese, etc each on separate pieces of paper. This would become very disorganized quickly. Instead, we create a list. Javascript has something very similar to a list called an array.

Grocery list

Let’s create a list called groceries. Let’s do this in the Chrome devTools console tab. How to open the console was covered in this post here. To make our grocery list we need to declare a new variable. Just like when we declared our string variable in the previous post, we will use the var keyword. However, to create the list we need to use a pair of square brackets []. We can make an empty list like this: var groceries = [], but this isn’t very useful. In order to have things in our list, we add them inside our brackets and separate them with a comma. Strings still need to be in quotes, so a list with milk and bread would look like:  var
groceries = ["milk", "bread"]
. Go ahead and give that a try, type that in and press enter. Now to see your list again, you can type groceries and hit enter.

Array of Numbers

Arrays can also hold numbers. Creating an array with a number is the same as with a string except you don’t place numbers in quotes. For example, var lotteryNumbers
= [4, 8, 15, 16, 23, 42]
.

Other useful array features

Arrays have some cool features that make them very useful. An array can tell you how many items it has with the length property. To check the length of our groceries list, we would use groceries.length. The dot here allows us to access the “Sub” properties of the array. The length is a property of all Javascript arrays. Along with length, arrays have a few functions that are also accessible by using “dot” after the array name. One of the most useful allows us to search an array to find the position of a specific entry (element). This property is called “findIndex”. Since it is a function, it has to be invoked. Functions in Javascript are invoked with a pair of parenthesis immediately after the function’s name. For example, if we had a list of students ordered by class rank, and we wanted to know John’s position, given the array var
students = ["Mary", "John", "Steve",
"Bob"]
(Looks like the parents of these students were not very creative in naming their children), we could enter students.indexOf(“John”) to find that John’s index is 1. Well, that may not have been what you expected, since Mary is the first student, but our indexes start with 0. So Mary’s index would be 0 and John’s would be 1.

I

f the item is not found, findIndex returns -1. It’s a common operation to use this in order to check if an item is in an array. The logic looks like this: “if findIndex of needle in haystack is -1 then the needle is not present”.

Arrays come with a lot of other properties and built-in functions. Check out this list on MDN to see what else an array can do. I’ll cover arrays in more detail in a later post.

Feel free to use the comment section to create some array examples.

How to Create and Use Basic Objects in Javascript

Previous posts have covered strings, numbers, and arrays. Arrays can help organize related strings and numbers into a list-like behavior, but finding items in the list can be a bit difficult. Javascript offers one more method to organize data called an “object”.  Objects store and retrieve items using a key – value system. For example, if you had an item located somewhere in a room full of lockers, you might tell someone to go and get me the contents of locker 15. In this example, the key is 15. Another example might be a phone book or encyclopedia (ancient relics of the past), where the key would be the subject title or person’s name and the value is the content.

Time to break some stuff

Ok, let’s go back to the console to look at this concept first hand. (First post covers opening the console) Let’s create a new object called “bank”. Enter the following into the console var
bank = {}
. When you press enter, it will create a new object and store it as a variable named bank. To verify this, you can type bank and hit enter. The console will show you a set of brackets like {}. Now, most banks have accounts, so let’s add a few accounts to our bank. Good news, our first customer John just walked in and created a new savings account with $500. So we need to store at least two bits of information about John’s bank account, the balance, and the account type. For our bank, we need to store multiple bits of information about each account, the best way to do this is by using an object.

As you just learned, objects can store string and numbers, but they can also hold other objects. With that in mind, let’s create a new object called John. But this time instead of creating an empty object, we will create the object with John’s account information. Similar to when we created the bank object, we will use the var keyword and a set of brackets, but our brackets this time will not be empty. We will add the object’s data inside the brackets and each entry will be delimited by a comma. Each item entry is a key-value pair with a colon separator. So for John’s account it will look like var john =
{balance: 500, accountType: "savings"}
. There are a few things here I want to point out, as I hope to prevent you from confusion. First, you should notice that the “Keys” balance and accountType are not in quotes; this is because they are the “keys” and in the same way that our object name “John” isn’t required to be in quotes, they do not need them either. Now it is OK to add the quotes and var john =
{"balance": 500, "accountType": "savings"}
would be perfectly valid. Second, string values need to be in quotes, but numbers do not. So now we have an object called bank and an object called account, but this is not very useful yet because we want John’s account to be part of the bank variable.

Putting it all together

Now we need to add John’s account to our new bank. With John’s account, we added the values during the object creation, but we created the bank as an empty object. Now we can add John’s account object to our bank object. There are a few ways to add to objects, here I will cover “dot notation”. Adding a subobject to an outer object looks like outerObject.subObject = “value” keep reading a bit if that is confusing. Hopefully, our bank example will help. We already created our empty bank with var
bank = {}
, now to

add John’s account to our bank with the key, “johnsAccount” we enter bank.johnsAccount
= john
. Great, now our bank has a new customer named John and we can access his account info using the same dot notation bank.johnsAccount This will return us John’s account details.

Bonus material

John just came back in and deposited an extra $100, now we need to update his balance, how can we do this? To update John’s account, we can use the dot notation to access his balance and update it. To add $100 we could set it to 600 using bank.johnsAccount.balance
= 600
, but we could instead let Javascript do the math. There are a few special operators for add, subtract and other math functions. To add to a variable, we can use the += operator. This is called the “plus assignment” operator. It’s called “assignment” since it does the math and reassigns the variable of the output. If we wanted to add 100 to the balance without using the assignment operator, it would look like this: bank.johnsAccount.balance =
bank.johnsAccount.balance + 100
. However, using the assignment operator shortens the statement quite a bit to just bank.johnsAccount.balance += 100. Running this will update the balance by adding $100. There is also the -= assignment operator which works the same way, but of course, subtracts.

Strange behavior

There is one strange side effect of changing the bank balance. We updated bank.johnsAccount.balance, but what about our original variable of john? It turns out that it gets updated too. Take a look, type john in the console and hit enter and you will see that john.balance has been updated. This is because bank.johnsAccount wasn’t just set to the value of “john”, it actually is a reference to the variable john. Updating one changes the other as well.

This is a special feature of objects, this same behavior is not repeated with string or number variables. For example, var
foo = "bar"
followed by var bax = foo of course sets bax to the value of foo, which is then the string “bar”. You might think that changing foo would also change the value of bax, yet it doesn’t.

Can you think of some good uses for objects? Leave me some examples in the comments. Remember to practice what you are reading. When I was first learning, I could read and read, but it only “sunk in” once I practiced it. So go ahead and open up that console.

How to Write Your First Function In Javascript

Functions are the basic building block of programming

Now for the real meat of programming, functions. Functions are named sections of code that combine operations to perform a certain procedure. Functions can accept inputs and may return a value (an output). In the previous post, we started a bank and our first customer, John, deposited $500. Whenever John made a transaction, we had to add or subtract the transaction from his balance manually. This is a perfect use case for a function. By the end of this post, you should understand how to write a function that can do exactly that.

A very basic function

Let’s start by making a very basic function that calculates a tip for us. Given we want to always tip an even 15%, this is an extremely simple function to write. To calculate this in the console would just be cost * .15, but now, let’s make a function. We can declare a function with the var keyword, just like we declared strings, arrays, and objects. The var keyword is followed by the function name, an equal sign and then the function’s body. Let’s call our tip calculator function, “getTip”. Since our tip is based on the cost of a service or meal, our function will need a way to accept that value as an input. Parameters are used to provide inputs to functions and we will need to input the meal cost, so let’s make a parameter called “cost”. Now, our function would look like this: var getTip = function (cost) { return cost * 0.15 }. The return keyword causes whatever follows it on the same line to be “outputted” from the function, but the return keyword also stops further execution of code. Try creating this function in the console (see how to open here). After the function is declared, it’s stored under the named variable you assigned it to. So, if you used getTip, you can type getTip, followed by enter to see that it has successfully been declared as a function. This will not execute the function, but simply display it in the console.

Invoke a function

Now to invoke a function, we enter the function’s name followed by a set of parentheses. Inside the parentheses, we place the value (or values) of our parameters. So, to calculate a tip for a $50 meal, we would use getTip(50). This will “return” (“return” is the output of a function) us the tip amount, or in this case, 50 * 0.15, which is 7.5.

Bank deposit function

Our getTip function takes a parameter “cost”, performs a calculation using this parameter and then returns a value; however, not all functions must return a value. Some functions can perform an action and modify an existing object, but return nothing. In a previous post we used a bank as an example, let’s use that example again. First declare the bank object, var bank = {}, and then we can add John’s account directly bank.john = { accountType: "savings", balance: 500 }. This is slightly different than how the account was created in the previous post, but it does the same thing. Now, if we type bank and hit enter, we should see our bank object with John’s account on it. Great, our bank is loaded. Next, let’s create a function named deposit, that will make a deposit to John’s bank account. We can name this function “deposit”, and it will take the balance in John’s account and add to it whatever amount is passed into the parameter “amount”. Thus, it would look like:

var deposit = function (amount) {
  bank.john.balance += amount
}

We timed that perfectly, as John just won the lottery and is here to deposit his $1,000,000 winnings. Let’s give it a try deposit(1000000), and now we need to check John’s account balance, bank.john.balance. Wow, that worked great, John’s balance is now $1,000,500, and we didn’t have to do any manual update to his account balance. However, there is a problem here: this function works great if we only have one customer, but most banks have multiple customers, and they will not be happy if every time they each make a deposit, it winds up in John’s bank account. Fortunately, there are a lot of great solutions for this problem, and in future posts, we will cover fun and useful concepts like classes and inheritance that solve this and similar problems.

Practice

OK, in the comment sections, see if you can create functions to do some of the following:

  • Multiply a number by 2
  • Square a number
  • Make a greeting function that takes someones name and returns “Hello, [name here].”
  • Function to withdraw from an account
  • A function to add interest into a bank account
  • Or another problem you can think of

How to Add Javascript to an HTML Webpage

Until recently, using JavaScript meant was reserved strictly to building websites, but today, Javascript runs pretty much everywhere. That being said, the most common application for JavaScript is still to manipulate websites or make a web-based application. There are two ways that JavaScript code can be loaded and/or added to a webpage: inline scripts and external scripts.

Practicing these examples will help you start your journey of learning JavaScript. You will need a simple text editor to make your website files. Don’t use a word processor, because they adds hidden tags to format documents, and while these tags are useful for producing formatted documents, they are not compatible with HTML.

To begin, you can open a valid HTML file with your browser. There are a few ways to do this, and the easiest way is to right click the file and use “Open With” to open the file with a web browser. For more information, visit https://www.codecademy.com/articles/local-web-page

Using inline scripts to add Javascript to a web page

Let’s open our editor and create a basic webpage using the following code:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello Javascript</title>
    </head>
    <body>
        <h1>Webpage works!</h1>
    </body>
</html>

After saving and opening the file, you should see the bold title “Webpage works!” when you view that file in a browser. So now let’s add some JavaScript.

JavaScript can be added directly to an HTML webpage by adding it inside script tags <script> /*javascript code goes here */</script>. There is a function console.log that allows us to output values to the console. Let’s use it in our first script. Let’s insert a set of script tags inside our previous HTML code with console.log('Hello from Javascript') inside. Our completed HTML should now look like:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello Javascript</title>
    </head>
    <body>
        <h1>Webpage works!</h1>
        <script>
            console.log('Hello from Javascript')
        </script>
    </body>
</html>

Now open that page in a web browser. With the console open, you should see the words “Hello from JavaScript”.

Adding external Javascript files to a web page

Inline scripts are fine for smaller sections of code, but they are not ideal for larger projects. Thankfully we can solve this problem by using external scripts. To demonstrate this, let’s write some JavaScript in a separate file and then include it into our page with the same script tags as above, but with one modification.

To do this, we can use an attribute within the script tag which looks like: <script src="file.js"></script>The “src” stands for source, and it defines where the webpage can find the script file. So to add an external script to our example web page, let’s save a JavaScript file in the same folder as our HTML file and name it “example.js”. Using our text editor again, add the console.log('Hello from Javascript') . Let’s also add another line, console.log('I am an external script'). So our example.js file should look like:

console.log('Hello from Javascript')
console.log('I am an external script')

Once that is done, we need to go back to our HTML file and update our script tag. By having the two files in the same folder, all we have to do is add our Javascript file name to the “scr” attribute. So your HTML file will look like:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello Javascript</title>
    </head>
    <body>
        <h1>Webpage works!</h1>
        <script src="example.js"></script>
    </body>
</html>

As long as we entered everything correctly and the files are in the same folder, opening the HTML file with a web browser should look like:

You can see both of the console.log statements printed their values into the console. It’s important to note, however, that if the file was in a different location or named incorrectly, our browser would try to load the file but would return an error instead. This would look like:

And our console.log would never show, of course.

That’s all there is to it! I also added a special file to this page, and it is logging a question for you in the console. Please take a look and answer the question in the comments.

please feel free to checkout out one of my projects AEROTRAKS.COM

How to use Javascript to Interact With HTML Webpage

One of the most useful aspects of JavaScript is its ability to manipulate a website. When a pure HTML website loads, that’s it—it’s done and it will not change again until the page is reloaded. Adding JavaScript to a page, however, gives us the ability to update a page even after it has been completely loaded. We’re going to be using the Chrome devTool’s console for this post, so if you don’t know how to open it and use it, please check out the console post for more info.

The HTML Document

The HTML document is composed of elements that are created using tags. HTML tags have the standard format <tagname>Content</tagname>

, and they describe the type of content they contain. For example, to indicate the beginning and end of a paragraph, the content is wrapped using a “p” tag: <p>The paragraph goes here.</p>. W3 School has a great in-depth article here covering HTML tags.

When using JavaScript to manipulate an HTML document, we can use the tags as a road map to navigate and select the document section we want to manipulate.

What is the DOM

When dealing with JavaScript and HTML you will likely hear people refer to the DOM. DOM stands for Document Object Model, and it is essentially an interface that allows JavaScript to access the web page “document.”

To illustrate this point, imagine a string puppet for a minute. If you think of a web page as a puppet, then the DOM could be thought of as the strings and the points at which they attach to the puppet.

Using this same analogy, JavaScript would best be compared to the stick that controls the strings. The DOM allows us to connect JavaScript and HTML together.

Included with a browser’s JavaScript version is an object called the “document.” It is on this object that we can find methods that allow us to interact and manipulate the DOM. Continuing with the analogy, the puppet control sticks have multiple “methods” or actions that can be used to manipulate the puppet.

The DOM is made up of elements that are connected in a tree-like structure. The elements of this tree are objects, and they can be accessed from the root document object mentioned in the previous paragraph.

Navigating the DOM

Before we can manipulate a section of the DOM, we first need to know how to select an element. To help with this, I’ve made a very simple web page that you can experiment with: http://matw.me/example.html. Open this page in a new tab and follow along.

Here is what the HTML code of this example.html page looks like:

<!DOCTYPE html>
<html>

  <head>
  </head>
  <body>
    <div>
      <h1>Div 1 Heading 1</h1>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
    </div>
    <div>
      <p>Div 2 Paragraph 3</p>
      <span>
        Text inside span 1.
        <span style="color: blue;">I am a span within a span.</span>
      </span>
    </div>
  </body>
</html>

As you can see, it’s a fairly simple page. There is an inline style to color the nested span blue, but not much else is going on. First off, let’s change the text of the first paragraph.

Before we can manipulate the first paragraph, we have to select it. There are many ways to select an element on a page—you can get elements by class name, id, tag name, or by “walking” up and down the DOM tree. Since the “document” is the DOM root, everything on the web page is a child of the document.

This may be a bit difficult to understand, so let’s take a closer look at it. Go to the example.html page and then open the console. Then type in document.children and press enter. The console should look something like:

Now click the triangle to expand the HTMLCollection object. Can you see how it compares to our HTML code? The first and only child element is the “html” object. This is the root from which everything else on the page stems. Since this is an object, we can save it to a variable. To do that, use var htmlRoot = document.children[0] and press enter. We have to add [0] to the end of our document.children because we want the first child. In JavaScript, the first item is item 0. Now our variable htmlRoot is a reference to the DOM’s html object. Looking back at our page code, you can visualize what this variable references on the page.

Let’s take a look at the HTML’s hierarchical structure:

In the console, we can view the content of our htmlRoot variable. Enter htmlRoot and you should see:

In a tree form, this would look like:

As you can see in the tree above, “html” has two children: “body” and “head.” If we want to navigate to the first paragraph, we have to go through the “body” and then the first “div.” The first paragraph will then be the second child.

Let’s return to navigating to our first paragraph element, and take it one step at a time. Remember the htmlRoot object we created earlier? This is the html element at the top of our tree, so if we enter htmlRoot.children, we should see that htmlRoot has two children: “head” and “body.”

We already know we want the body, which is the second child. Since our index starts at 0, htmlRoot.children[0] would refer to the head, and htmlRoot.children[1] would refer to the body. Let’s save the body as a new variable. We can do that with var body = htmlRoot.children[1], and pressing enter.

Now let’s look at our body variable:

All the code entered to get here is recapped at the bottom of the page.

Well, I think that’s pretty neat. We now have a JavaScript variable that represents the HTML “body” element. Now to get that first paragraph, we need to go to the first child of the body, which is a “div” and then the second child of that div would be our paragraph (p element). That will be:

var firstDiv = body.children[0]
var firstParagraph = firstDiv.children[1]

In the console it would look like:

As you can see, we finally have our paragraph saved as a variable! Now we can manipulate the text, style, class, id, or other attributes of our “p” element. This style of selecting an HTML element by going up or down the tree using children or parent selectors is called “walking the DOM.” There are other ways to select elements on a page, but I will cover these in future posts.

Changing An Element’s Text With JavaScript

Let’s update the text in our first paragraph to say “Hello World.” Even though navigating the DOM and selecting the first paragraph was somewhat complicated, changing the text itself is very easy. The paragraph element, which is of course an object, has a property “innerText.” If we type firstParagraph.innerText, we will see the current text of the element returned.

We can simply set this innerText to our new value and it will update the page.

firstParagraph.innerText = "Hello World"

Instantly, our text gets updated to “Hello World”.

Recap

In order to update a section of text on the screen, the first step we need to take is selecting the element’s DOM object. Then we can reassign the inner text. For this page, it looks like:

What’s next?

There are lots of methods that can be used to select elements from the DOM, and while many of them would have made selecting this element easier, in my opinion it is very important to learn how to navigate the DOM using a simple straight “walk down” as demonstrated here. Learning this method helps provide an understanding of what the DOM is and how it is structured.

In my next post, I plan to go over other “document” methods that will make navigating and manipulating the DOM simpler and faster.

In the meantime, play around with selecting DOM elements and updating them. Share some screenshots in the comments section.