In lesson 2, we learned about branching. Branching is one of the most important concepts in coding, it's what allows the program to make decisions based on the current state of the system.
Boolean expressions are simple expressions that can be either true or false.
The simplest boolean expressions in Javascript are the terms true and false. Boolean variables can take on one of these 2 values
We generally ask a "true or false" question about data to create a boolean expression. For example, if you have a number stored in a variable, you can ask questions about it, like "is it greater than 10?". We write these in a mathematical expression like num > 10
We act on boolean expressions by using an 'if' statement. An if statement has the following construction or syntax:
if( expression ) { ... }
In the above, expression should be replaced by a boolean expression that evaluates to either true or false. If the expression evaluates to true, then the code inside the curly braces (represented by ...) is executed. If the expression is false, the code is skipped.
We can execute something different if the expression is false by using the else statement. An else statement follows immediately after the if statement, and looks like this:
if( expression ) { ... } else { ... }
To create a checkbox in HTML, we use the input tag with the type attribute set to "checkbox".
In Javascript, you can tell whether a checkbox is checked or not by using the property checked. The checked property is a boolean value of true or false.
Using the checked property, we can do something different depending on whether the user checked the box or not
Below is a complete example that you can copy and paste into a file, and then run on your browser, which shows what we accomplished in the class
<!DOCTYPE html> <html> <head> <title>Lesson 2 for coding!</title> <script> function showString() { var ischecked = document.getElementById('option').checked var str = document.getElementById('thestring').value var target = document.getElementById('code') if(ischecked) { target.innerHTML= "<b>" + str + "</b>" } else { target.innerHTML = str } } </script> </head> <body> Result appears here: <span id="code"></span> <p> <input id="thestring"> <input type="checkbox" id="option"> Bold <button type="button" onclick="showString()">Click Me</button> </p> </body> </html>
Here are several playgrounds that you can use to try out HTML and JavaScript. Note that I no longer recommend LiveWeave due to the issues we have had during class. I am now recommending JSFiddle. It has very similar features, but I think is better implemented. There is also the ability to add a console to allow understanding what is wrong in your javascript code. Unfortunately, it's not easy to do, but we will work on it at the beginning of next class.
You can also open a local file (if you have a normal computer), name it anything with a .html extension, and then open it in your browser and it will work!
©2019 Steven Schveighoffer