[toc]
Programs may be though of as being made up of two things:
- Data
- Operations that manipulate data
This chapter will focust on the Data point.
Data can be stored in a program in various ways. The most basic unit of data is a value, a specific piece of data such as a word or number. Each value belongs to a category called a data type. We'll see many different data types throughout this course. The first two to become familiar with are number and string types.
Numeric values such as 4 and 3.3 are Number type. Sequences of characters inclused in quotes, such as Hello, World!, are String type. Strings must be enclosed in single or double quotes. (NOTE: You can now use back tick quotes! More on this later!)
If you are not sure what data type a value has, you can use the typeof operator. An operator is an entity similar to a function that carries out some kind of action, though the syntax is different from that of functions.
📄 SYNTAX: Although you can use
typeofwithout parenthesis following it, it is recommended that you do so.typeof "Hello, World"; // ✅ (Acceptable) typeof("Hello, World"); // ✅ (Recommended)Both of those examples will return
string.
Let's try out the typeof operator.
console.log(typeof "Hello, World!"); // string
console.log(typeof 17); // number
console.log(typeof 3.14); // numberIf you quote numbers, they are no longer number but strings.
console.log(typeof "17"); // string
console.log(typeof "3.2"); // stringStrings can be single or double quoted.
console.log(typeof 'This is a string'); // string
console.log(typeof "And so is this"); // stringDouble quoted strings can have single quotes inside them and single quote string can have double quotes inside them. JavaScript won't care if ouuse single or double quotes to surroind your string. Once it has parsed the text of your program or command, the way it stores the value is identical in call cases, and the surrounding quotes are not part of the value.
console.log('We are the Knights Who Say "Ni!"'); // ✅
console.log("No! Not the the Knights who say 'Ni!'"); // ✅
console.log("Oh my Lord! It's Them!"); // ✅
console.log('Don't Say that word!'); // ❌ (Odd numer of quotes)When you type large integer values, you might be tempted to use commans between three groups of digits as in 42,000. But this is NOT a legal integer in JavaScript, but it does mean something else in the console.log which is legal.
console.log(42000); // 42000 // ✅ (Proper)
console.log(42,000); // 42 0 // ✅ (Outputs 42 and 0)JavaScript chose to treat 42,000 as a pair of values. In fact, the console.log function can print any number of values as long as you separate them by commas. Notice that the values are separated by spaces when they are displayed.
console.log(42, 17, 56, 34, 11, 4.35, 32); // 42 17 56 34 11 4.35 32
console.log(3.4, "hello", 45); // 3.4 'hello' 45ℹ️ NOTE: Remember not to put commas or spaces in your integers, no matter how big they are. Also, revisit what we said in How Programs Work: formal languages are strict, the notation is concise, and even the smallest chage might mean something quite different from what you intended (literal!)
Every programming langauge has a type system, which is the set of rules that determine how the languages deal with data of different types. Namly, how values are divided up into different data types is one characteristic of a type system.
In many programming laugnages, integers (whole numbers) and floats (short for floating-point numbers, or decimals) are considered to be different data types. For example, in Python 42 is of the int (integer) data type, while 42.0 (with that decimal and zero at the end) is of the float data type.
ℹ️ NOTE: While JavaScript does not distinguish between flaots and integers, at times you may wish to do so. For examples, an inventory-tracking program stores items and the number of each number in stock. Since a store can't have 3.5 shirts in stock, the programmer makes the quantity of each item integer values as opposed to floats.
When discussing the difference between programming languages, the detail of the type systems are one of the many factors that programmers consider. There are other aspects of type systems beyound just how values are categoriezed. We'll explore these later.
❓ Question: Which of these is not a data type in Javascript? a.
numberb.stringc.letter⬅️ d.object❗ Answer: c.
letteris not a data type!
Sometimes it's necessary to convert values from one type to another. JavaScript provides a few simple functions that will allow us to convert values to different data types. The function Number and String will attempt to covert their arguments into types number and string, respectively. These are called type conversion functions.
ℹ️ NOTE: I added these subsections.
The Number function can take a string and convert it into an integer.
console.log(Number("2345")); // 2345
console.log(typeof Number("2345")); // 'number'
console.log(typeof(Number("2345"))); // 'number'
console.log(Number(17)); // 17
console.log(Number("23bottles")); // NaNWhoops! Loop like that last one didn't convert into a number. Instead it returned NaN or "not a number". NaN is a special value that represents that state of not being a number. The example on line 5 shows that a string has to be a syntactically legal number for conversion to go as expected. Values like "34" and "-2.5" will convert into number 34 and -2.5, but "Alexander Hamilton" will return NaN. If the value cannot be cleanly converted to a number then NaN will be returned.
The type conversion function String turns its argument into a string. Remember, that when we print a string, the quotes may be removed. However, if we print the type, we see that it is definitely 'string'.
console.log(String(17)); // '17'
console.log(String(123.45)); // '123.45'
console.log(typeof String(123.45)); // 'string'
console.log(String("23bottles")); // '23bottles'This time the "23bottles" example returns a string!
❓ Question: Which of the following strings result in
NaNwhen passed toNumber? (Feel free to try running each of the conversions). a.'3'b.'three'⬅️ c.'3 3'⬅️ d.'33'❗ Answer: b and c.
console.log(Number('3')); // 3 console.log(Number('three')); // NaN console.log(Number('3 3')); // NaN console.log(Number('33')); // 33
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. Recall that a value is a single, specific piece of data, such as a specific number or string. Variables allow us to store values for later.
A useful visual analogy for how a variable works is that a label points to a piece of data.
🧜♀️ Mermaid Note: We can't seem to insert double quotes, so in the below figure, let's fake it with two sets of single quotes on each side for now. (:reminder_ribbon: TODO: Find out why we can't use double quotes later. ) This note isn't important to the lesson. It's something for me to fix later.
graph LR
var[programmingLanguage] --> val[''JavaScript'']
In the above figure, the name programmingLanguage points to the string value "JavaScript". This is more of an analogy, since it also represents how a variable and its value are stored in a computer's memory. With this analogy in mind, let's look at how we can formally create variables in JavaScript.
To create a variable in JavaScript, create a new name for the variable and precede it with the keyword let:
let programmingLanguage;This creates a variable named programmingLanguage. The act of creating a variable is referred to as variable declaration or simply declaration.
Once a variable has been declared, it may be given ("assigned") a value using an assignment statement, which uses the equal operator (=) to give an variable a value.
let programmingLanguage;
programmingLanguage = "JavaScript";The act of assigning a variable a value for the first time is called initialization. Often when we do this, we say we "set the intial value" or "we initialize a variable."
Let's look at those two lines in the previous code example in detail.
The first line creates a variable that does not yet have a value. The variable is a label that does not point to any data. The result of let programmingLanguage;.
graph LR
var[programmingLanguage]
The second line assigns the variable as a value, which connects the name to the given piece of data. The result of programmingLanguage = "JavaScript";.
graph LR
var[programmingLanguage] --> val[''JavaScript'']
It is possible to declare and initialize a variable with a single line of code. This is the most common way to create a variable.
let programmingLanguage = "JavaScript";🏴 Old and Busted, New Hotness: "What about
var?" You will see some programmers usevarto create a variable in JavaScript, like this:var programmingLanguage = "JavaScript";While this is valid syntax, it is recommended to use the new
letkeyword instead of the oldvar. Usingvaris old JavaScript syntax, and it differs fromletin important ways that we will learn about later. When you see examples usingvar, useletinstead. (It might be a good idea to replace thevars withlets. We'll find out later if that's a good idea.) (:reminder_ribbon: TODO: ASK!)If you are curious about the differences, read about the differences between
varandlet.
To give a variable a value, use the assignment operator (=). This operator should not be confused with the concept of equality*, which expresses whether two things are the "same". (We will see later that equality uses the === operator.) The assignment statement is a name, on the left-hand side of the operator, with a value, on the right-hand side. This is why you will get an error if you try to run the following example:
"JavaScript" = programmingLanguage; // ❌An assignment statement must have the name on the left and the value on the right.
ℹ️ NOTE: When you thing of assignment think of this: :white_check_mark:
programmingLanguageis assigned'JavaScript'. :white_check_mark:programmingLanguagegets/has the value'JavaScript'. Don't think of the word "equals" or "is equal to" as it implies equality. :x:programmingLanguageequals'JavaScript'.OK, this aside is bunk. But let's roll with it for now.
⚠️ Warning: What if you leave offletwhen declaring a variable?programmingLanguage = "JavaScript";JavaScript won't complain or throw an error. In fact, creating a variable without
letis valid syntax, but it results in very different behavior. Such a variable will be treated as a global variable, which we will discuss later.The main point to keep in mind for now is that you should always use
letunless you have a specific reason not to do so.
After a variable is created, it may be used later in a program anywhere a value may be used. For example, console.log prints a value, but we can also give console.log a variable. In the following example, line 1 will return the same results as line three because of line 2.
console.log("Hello, World!"); // 'Hello, World!'
let message = "Hello, World!";
console.log(message); // 'Hello, World!'When we refer to a variable name, we are evaluating the variable. The effect is just as if the value of the variable is substituted for the variable name in the code when executed.
let message = "What's up, Doc?";
let n = 17;
let pi = 3.14159;
console.log(message); // "What's up, Doc?"
console.log(n); // 17
console.log(pi); // 3.14159In each case, the printed result is the value of the variable.
Like values, variables also have types. We determine the types of a variable the same way we determine the type of a value using typeof.
// continuing from the previous code example
console.log(message); // 'string'
console.log(n); // 'number'
console.log(pi); // 'number'The type of a variable is the type of the data it currently refers to.
We use variables in a program to "remember" things, like the current score at the football game. As their name implies, variables can change over time, just like the scoreboard at a football game. You can assign a value to a variable, and later assign it to a different value.
let day = "Thursday";
console.log(day); // "Thursday"
day = "Friday";
console.log(day); // "Friday"
day = 21;
console.log(day); // 21Notice, that we changed the value of day three times, and in the third assignment, we even give it a value that is of a different data type.
A great deal of programming involves asking the computer to remember things. For example, we might want to keep track of the number of missed calls on you phone. Each time another call is missed, we can arrange to update a variable so that it will always reflect the correct total of missed calls.
ℹ️ NOTE: We only use
letwhen declaring a variable, that is, when we created. We do NOT useletwhen reassigning the variable to a different value. In fact, doing so will result in a error.
❓ Question: What is printed when the following code executes?
let day = "Thursday"; day = 32.5; day = 19; console.log(day);a. Nothing is printed. A runtime error occurs. b.
Thursdayc.32.5d.19⬅️❗ Answer: d.
❓ Question: How can you determine the type of a variable? a. Print out the value and determine the data type based on the value printed. b. Use
typeof. ⬅️ c. Use it in a known equation and print the result. d. Look at the declaration of the variable.❗ Answer: b.
❓ Question: Which line is an example of variable initialization? (Note: only one line is such an example.)
let a; a = 42; a = a + 3;❗ Answer: Line 2.
Line 1 is where the variable is declared, line 2 is where the variable is initialized. Line 3 is where the variable is updated.
The previous section coverd creating, evaluating, and reassigning variables. This section will cover some additional, more nuanced topics relating to variables.
One of the key featueres of variables we've discussed so far is their ability to change value. WE can create a variable with one value then reassign it to another value.
let programmingLanguage = "JavaScript"; // ✅
programmingLanguage = "Python"; // ✅In some situation, we want to create variables that CANNOT change value. Many programming languages, including JavaScript, provide mechanisms for programmers to make variables that are constant. A variable which you cannot change the value once it is set is called a constant and it is declared with the const keyword instead of let.
const appName = "Get It Done"; // ✅
appName = "Git'er done!"; // ❌ TypeError: Assignment to constant variable.As we've seen in other examples--such as tyrping to declare a variable twice, using incorrect syntax, or failing to enclose strings in quotes--JavaScript prevents undesired code from executing by throwing an error.
As you may have discovered already, not just any sequence of characters is a valid variable name. For example, we can't declare variables with spaces in them. First, that would make it two variables. Secondly, if you wanted to create two variables on the same line, you would need to separate them with a comma.
let application name; // ❌ SyntaxError: Unexpected identifier.In this case, "identifier" is a nother term for a variable name. So this error message means that the variable name is not valid or "unexpected".
JavaScript provides a broad set of rules for naming variables, but there is no reason to go beyond a few easy-to-remember guidelines:
- No Whitespaces or special characters. Use only number (
0-9), lowercase letters (a-z), uppercase letters (A-Z) and underscore (_). Do not use special characters, emojis, or whitespaces (spaces, tabs, etc.) - Do not start a variable name with a number. An addendum to rule 1, variables may have numbers in them, just not as th first character of a variable name.
- Avoid starting variable names with a underscore. Doing so is a convention used by some JavaScript developers to mean something very specific about the variable and it should be avoided.
- Do not use keywords. Javascript has a list of reserved words that are used by the language itself. These are called keywords. We'll discuss them later in this chapter.
By following these guidlines, you will prevent creating illegal variable names. You should strive to create good variable names, which we'll touch on this next section.
🤪 Rule 3 says "don't start variables with underscores, but what about Lodash?" Lodash is a JavaScript library much like jQuery, that adds extensible functionality to JavaScript. More than likely the Lodash people (who couldn't use the dollar sign that jQuery uses), decided to ignore rule 3 when they wanted to make their own library. To my knowledge, this course won't be using either library. Besides, you should learn how to make JavaScript do things these "libraries" do on your own, and more importantly take advantage of learning how some of the standard and new features JavaScript has does what libraries like those do.
Writing good code is about more than writing code that simply workd and accomplishes the task at-hand. It's also about writing code that can be read, updated, and maintained as easily as possible. How to write code that achieves these goals is a theme we will constantly visit.
One of the primary ways writing bad code happens is by using bad variable names. For example, consider the following program. While we havn't introduced each of the components used here, you should be able to come to a general understanding of the new components.
let x = 5;
const y = 3.14;
let z = y * x ** 2;
console.log(z);Understanding what this program is trying to do is not obvious, to say the least. (Well, at least not to anyone who is a math geek and can see that they were trying to compute the area of a circle.) The main problem is that the variable names x, y, and z are not descriptive. They don't tell us anythng about what they represent, or how they will be used.
Let's add a fifth rule to the list in the previous section:
- Variable names should be descriptive. Variables names should describe what they are for, providing context about the data they contain and how they will be used.
Let's try writing that program again, this time with better variable names.
let radiusOfCircle = 5; // a simple 'r' would have also sufficed.
const pi = 3.14; // I have a couple of things to say about this after this example.
let areaOfCircle = pi * radiusOfCircle ** 2;
console.log(areaOfCircle);With improved variable names, now it becomes clear that the program is calculating the area of a circle of radius 5.
💡 Tip: When considering program readability, think about whether or not your code will make sense to another programmer. It is not enough for code to be readable by only the programmer that originally wrote it.
There is one more aspect of naming variables that you should be aware of, and that is conventions used by professiona programmers. Conventions are not formal rules, but are informal practices adoped by a group.
There are a variety of types of conventions used by different groups of programmers. One common type of convention is that programmers that specialize in a specific language will adopt certain variable naming practices.
In Javascript, most programmers use the camel case style, which stipulate the variable names consist of names or phrases that:
- Are joined together to omit spaces.
- Start with a lowercase letter.
- Capitalize each internal word.
In the example from the privious section, the descriptor "area of circle" became the variable name areaOfCircle. This convention is called camel case because the capitalization of internal words is reminiscent of a camel's humps. 🐫 Another common name for this convention is lower camel case, since names start with a lowercase letter.
ℹ️ NOTE: Different programming languages often have different variable-naming conventions. For example, in Python, the convention is to use all lowercase letters and separate words with underscores, as in
area_of_circle.
WE will use the lower camel case convention throughout this course, and strongly encourage you to do so as well.
ℹ️ NOTE: I added this section. It's not part of the original LC outline.
One thing this course overlooked is something that probably should be practiced with constant variables that many languages, including JavaScript do: CAPITALIZE_CONSTANT_VARIABLES.
As you will find out later when we tinker with the Math object, some built-in variables are written in all caps and have underscorse in them. This case should be used for constants.
- Camel Case:
let firstNameInitial = "S";l`- Pascal Case (a.k.a. Class Case):
let FirstNameInitial = "S";- Snake Case:
let first_name_last_initial = "Shawn";(What we just talked about, but for let.)Kebab-Case:🙅♂️ DON'T DO THIS!let first-name-first-initial = "Shawn";`
Our last note on naming variables has to do with a collection of words that are reserved for by the Javascript langauge itself. Such word are called keywords, or reserved words.
Any word that is formally paort of the JavaScript language syntax is a keyword. So far, we have seen only four keywords: let, const, var, and typeof.
⚠️ WARNING: Whileconsoleandconsole.logmay seem like keywords, they are actually slighly different things. They are entities (an object and a function, respectively) that are available by default in most JavaScript environments.
Attempting to use a keyword for anything other than it's intended use will result in an error.
let const; // ❌ SyntaxError: Unexpected token constℹ️ NOTE: Most code editors will highlight keywords in a different color than variables or other parts of your code. This should serve as a visual cue that a given word is a keyword, and can help prevent mistakes.
The following table provides a list of keywords as well as a few other words you should avoid using as variable names.
|
|
|
The following list indicates what each of the superscript numbers mean in the table above. Most of the items that have a superscript number next to them are reserved either as future reserved keywords or they are traditionally reserved in other languanges.
- Always reserved
- Only reserved when they are found in strict mode code.
- Only reserved when they are found in module code.
- Reserved as ture keywords by older ECMAScript specifications (ECMAScript 1 thorugh 3.)
- Literals
null,true, andfalsecannot be used as identifiers in ECMAScript. - A few other words that probably should be in this list because some languages use them. (I added these.)
- Identifiers with special meaning.
For more info about keywords, read this page.
❓ Question: Which is the best keyword for declaring a variable in most situations? a.
varb.let⬅️ c.constd. (no keyword)❗ Answer: b. while
varis still use in most places,letis the new standard.
An expression is a combination of values, variable, operators, and calls to functions. An expression can be thought of as a formula that is made of multiple pieces.
The evaluation of an expression produces a value, known as the return value. We say that an expression returns a value.
Expressions need to be evaluated when the code executes in order to determine the return value, or specific piece of data that should be used. Evaluation is the process of computing the return value.
If you ask JavaScript to print an expression using console.log, the interpretor evaluates the expression and displays the result.
console.log(1 + 1); // 2This code prints not 1 + 1 but rather the result of calculating 1 + 1. In other words, console.log(1 + 1) prints the value 2. This is what we would expect.
Since evaluating an expression produces a value, expressions can appear on the right-hand side of an assignment statement.
let sum = 1 + 2;
console.log(sum); // 3The value of the variable sum is the result of evaluating the expression 1 + 2, so the value 3 is printed.
A value all by itself is a simple expression, and so is a variable. Evalulating a variable gives the value that the variable refers to. This means that line 2 of the example above also contains the simple expression sum.
Now that we cna store data in variables, let's explore how we can generate new data from existing data.
An operator is one of more characters that represents a computation, like addition, subtraction, multiplication, or division. The values an operator wors on are called operands.
For example, in the calculation 20 + 32, the operator is the plus sign (+) and the operands are 20 and 32.
We'll list what the various symbols mean later as well as the order of which they are processed in.
console.log(2 + 3); // 5
console.log(2 - 3); // -1
console.log(2 * 3); // 6
console.log(2 ** 3); // 8
console.log(3 ** 2); // 9We use the same terminology as beofre, stating that 2 + 3 returns the value 5. Arthmetic symbols mean in Javascript what they mean in mathematics. The asterisk (*) and the double asterisk (**) are the symbols of multiplication and exponentiation respectively. Division uses the slash / as an operator.
When a variable name appears in the place of an operand, it is replaced with the value it refers to before the operation is performed.
let minutes = 645;
let hours = minutes / 60;
console.log(hours); // 10.75Ins summary, operators and operands can be combined to create expressions that are evaluated upon execution.
Some of the most commonly-used operators are the arthmetic operators, which carry out basic mathematical operations. These may behave exactly as you are used to, thorugh the modulus operator (%) may be new to you.
Modulus is the remainder of integer division. The division operator (/) produces a number called the quotient. Let's look at it more visually.
$$
\begin{aligned}
\frac{dividend}{divisor} &= quotient + \frac{remainder}{divisor}
\end{aligned}
$$
The quotient should be the whole number of the number of what you get when you divide something. That is if we multiplied the quotient by the divisor (the number we divide by) the result should be the dividend minus the remainder.
$$
quotient \times divisor = dividend - remaninder
$$
Let's use a simple example: 6 divided by 2 is 3. Let's add something extra to that expression and say "6 divided by 2 is 3 remainder 0". Thus, 7 divided by 2 is 3 remainder 1 because 2 times 3 plus 1 is 7.
$$
\begin{aligned}
6 \div 2 &= 3 \mod 0 \
7 \div 2 &= 3 \mod 1
\end{aligned}
$$
The modulous value will alway be an integer between 0 and one less than the divisor.
$$
\begin{aligned}
6 \div 3 &= 2 \mod 0 \
7 \div 3 &= 2 \mod 1 \
8 \div 3 &= 2 \mod 2 \
9 \div 3 &= 3 \mod 0
\end{aligned}
$$
ℹ️ NOTE: I subdivided this section.
For arthmetic operators, the same rules of PEMDAS/BODMAS apply in JavaScript.
- Parthethesis/Brackets
- Exponents/Order
- Multiplication
- Division (and Modulus)
- Addition
- Subtraction
ℹ️ NOTE: The exponet operator (
**) operates from right-to-left rather than left-to-right like all the other arithmetic operators work. This direction of how an operator works is called associativity. This means that the right-most**operator will be applied first.In the following example,
2**3**2is the same as saying2**(3**2)which produces2**8which will produce512as the answer. In order to have the left-most**to take precedence, the2**3part needs to be encapsulated in parenthesis, which has a higher precedence than exponentation.console.log(2 ** 3 ** 2); // 512 console.log((2 ** 3) ** 2); // 64
ℹ️ NOTE: I've moved all this information to the Operators file in the Computer Science directory.
GO READ MY OPERATORS DOCUMENT!
❓ Question: What is the value of the following expression?
16 - 2 * 5 / 3 + 1a. 14 b. 24 c. 3 d. 13.666666666666666666666 ⬅️
❗ Answer: d. $$ \begin{aligned} 16 - \underline{2 * 5} \div 3 + 1 && \text{Given} \ 16 - \underline{10 \div 3} + 1 \ \underline{16 - 3.\overline{3} + 1} && 3.\overline{3} = 3.3333\ldots \ 13.\overline{6} && \blacksquare \end{aligned} $$
❓ Question: What is the output of the code below?
console.log(1 + 5 % 3);❗ Answer: 3 $$ \begin{aligned} 1 + \underline{5 % 3} && \text{Given} \ \underline{1 + 2} && \because 5 \div3 = 1 \mod 2 \ 3 && \blacksquare \end{aligned} $$
❓ Question: What is the value of the following expression?
2 ** 2 ** 3 * 3a. 768 b. 128 c. 12 d. 256
❗ Answer: a. $$ \begin{aligned} 2^{2^3} \cdot 3 && \text{Given} \ 2^8 \cdot 3 \ 256 \cdot 3 \ 768 && \blacksquare \end{aligned} $$
Mays Gilliam: I asked my niece the other day what 4 plus 4 was. She said 44. Crowd Member: It is!
--Head of State (2003)
So far we have only seen operators that work on operands which are of type number, bu there are operators that work on other data types as well. In particular the + operator that can be used with string operands to concatentate, or join together two strings.
console.log("Launch" + "Code"); // "LaunchCode"
console.log(1 + 1); // 2
console.log("1" + "1"); // "11"This example demonstrate that the the operator + behaves differently based on the data type of its operands.
So far we've only seen examples of operators working with data of like types. For example 1 + 1 and "1" + "1", both operands are of type number and string, respectively. We'll deal with "mixed" operation later.
Back in 4.6.3.2., there were a list of operators whose precedence was third from the bottom. These are the assignment operators. The one you already know is the = sign which we used to assign values to variables.
let x = 1;
x = x + 1;
console.log(x); // 2Compound assignment operators are similar to the assignment operator, but it's more like a shorthand for specific operators.
let x = 1;
x += 1; // same as x = x + 1
console.log(x); // 2| Shorthand | Meaning |
|---|---|
x = y |
x = y |
x += y |
x = x + y |
x -= y |
x = x - y |
x **= y |
x = x ** y |
x *= y |
x = x * y |
x /= y |
x = x / y |
x %= y |
x = x % y |
x <<= y |
x = x << y |
x >>= y |
x = x >> y |
x >>>= y |
x = x >>> y |
x &= y |
x = x & y |
x ^= y |
x = x ^ y |
x |= y |
x = x | y |
console.log works for printing static (unchanging) messages to the screen. If we wanted to print a phrase greeting a specific user, then console.log("Hello, Dave."); would be OK as long as Dave is the actual user.
What if we wanted to great someone else. We could change the string inside the parethesis to be 'Hello, Jerry' or 'Hello, Newman' or any other name we need. But this is inefficient. Also, what ifw we don't know the name of the user beforehand? We need to make our code more general and able to respond to different condition.
It would be great if we could ask the user to enter a name (as a string), store that string into a variable, and then print a personalized greeting using console.log. Variables to the rescue!
To personalize the greeting, we have to get input from the user. This involves displaying a prompt on the screen (e.g. "Please enter a number: "), then waitin for the user to respond. Whatever information the user enters gets stored for later.
As we saw earlier, each programming laugnage has its own way of accomplishing the same task. For example, in Python we say input("Pleas enter your name: "). In C# we use Console.ReadLine();
JavaScript also has a built-in mode for collecting data from the user, called readline-sync. Unfortunately, using this module requires more than a single line of code.
Gathering input from the user requires the following setup:
const input = require('readline-sync');
let info = input.question("Question text... ");In line 1, const input = require('readline-sync') pulls in all the functions that allow us to get data from the user and assigns them to the variable input.
Recall that const ensure that input cannot change.
💡 TIP: Ideally, you should probably put any
requires near the top when importing stuff.
This section was about what was on line 3.
To display a prompt and wiat for a response, we use the following syntax:
let info = input.question("Question text... ");When JavaScript evaluates the expression, it followis these instructions:
- Display
Question texton the scree. - Wait for the user to respond.
- Store the data in the variable
info.
For our greeting program, we would code let name = input.question("Enter your name: ");. The user enters a name and presses Enter. When this happens, any text entered is collected by the input function and stored in the name.
ℹ️ NOTE: There's a Repl.it here to create! Do it!
const input = require('readline-sync');
let name = input question("Enter your name: ");
console.log("Greetings, " + name + "!");Note that after entering the name, the program doesn't actually do anything with the info. If we want to print the data as part of a message, we need to put name in a console.log statement.
By storing the user's name inside name, we gain the ability to hold onto data and use it when and where we see fit.
There is one very important quirk about the input function that we need to remember. Given console.log(7 + 2);, the output would be 9. But here's what happens when we run this program:
const input = require('readline-sync');
let num1 = input.question("Enter a number: "); // 3
let num2 = input.question("Enter another number: "); // 8
console.log(num1 + num2); // 38 ❌See the problem? Our two inputs concatenated instead of added. So how do we fix that? Type coversion.
const input = require('readline-sync');
let num1 = input.question("Enter a number: "); // 3
let num2 = input.question("Enter another number: "); // 8
num1 = Number(num1);
num2 = Number(num2);
console.log(num1 + num2); // 11 ✅Nice...but let's try something better. I think Python and Java do this.
const input = require('readline-sync');
// COMBO!
let num1 = Number(input.question("Enter a number: ")); // 3
let num2 = Number(input.question("Enter another number: ")); // 8
console.log(num1 + num2); // 11 ✅Huh, whadayaknow. That what that "Try It" 🧩 section was. Good to know.
❓ Question: What is printed when the following program is run?
const input = require('readline-sync'); let info = input.question("Please enter your age: "); //The user enters 25 console.log(typeof info);a.
string⬅️ b.numberc.infod.25❗ Answer: a.
❌ CENSORED! Sorry, I'm not going to rewrite these things verbatum. I figure this one is good enough for now.
"Now, this is the plan. Get your a** to Mars." --Carl Hauser, Total Recall (1990)
Exercises appear regularly in this book. Just like the concept check, these exercises will check your understanding of the topics in this chapter. They also provide a good practice for the new skills.
Unlike the concept checks, you will need a code edotr to complete this exercise. Hopefully, you makde your Repl.it account as part of the prep work.
If you are enrolled in a LaunchCode program, access to the studio (4.10.) by floowing the Repl.it classroom links posted in your class at https://learn.launchcode.org/.
If you are working through this material on your own, use this repl.it link.
Use the information given below about your space shuttle to complete the exerciess:
| Data | Value |
|---|---|
| Name of the space shuttle | Determination |
| Shuttle Speed (mph) | 17,500 |
| Distance to Mars (km) | 225,000,000 |
| Distance to the Moon (km) | 384,400 |
| Miles per kilometer | 0.621 |
- Declare and assign variables
Delcare and assign a variable for each item in the list above.
Hint: When declaring and assigning your variables, remember that you will need to use that variable throughout the rest of this exercise. Make sure that you are using the correct data type!
- Print out the type of each variable
For each variable you declare in part A, use the
typeofoperator to print its type to the console, one item per line.Click "Run" (in repl.it) and verify that your code works before moving to part C.
- Calculate a space mission!
We need to determine how many days it will take us to reach Mars.
- Create and assign a mile to Mars variable. You can get the miles to Mars by multiplying the distance to Mars in kilometers by the miles per kilometer.
- Next, we need to create a variable to hold the hours it would take to get to Mars. To get the hourse, you need to divide the miles to Mars by the shuttle's speed.
- Finally, declare a variable and assign it the value of the days to Mars. In order to get the days it will take to reach Mars, you need to divide the hours it will take to reach Mars by 24.
- Print out the results of your calculations
Using variables from above, print to the screen a sentance that says
"_____ will take ___ days to reach Mars."Fill in the blanks with the shuttle name and the calculated time.Click "Run" (in repl.it) and verify that your code works before moving on.
- Now calculate a trip to the Moon
Repeat the calculations, but this time determine the number od days it would take to travel to the Moon and print to the screen a sentence that says
"_____ will take ___ days to reach the Moon."
❌ CENSORED! Sorry, I'm not going to rewrite these things verbatum.
❌ CENSORED! Nope.
❌ CENSORED! Nuh-uh.
❌ CENSORED! Sorry.
❌ CENSORED! Can't do that.
When finished, show your code to your TA so they can verify your work.
If you do not finish before the end of class, login to Repl.it and save your work. Complete the studio at home, the compy the URL for your project and submit it to your TA.
❌ CENSORED! No way, José.
🏁 Finally! That was a TON of work. Up Next: Conditionals.
#LaunchCode