Lab 8

Program Flow and State

Christian Grewell
Nov 4 · 9 min read
Photo by Matt Popovich on Unsplash

What You Should Know:

  1. What are some common operators in JavaScript
  2. What is program flow and why is it useful.
  3. How to write an statement and an statement.
  4. What a JavaScript event is
  5. What State is in an application?
  6. How to use to add interactivity to a React program

OPERATORS

This should be review for most of you, but we are going to need to remember some common operators in JavaScript in order to work with statements and other program flow concepts.

less than

greater than

less than or equal

greater than or equal

equal to

not equal to

And some logical operators:

and

or

not

LOGICAL OPERATORS (and or and not )

The and operator will evaluate to if all statements are true:

console.log(true && false); 
//false
console.log(true && true);
//true

The or operator will evaluate to true if one of the statements is true

console.log(true || false); 
//true
console.log(false || false);
//false

The not operator will flip the value that you give it

console.log(!true); 
//false
console.log(!(1 === 2));
//true

Program Flow

Normally program flow is top to bottom, left to right. If that were the only option available to us, we’d have a lot of very linear programs and not a lot of interactivity. There is also conditional program flow, these are ways that expressions can be evaluated to produce different output. There are a few workhorse statements in JavaScript that help us direct the computer to do different things based on different conditions.

They are the statement, associated and statements as well as looping statements such as , , and . In this portion of the article, we’ll cover the , and statements.

Branching Logic

The first batch of statements handles ‘branching’ within our programs. What I mean by this is that we first evaluate a statement, and then do something depending on the way that statement evaluated. Think of it like a fork in the road, or even a huge public square with many many paths leading out.

The statement

The statement is very useful. You can use this to evaluate if something between parentheses is true.

We can also use the statement to check if something is not true. The statement will evaluate whatever expression you give it and if it’s true, it will execute whatever is between the

The statement

The else statement gives us another path to take

Below is the statement syntax. First, JavaScript will evaluate the statement in , just like the statement does, then if the statement is false and there is an else following the closing , it will execute that statement.

You can also add even more conditions to check before the else statement by using the statement after the first statement.

Challenge:

Write a function that accepts a argument and ’s a different message depending on if the argument is true or false.

Interactivity and State

Now that you know a bit about functions, variables, data types, program flow, components and properties, you’re finally ready to add interaction to your application. In this rest of this article, we’re going to introduce you to two final big concepts you’ll need to understand in order to create web applications: program flow and state.

Let’s take a text field that should respond to user input, if the user enters the their name, we’d like to show a fun gif on the page, if they enter anything else, we’d like to show an unfun gif on the page. This is more than just a user interface now, this is the beginning of an interactive web application. Before we show you the code, let’s think about how our application should be structured. What will we need?

  1. We’ll need a text input field.
  2. We will need a way to store whatever the user is typing.
  3. We need a Component that displays a gif.
  4. We will to pass that component a property (prop) that changes based on what the user has typed so that the component updates.

Step 1: We’ll need a text input field.

This is quite easy for us, just use an tag:

Step 2: We will need a way to store whatever the user is typing.

This is a bit more difficult, we need some way to capture what the user is typing and store that value (are you thinking about a variable??? Good!).

In the case of web applications, events are fired inside the browser window, and tend to be attached to a specific item that resides in it — this might be a single element, set of elements, the HTML document loaded in the current tab, or the entire browser window. There are a lot of different types of events that can occur, for example:

  • The user clicking the mouse over a certain element or hovering the cursor over a certain element.
  • The user pressing a key on the keyboard.
  • The user resizing or closing the browser window.
  • A web page finishing loading.
  • A form being submitted.
  • A video being played, or paused, or finishing play.
  • An error occurring.

For this, we will need to use something called an Event Handler, there are a lot of different event handlers in JavaScript. Here are some of the most common. It’s unlikely you’ll need any more than these throughout the next few weeks.

note: in React, we use camelCase for these names, you’ll see an example below

Which event handler do you think we’ll need to put on our tag in order to store whatever the user is typing? Well, since we don’t have a button in this example, let’s use the event handler.

Here are the steps I usually take to handle events:

  1. Choose your event handler (normally or )
  2. Create a function that accepts one argument (I normally call it , some people name it).
  3. Write whatever you need inside your new function
  4. Have your function execute whenever that event happens.

