<p>The exercise files for this chapter are made up of an HTML page that is blank (and really does nothing more than call in a JavaScript file) and the JavaScript file. We are really just messing around with creating variables and seeing how that works in JavaScript and much of this can (and probably will) be done in the console. The folder for the files 06_02.</p>
<p>Note that the first few parts of this chapter will be looking at different kinds of variables so we might think of these as variable types and these shoudl not be confused with data types. To make this clearer, we can create a variable with a statement like</p>
<preclass="inset">var a = 5;</pre>
<p>This is a straightforward statement assigning the number 5 to the variable called a so if, in the console, we type a and return, we will get a 5 back. In this example, var is the variable type and a variable type describes its scope and whether it is immutable or not. For var, the scope is global and the variable is mutable. In general, a variable is mutable by definition since it is a named value that can change. For example, having set a to a value of 5, we could then change it to something completely different.</p>
<preclass="inset">a = "blue";</pre>
<p>Note that we only need to declare the variable type once so we don't need to use it when working with a variable that already has a variable type.</p>
<p>We will look at scope shortly, but for now, ;et's just say that var is globally scoped and it is also the default variable type. Bear in mind that whatever you put in your JavaScript code, the browser will try to interpret it as best it can and will make some assumptions in doing that. For instance, lets say we have the following line in our code.</p>
<preclass="inset">b = 5;</pre>
<p>Assuming this is the first time the variable b has appeared in the code, the browser will assume that it is globally scoped so in essence, the variable type is var. There is one important difference between a variable declared as a var and a variable where the variable type is omitted. Once you have declared a variable type, you can't change it so for instance, we couldn't do this</p>
<preclass="inset">let a = 5;</pre>
<p>If we have already declared a with var. However, since we didn't declare a variable type for b (the browser assumed it was var), we can do this</p>
<preclass="inset">let b = 5;</pre>
<p>We can create multiple variables of the same variable type in a single statement separating them with commas like this</p>
<preclass="inset">var x = 4, y = 5, z = "red";</pre>
<p>We can also create variables that don't have any content (in other words, uninitialised variables).</p>
<preclass="inset">var empty;</pre>
<p>The value of empty, or any uninitalised variable, is undefined so if we type this into the console and then type empty and return, the browser will return undefined.</p>
<p>Aside from that, an undefined variable acts like any other. Consider the code shown below.</p>
<preclass="inset">
var a = "hello";
var empty;
console.log(a);
a = empty;
console.log(a);</pre>
<p>We have created two var variables, a with a calue of "hello" and empty which is undefined. We then output the value of a to the console which gives us hello as the output. Next, we assign the value of empty (undefined) to a and outpu tit to the console again. This time, the output is <em>undefined</em>.</p>
<p>I'm not sure if there would be any reason for detaching a value from a variable but this allows you to do that, but you don't need a variable to do that, you could simply assign it the value undefined.</p>
<preclass="inset">a = undefined;</pre>
<h2class="sectiontitle">Scope</h2>
<p>I mentioned earlier that variables of type var have global scope and this means pretty much the same as it would in most other programming languages but we will briefly look at what exactly this means in JavaScript. Bear in mind the fact that JavaScript is interpreted line by line so you cannot reference a variable based on its global scope until it has been declared.</p>
<p>The exerise files for this video which are in folder 06_03 include the following JavaScript code.</p>
<p>So, we first created a variable called color and initialised it with a string value, purple. We then use this to set the background color of the left pane to that value and also setting the innerHTML of the same pane to the same value. In other words, the pane will have a background colour of purple and will display the text, Purple. We also do the same thing with the right pane.</p>
<p>Between the two lines for the left pane and the two lines for the right pane, we then added a line of code changing the value of color.</p>
<preclass="inset">color = "skyblue";</pre>
<p>We are still using the same variable, color, to set the background colour and innerHTML for both panes, but in this case, color has a value of "Purple" when setting these values for the left pane, but it is changed to "skyblue" before the background colour and innerHTML are set on the left pane. The result is that one pane is now purple amd the other is skyblue.</p>
<p>A global variable has scope in the whole JavaScript file from the point where it is assigned a value and this applies whether the code that sets that value is inside a function or not.</p>
<p>This means that the browser executes each statement in sequence and so when the color variable is being accessed, it has the value that was most recently assigned to it.</p>
<p>Unlike var, a variable with type let has local rather than global scope. However, in some situations, there is no difference between the two. If you have a JavaScript file that is just a sequence of statements with no functions, there is only one scope - that is, every statement belongs to the same local scope and so the distintion between local and global scope has no meaning. However, if you have one or more function in your file, if you want a variable to apply only inside a function. you would declare it inside the function as a let variable and that variable cannot be accessed outside of the function.</p>
<p>Let's extend our example by adding a new function called headingColor so our code now looks like this.</p>
<p>This function is positioned at the end of the code file. It sets the value of the color variable to blue and then sets the colour value of the element with class title using that value so our title changes colour to blue.</p>
<p>The variable, color, has its value set three times. The first is where we are declaring it with let and setting the value to "green". It is then used to set the colour for the left panel and the value is set to "skyblue" which is used to set the colour of the panel on the right.</p>
<p>It is then set for a third time inside the headingColor function to "blue" and is used to set the colour of the title.</p>
<p>Note that since it was declared with let, it is a locally scoped variable but because of its positioning, it is local to this file so it can be accessed from anywhere within the file including inside a function so when the value is being set on all three occassions, it is the same variable we are changing. This means that the order in which the statements are executed is very important. To demonstrate this, let's shuffle the code around a little so that we are calling the headingColor function after the statement setting the value of color to "skyblue", but before we set the value of the colour in the right hand pane. The code now looks like this.</p>
<p>If we run this code, the left hand pane is green and both the title and the right hand pane. Although we set the value of colour to "skyblue", we then called the function, headingColor before it was used and this sets the value of color to "blue" so the value, "skyblue", is never used.</p>
<p>The main point to take from this is that the order in which values are set and used can be very important and you need to take into account scope. Bear in mind that if the variable is local to the file, as it is here, within the file it can be thought of as being a global variable so you need to make sure that if you set the value of the variable to a particular value for a specific purpose (such as setting the colour of the right hand pane) you need to make sure that you have used it for that purpose before setting the value again and that can mean if it is set inside a function (again, as it is here).</p>
<p>What do I mean when I say that this <strong>can</strong> include setting the value inside a function? Let's make another quick change in the code.</p>
<p>This time, we have declared the variable as a local variable inside the headingColor function. This means that whatever value we set it to inside the function, it isn't going to have any effect on the value outside the function. We now have two different variables called value, one is local to the file, the other is local only to the headingColor function.</p>
<p>The flow of the code is now like this. We set the value of color to "green" and use that to set the colour of the left-hand pane. We then set the value to "skyblue". Next, we call the function, headingColor which sets the value to "blue" (but only inside the function) and use it to set the colour of the title. When the function completes, we set the colour in the right hand pane but it is set to "skyblue" because that "blue" value was set on a different variable (the one that is local to headingColor.</p>
<p>This is probably a bad example in some ways, although a good example of demonstrating scope. In real life, you would probably want your code to be a little bit tidier. For example, if it is very important that particular colours are used for particular purposes, you would probably want to use different variable names which can also make your code easier to read. For example, if you have a variable declaration like this</p>
<preclass="inset">
let left-pane-color = "green";
let right-pane-color = "skyblue";</pre>
<p>This is clearer because you can tell just by reading the code why these variables were created and where they should be used.</p>
<p>It is also important to remember that when you are using global variables, you need to be careful, particularly if you are calling one or more function between setting the value and using it because it could be changed by a function before you use it and this can give you unintended results.</p>
<h2class="sectiontitle">Let</h2>
<p>We covered the basics of let in the previous section. One pint worth clarifying is that a variable declared it with let is scoped according to the code block in which it is declared. We suggested earlier that if it is declared within a function, it is only accessible inside that function which will be true in many cases, but this is because it is declared in the code block associated with that function. If there is another code block inside the function code block, this can change. A demonstration may make this clearer. Let's say that we amend our code to look like this:</p>
<p>Inside the headingColor function we have a conditional statement and there is an inner code block associated with it and inside this code block, we declare a variable called myVar. We then log this to the console, but our console.log statement is outside of the if code block so it can't access this variable and we get this error message in the console.</p>
<preclass="error">
Uncaught ReferenceError: myVar is not defined</pre>
<p>The pint is that with a locally scoped variable, it is only accessible in the code block in which it is declare, in this example that means the if code block. It is not accessible outside of that block.</p>
<p>Another interesting point here is that when we run this code, bothe the left and right panes are green and the title is blue. This is because if we go back to the code and walk through it line by line, we can see that the left pane is set to green, the color variable is set to "skyblue" and then the function is called, changing it to "blue" and setting the colour of the title to blue.</p>
<p>The if statement is called which declares the variable myVar with a let and then terminates and then we try to console.log the value of myVar and this generates the error.</p>
<p>The next statement would set the colour on the right hand pane to blue but the error in the headingClass function causes the javascript to stop rendering so the rest of the code is not executed (green is the default colour ).</p>
<p>The key point to remember is that it is perfectly normal to have code blocks inside of other code blocks in javascriptas we have in the example above. There we have three code blocks so it may be helpful in making things clearer if we identify each of these code blocks in turn so we can be clearer with respect to what we mean when we talk about declaring a variable inside a code block. Bear in mind the fact that a code block can generally be defined as any group of statements enclosed in curly braces, our first block is the excpetion to that rule and we will call it the file block. That is, any statements in our script are part of the file and therefore part of a code block. The end of this code block is simply the end of the file so we don't need curly braces.</p>
<p>Within that file, we have our function, headingColor and there is a code block associated with that, let's call that the function code block. Inside the function is another code block associated with the if statement so we'll call that the if block.</p>
<p>This means that there are three places where we can define a locally scoped variable and we have one of each of these so let's look at these in turn. Firstlt, we have</p>
<preclass="inset">
let color = "green";</pre>
<p>This is declared in the file block so it is accessible anywhere in this file (essentially making it a global variable, inside the file). Since it is accessible anywhere within the file block, it is also accessible inside the function block or the if block.</p>
<p>The second variable is</p>
<preclass="inset">
let color = "blue";</pre>
<p>This one is declared inside the function block so it is only accessible inside the function. It cannot be accessed from other parts of the file block.</p>
<p>Finally, we have</p>
<preclass="inset">
let myVar=5</pre>
<p>This is declared inside the if block, so it is only accessible inside that block. This means that if we want to access it, isn't enough to try to access it from inside the function, any attempt to access it must be inside the if block.</p>
<p>In most cases, if you need a mutable variable, you will probably want to use a let declaration because this gives you more control over the variable. A var declaration (with global scope), since it is accessible from anywhere, is more liable to be changed accidentally or to be duplicated.</p>
<h2class="sectiontitle">const</h2>
<p>The const keyword defines a block scoped constant. To see an example of this, we will take the same example we have seen previously and amend it so that the first color variable is defined as a const like this.</p>
<p>If this code runs without error, we would expect the heading to be blue, the left pane to be purple and the right pane to be sky blue. What we actually see is that the heading is black, the left pane is purple and the right pane is green, so the only colour change has been in the right pane.</p>
<p>In the console, we get this error message.</p>
<preclass="inset-error">
Uncaught TypeError: invalid assignment to const 'color'</pre>
<p>The error happened when we tried to change the value of color to "skyblue" and at this point, rendering stops before we call the headingColor function. If we change the variable name from this line of code so</p>
<preclass="inset">
color = "skyblue";</pre>
<p>becomes</p>
<preclass="inset">
colour = "skyblue";</pre>
<p>(we would also need to change this in the line of code that sets the colour of the tight hand pane). When we run this, we see that everything looks as it should and the console is free of errors. You may have expected this because although we cannot redefine the const color in the same scope, the function code block can also create a const with the same name and since this is a different scope, that works perfectly.</p>
<p>So, we can't change the value of a variable declared as a const in the same scope, but what this actually means is that when we declare a variable with const and give it a value, the variable will always reference that value. This means that we can't point it to a new value, but we can make changes to the value's properties (assuming that it has them). For example, if the const was referencing an object called myBackPack, we wouldn't be able to change this to reference yourBackPack (assuming both myBackPack and yourBackPack are instances of the Backpack class we saw earlier) so the value is constant in that sense.</p>
<p>On the other hand, myBackPack has mutable properties so if we change these, for instance we might change the strap lengths of myBackPack, that's perfectly fine and our const variable will still reference myBackPack with the amended strap lengths.</p>
<p>This means that if we say that you can't change the object that a const variable references, we mean that you can't change it for a different object, but you can make changes to the object itself.</p>
<p>Similarly, if a const variable references something like an array, it must always reference the same array but we can still change the array itself.</p>
<p>At the end of the previous section, we said that in most cases, if you want to use a mutable variable in your code, you should declare it with let. If you want to use an immutable variable, you should declare it with const.</p>
<h2class="sectiontitle">Data Types</h2>
<p>JavaScript is a loosely and dynamcially typed language. It is loosely typed because when we declare a variable, we don't have to worry about the type. We can simply assign a value and let the interpreter decvide what type it is.</p>
<p>It is dynamically typed because the type of a variable may not be known when the code is written or even when it is executed. For example, you may create a variable and assign it with a value obtained from the user, such as the user's age and let's assume that we have a variable called age to hold this value. The user may input any value but if we assume that they do input their age, this might be</p>
<preclass="inset">
• an integer such as 13
• a float such as 13.75
• a string such as "Thirteen and three quarters"</pre>
<p>The data type of a variable is determined simply by assigning a value to it and we can change the type by assigning a value with a different data type to it. You can find more information on the data types available in the online <ahref="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">MDN Web Docs</a>.</p>
<p>In most programming languages, it is important to know the differences between the various data types, particularly those that are similar. For example, you might have int and long for integer types or float and double for floating point numbers. In JavaScript, these differences are irrelevant because of the fact that JavaScript determines the type for you. All that you need to know to write JavaScript is the different kinds of value you can assign to a variable.</p>
<h2class="sectiontitle">Assignment vs Comparison</h2>
<p>We have already seen the use of the equals sign to assign a value to a variable, so that is the assignment operator. We also use the equals sign as a comparison operator. We can summaeise the way it is used like this</p>
<table>
<tr>
<th>Symbol</th>
<th>Operator</th>
<th>Example</th>
</tr>
<tr>
<td>=</td>
<td>Assignment operator</td>
<td>a = 5;</td>
</tr>
<tr>
<td>==</td>
<td>Comparison operator</td>
<td>if (5.0 == 5);</td>
</tr>
<tr>
<td>===</td>
<td>Identical comparison operator</td>
<td>if (5.0 === 5)</td>
</tr>
</table>
<p>The difference between the comparison operators is that the first of these, the comparision operator, will return a true value if both of the operands have the same value. In this example, 5.0 and 5 have the same value but different types, however the comparison operator does not take type into account and so this would return a true value.</p>
<p>The identical comparison operator is similar, but will only return a true value if the operands have both the same value and the same type. In this case, the identical comparison operator would return a false value.</p>
<h2class="sectiontitle">Math Operators</h2>
<p>The math operators in JavaScript seem to be pretty much standard but the code example may be useful for experimentation if there is an operator you are not sure about. You can change either the values or the operator in the code to see exactly what that operator does.</p>
<preclass="inset">
let a = 5;
let b = 4;
let result = a + b;
console.log("Result: ", result);
console.log(typeof(a));
console.log(typeof(b));
console.log(typeof(result));</pre>
<p>In this example, we are performing a simple addition using the two integer values and the result is 9, which is also an integer. I will perform some further tests with a number of operators and different types of values and summarise the results in a table below.</p>
<table>
<tr>
<th>Value of a</th>
<th>Type of a</th>
<th>Value of b</th>
<th>Type of b</th>
<th>Operation</th>
<th>Result</th>
<th>Type of result</th>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>4</td>
<td>number</td>
<td>a + b</td>
<td>9</td>
<td>number</td>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>3.2</td>
<td>number</td>
<td>a + b</td>
<td>8.2</td>
<td>number</td>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>4</td>
<td>number</td>
<td>a / b</td>
<td>1.25</td>
<td>number</td>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>4</td>
<td>number</td>
<td>a % b</td>
<td>1</td>
<td>number</td>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>4</td>
<td>number</td>
<td>a ** b (exponent)</td>
<td>625</td>
<td>number</td>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>'4'</td>
<td>string</td>
<td>a / b</td>
<td>1.25</td>
<td>number</td>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>'4'</td>
<td>string</td>
<td>a ** b (exponent)</td>
<td>625</td>
<td>number</td>
</tr>
<tr>
<td>5</td>
<td>number</td>
<td>'4'</td>
<td>string</td>
<td>a + b (exponent)</td>
<td>54</td>
<td>string</td>
</tr>
</table>
<p>This isn't intended to be a full list of available operators, for that you can visit the online docs in the <ahref="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math">MDN Web Docs</a> or <ahref="https://www.w3schools.com/js/js_arithmetic.asp">w3schools.com</a>. JavaScript doesn't have an operator for integer division but it is nevertheless possible to perform intenger division using the floor method which is part of the Math library and you can get more information on that from an article on delfstack.com entitled <ahref="https://www.delftstack.com/howto/javascript/integer-division-javascript/">Integer Division in JavaScript</a>.</p>
<p>There are a couple of interesting points in this table, however. Firstly, note that the table is far less complex than a similar table covering Math operators in most programming languages would be because of the fact that the data type for almost all of these operands is number (as I mentioned earlier, we don't have different types of integer value and to some degree, JavaScript doesn't even differentiate between integers and floats when it comes to number types, it just classifies everything as a number.</p>
<p>Second, you will notice that when we combine a number and a string where the string can be converted to a number, this conversion takes place automatically. For example, if we perform an operation like</p>
<preclass="inset">
5 - '4'</pre>
<p>this operation only makes sense if the operands are numbers, so JavaScript converts the string value '4' to the number 4 and then performs the operation and returns a number, 1 in this case, as the result. This also applies in most cases with arithmetic operations, but not when the operation is an addition. In that case, there is a string operation using the + sign and that is concatenation. As a result, if we have an operation like</p>
<preclass="inset">
5 + '4'</pre>
<p>the 4 is converted to a string value, '5' and the operands are concatenated rather than added. This gives you a result which you may not expect of 54 and this value is a string value. When it comes to mixing strings and numbers in an operation, you therefore need to be careful when using the + operator.</p>
<p>Another operator which is not really an arithmetic operator is the increment operator (++). It works in the same way as it does in languges such as C or Java. Let's say we have a value such as </p>
<preclass="inset">
a = 5;</pre>
<p>and we then assign a value to bwith</p>
<pre>b = a++;</pre>
<p>What value will b have and what will the value of a be after performing this operation. To test that, let's compare two short snippets of code.</p>
<preclass="inset">
let a = 5;
let b = a + 1;
console.log("The value of a is", a);
console.log("The value of b is", b);</pre>
<p>This is straightforward, it assigns a value of 5 to a and then assigns the result of a + 1 to b so be has a value of 6. You might expect to get the same results using the increment operator like this.</p>
<preclass="inset">
let a = 5;
let b = a++;
console.log("The value of a is", a);
console.log("The value of b is", b);</pre>
<p>the output this gives us is</p>
<preclass="inset">
The value of a is 6
The value of b is 5</pre>
<p>The reason for this is that the increment operator is incrementing the value of a but there are two forms of the increment operator so let's see what happens when we use the other form.</p>
<preclass="inset">
let a = 5;
let b = ++a;
console.log("The value of a is", a);
console.log("The value of b is", b);</pre>
<p>This time, the output we see is</p>
<preclass="inset">
The value of a is 6
The value of b is 6</pre>
<p>So again, a has been icremented by 1 but this time, it is the increased value which has been assigned to b and to explain why this happens, consider the following question. If we are incrementing and assigning the value of a to b, which of these operations do we do first. If we do the assignment first, b will have a value of 5 but of we do the increment first, b will have a value of 6.</p>
<p>The two forms of the increment operator are the post-increment operator and the pre-increment operator. With the post increment operator, which we saw with</p>
<preclass="inset">
b = a++;</pre>
<p>The increment is performed after the assignment and so b is assigned the value 5. The pre-increment operator</p>
<preclass="inset">
b = ++a;</pre>
<p>a is increment before the assignment takes place and so b is assigned the value 6. Note that a is incremented in both cases and so has a value of 6 in both.</p>