Below is an example, try typing in the input box and see what the console outputs (remember to use your browser’s console, not the console in repl.it!:

The Event Object

The event object is an object we can access using JavaScript that gives us the ability to read different types of events, such as user input, mouse clicks, and the value of what the user has typed in an input box.

Step 3: We need a Component that displays a gif.

Now that we have a way to capture what the user is inputting into the text field, let’s create a simple component that displays a gif.

Challenge 2!

In this next challenge, see if you can get the component in the example above to display a gif only if the property value you pass has a value (e.g., it’s not empty).

Step 4: We will to pass that component a property (prop) that changes based on what the user has typed so that the component updates.

If you were able to pass the challenge above, you probably can guess what we’ll need to do in order to complete our application. We need some way to store what the user is typing and have the property we pass to the Profile component change based on this.

To do so, we need one final BIG concept — don’t worry if this is confusing at first, we will spend most of the remainder of the semester practicing.

State

One way to think about state in a web application, is to think about what happens when you go to a web page like the New York Times. Provided you’re not logged in, then you should see the same version of the page that I see, our applications (in this case, the HTML and CSS and JavaScript that make up nytimes.com) have the same exact state.

On the other hand, if you were to log in, and I did not, your version of the website would likely have a different state, you might see a ‘welcome Cindy’ message, or maybe you’d see some more stories, or a completely customized news feed.

Going one level deeper, you can think about application state as the state of ALL of your variables in your application, for example, if you had a true/false (boolean) variable like this:

Then you could say that the state of your application includes , and proceed to have your app do or how something else as a result. Hopefully you can now see how this concept of state can make applications very interactive and personalized.

useState (a preview)

This week, we’re going to learn just enough about useState in order to copy code from one application that uses useState, into another application. We’ll do this by using a “magic” line of code that has some parts that you change (the variable names, and the initial value), and some parts that you don’t (, the brackets, and the function name ).

In the lab, we demonstrated this application: https://repl.it/@ChristianGrewel/State-and-Interaction-1. Study the source code. It contains a line:

const [count, setCount] = useState(0);

This defines two variables:

  1. holds a value. Initially, it has the value 0 (because this is the argument to .) After is called,
  2. is a function. It can be called, with a value as an argument, to set the value of .; for example, . The new value doesn’t take effect immediately. It becomes the new value of count the next time that ExampleInteraction is called, will have the value 1, forever after until is called with a different value (and then that value will become the value of the next time ExampleInteraction is run).\

useState: Minimum Viable Knowledge

Here’s everything that you need to know in order to use :

  1. Where to find some example code (the Lab 8 demonstration application https://repl.it/@ChristianGrewel/State-and-Interaction-1), that you can adapt in order to use it.
  2. Your React application has a line . Change it to .
  3. Copy the line from the example application, into your component that contains an event handler, and therefore needs to make use of application state. Optionally change the names and to names that make sense for your application, and optionally change the to an initial value that makes sense for your application.
  4. Now wherever you need to get the state, use (or whatever you have changed this name to). Wherever you need to set the state, use (or whatever you have changed this name to).

An (Almost) Equivalent

Here’s an alternative to in the example app. This implementation doesn’t use (and it doesn’t quite work). You may find this useful in order to understand how to use the and that provides. (If you don’t, you can stop reading here.)

// this code doesn't work
function ExampleInteraction() {
let count = 0;
function setCount(newCount) {
count = newCount;
}
function handleClick() {
setCount(count + 1);
}
... // the rest of the function is the same
}

Differences from the example app:

  • The example app uses to define a variable and a function . The alternative uses to define a variable, and defines a function that uses assignment () to update its value.
  • The example app works. The alternative is broken.

Next week, we’ll talk about what the example app gets right, that the alternative gets wrong. If you’re curious, you can simple try it:

Optional activity 1: Make a copy of the Lab 8 example app, above. Replace its version of by the alternative. What isn’t working?

Optional activity 2: Add some calls to , and inside and . See if you can use this to figure out what’s going on.

Coming Attractions

Next week, we will go into more depth about:

  • The “magic” line. It’s not entirely magical. We’ll unpack it a little bit.
  • Why we use in order to instruct React to provide a variable and a function that we can use to read and set our state variable. Why not just use to define a variable, and (or ) to change its value? There are a couple of good reasons, that we’ll go into later.

(to be continued next week in part 2: State in React Web Applications)

References

The section Declaring a State Variable of the React documentation page Using the State Hook contains additional additional discussion of . Some parts of this documentation are aimed at an audience that is familiar with the of JavaScript es (as in, Object-Oriented Programming, or OOP) to define React components. If you read this and you are not familiar, from materials outside of this course, with JavaScript classes and React class components, you may find these parts of the documentation more confusing than enlightening.

applab-fall-2019

App Lab, Fall 2019, NYU Shanghai

Christian Grewell

Written by

Hi! My name is Christian Grewell, I grew up in Portland, Oregon playing music, programming video games, building computers and drinking coffee. I live in China.

applab-fall-2019

App Lab, Fall 2019, NYU Shanghai

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade