JavaScript Module 1 Lecture.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Javascript Module 1 Values, Types, and Operators Inside a computer, there is only data. Comprised of 1’s and 0’s. A typical working computer has more than 30 billion bits at any time stored in RAM. On a hard disk it tends to have a few order of magnitude more. To be able to work with such quantit...

Javascript Module 1 Values, Types, and Operators Inside a computer, there is only data. Comprised of 1’s and 0’s. A typical working computer has more than 30 billion bits at any time stored in RAM. On a hard disk it tends to have a few order of magnitude more. To be able to work with such quantities of bits without getting lost, we must separate them into chunks that represent pieces of information. In a JavaScript environment, those chunks are called values. Every value has a type that determines its role. Some values are numbers, some values are pieces of text, some values are functions, and so on. To create a value, you simply declare a variable type and give that value a name. Values, Types, and Operators JavaScript has 6 types of number: Numbers (14, 4.6, 1.456e3) Strings (“Hello World!”) ○ 0 or more characters stored as a single value Boolean (True,False) Objects Functions Undefined ○ Absence of value Arithmetic The main thing to do with numbers, is well, Math! Javascript has many Operators. Which include: + Addition - Subtraction * Multiplication / Division % Modulus ○ Remainder ** Exponent Arithmetic When operators appear together without parentheses, the order in which they are applied is determined by the precedence of the operators. Multiplication comes before addition. The / operator has the same precedence as *. Likewise for + and -. When multiple operators with the same precedence appear next to each other, as in 1 - 2 + 1, they are applied left to right: (1 - 2) + 1. When in doubt. Add (brackets) Arithmetic There are 3 special numbers in Javascript. + Infiniti - Infiniti NaN The infinitis represent positive and negative infiniti. Infiniti - 1 is still infiniti. This math isn’t sound so do not put too much trust into it as it will quickly lead to the next special number not a number (NaN) Special Use Cases For Infiniti Let’s say I were to give you an assignment that says something like: “Get the max value entered by the user” How would you do that? You may create a function that compares values which may look something like the following, don’t worry too much about what this code means just yet. let returnLarger = (arr, maxNum) => { return arr.map(v => v > maxNum ? v : "").filter(Boolean) } let maxNum = 0; //TODO: Get user input for getting numbers //Call function Does anyone see a problem with this? Special Use Cases For Infinity What if the user only supplies negative numbers? Now 0 is artificially our max number. So what would be safe to use? -100? -1000? -100000000000? How about this: let returnLarger = (arr, maxNum)=> { return arr.map(v => v > maxNum ? v : "").filter(Boolean) } let maxNum = -Infinity; //TODO //Get user input for getting numbers //Call function Now no matter what, ANY number will be larger than -Infinity Strings The next data type is stings. Strings represent text and are written by enclosing their constants in quotes “Down by the bay” ‘Where the watermelon grow’ You can put almost anything between quotes as long as you match the quote type. Escape Characters Some characters have special meaning, to make it possible to include such characters in a string, the following notation is used: whenever a backslash (\) is found inside quoted text, it indicates that the character after it has a special meaning. This is called escaping the character. “Good\nMorning” "A newline character is written like \"\\n\"." String Literals Strings written with single or double quotes behave very much the same—the only difference is in which type of quote you need to escape inside of them. Backtick-quoted strings, usually called template literals, can do a few more tricks. Apart from being able to span lines, they can also embed other values. `half of 100 is ${100 / 2}` When you write something inside ${} in a template literal, its result will be computed, converted to a string, and included at that position. The example produces “half of 100 is 50”. String Operations Strings cannot be divided, multiplied, or subtracted, but the + operator can be used on them. It does not add, but it concatenates—it glues two strings together. The following line will produce the string "concatenate": "con" + "cat" + "e" + "nate" String values have a number of associated functions (methods) that can be used to perform other operations on them. I’ll say more about these in future lectures Boolean Values It is often useful to have a value that distinguishes between only two possibilities, like “yes” and “no” or “on” and “off”. For this purpose, JavaScript and most other languages have a Boolean type, which has just two values, true and false, which are written as those words. console.log(3 > 2) // →true console.log(3 < 2) // →false Logical Operators The && operator represents logical and. It is a binary operator, and its result is true only if both the values given to it are true. console.log(true && false) // → false console.log(true && true) // → true //The || operator denotes logical or. It produces true if either of the values given to it is true. console.log(false || true) // → true console.log(false || false) // → false Automatic Type Conversion Automatic Type Conversion If you have not noticed by now, we have not talked about variable types like we have seen in traditional languages. To declare a variable in JavaScript we use the keyword “let” let varOne = 8; //Notice I didn’t say what type I was giving the var console.log(varOne) // -> 8 varOne = "Now it's a string!"; console.log(varOne)//Now it's a string! varOne = true console.log(varOne)// true //You get the idea Automatic Type Conversion This works, as JavaScript “guesses”for us on what type the variable should be. However, this can occasionally back fire on us. let varOne = 8; let varTwo = "8"; console.log(varOne-varTwo) // 0 (As Expected) console.log(varOne*varTwo) // 64 (As Expected) console.log(varOne+varTwo) // 88 ????? //Can anyone guess why? Automatic Type Conversion What do we think the output of the following print statements are? console.log (0+true) console.log (0+false) console.log (0 == false) console.log (0 === false) console.log ("0" == false) console.log ("zero" == false) console.log(8 * null) Automatic Type Conversion console.log (0+true) //1 console.log (0+false) //0 console.log (0 == false) //true console.log (0 === false) //false console.log ("0" == false) //true console.log ("zero" == false) //false console.log(8 * null) // 0 Expressions and Statements The simplest kind of statement is an expression with a semicolon after it. This is a program, although a useless one; 1; !false; An expression can just be something to produce a value, which can be used by other code It could display something on the screen that counts as changing the world or it could change the internal state of the machine in a way that will affect the statements that come after it. These changes are called side effects. The statements in the previous example just produce the values 1 and trueand then immediately throw them away. This leaves no impression on the world at all. When you run this program, nothing observable happens. Expressions and Statements Sometimes JavaScript allows you to omit the semicolon at the end of a statement. In other cases, it has to be there, or the next line will be treated as part of the same statement. The rules for when it can be safely omitted are somewhat complex and error-prone. In this course, it is always best practice to use a semicolon at the end of a statement to make your lives easier. Variables How does a program remember things? Thus far we have seen how to create values using old values, but this does not change the old values, you must use the values immediately or else they will disappear. To achieve this, Javascript has something called Binding aka variables let equation = 5 * 5; The keyword let tells the compiler we want to create a variable called equation and assign it the value 25. Why 25? Why not 5 * 5? Binding After a Variable has been defined, its name can be used as an expression. The value of such an expression is the value the binding currently holds. Here’s an example: let ten = 10; console.log(ten * ten); // → 100 Binding When a binding points at a value, that does not mean it is tied to that value forever. The = operator can be used at any time on existing bindings to disconnect them from their current value and have them point to a new one. let mood = "light"; console.log(mood); // → light mood = "dark"; console.log(mood); // → dark Binding Let’s look at another example. To remember the number of dollars that Luigi still owes you, you create a binding. And then when he pays back $35, you give this binding a new value. let luigisDebt = 140; luigisDebt = luigisDebt - 35; console.log(luigisDebt); // → 105 Binding You can also define a value, without assigning a value as seen below. The compiler will just reserve the space in memory and Javascript will see the value stored there as “Undefined” let luigisDebt; console.log(luigisDebt); // Undefined A single let statement can also define many things let one = 2, two = 3 ; Binding The Var keyword and const keyword work a similar way to let var name = "Ayda"; const greeting = "Hello "; console.log(greeting + name); // → Hello Ayda Var is the way bindings were declared in pre-2015 JavaScript. For now, remember that it mostly does the same thing, but we’ll rarely use it in this book because it has some confusing properties. The word const stands for constant. It defines a constant binding, which points at the same value for as long as it lives. Binding Variable names can be any word. Digits can be part of binding names—catch22 is a valid name, for example—but the name must not start with a digit. A binding name may include dollar signs ($) or underscores (_) but no other punctuation or special characters. Words with a special meaning, such as let, are keywords, and they may not be used as binding names. There are also a number of words that are “reserved for use” in future versions of JavaScript, which also can’t be used as binding names. The full list of keywords and reserved words is rather long. Binding break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import interface in instanceof let new package private protected public return static super switch this throw true try typeof var void while with yield Please don’t memorize this, you will never need to know every word. If you ever use one by mistake the compiler will give you an error telling you that you used a reserved word Binding The collection of bindings and their values that exist at a given time is called the environment. When a program starts up, this environment (or world) is not empty. It always contains bindings that are part of the language standard, and most of the time, it also has bindings that provide ways to interact with the surrounding system. For example, in a browser, there are functions to interact with the currently loaded website and to read mouse and keyboard input. Functions A lot of the values provided in the default environment have the type function. A function is a piece of program wrapped in a value. Such values can be applied in order to run the wrapped program. For example, in a browser environment, the binding prompt holds a function that shows a little dialog box asking for user input. It is used like this: prompt("Enter passcode"); Functions Executing a function is called invoking, calling, or applying it. You can call a function by putting parentheses after an expression that produces a function value. Usually you’ll directly use the name of the binding that holds the function. The values between the parentheses are given to the program inside the function. These values are called Arguments. In the prompt function, the argument displays in the prompt on the users screen. Functions In the examples, I used console.log to output values. Most JavaScript systems (including all modern web browsers and Node.js) provide a console.log function that writes out its arguments to some text output device. In browsers, the output lands in the JavaScript console. This part of the browser interface is hidden by default, but most browsers open it when you press F12 or, on a Mac, command-option-I. Return Values Showing a dialogue text box or writing text to a screen is a side effect of a function. A lot of functions are only useful because of the side effect they produce. Functions also produce values, in which they don’t have a useful side effect. Such as the max function which will take any amount of args and return the largest console.log(Math.max(5,6,7,88)); console.log(Math.min(2, 4) + 100); What do these produce? Control Flow Javascript executes from top to bottom. Let's look at this program that takes user input and returns the square of that number let theNumber = Number(prompt("Pick a number")); console.log("Your number is the square root of " + theNumber * theNumber); Do you notice anything interesting about the first line? Control Flow - Conditional Execution What about this? Will every line run? let theNumber = Number(prompt("Pick a number")); if (!Number.isNaN(theNumber)) { console.log("Your number is the square root of " + theNumber * theNumber); } Control Flow - Conditional Execution You shouldn’t have code that will just fail and not give the user an explanation as to why it errored out. Let's revise that last program. let theNumber = Number(prompt("Pick a number")); if (!Number.isNaN(theNumber)) { console.log("Your number is the square root of " + theNumber * theNumber); } else { console.log("Hey. Why didn't you give me a number?"); } Control Flow - Loops JavaScript uses loops to control how many times a piece of code may want to execute, the two main loops are for loops and while loops. Let’s review some examples in VS Code for(let i = 0 ; i < 5; i++){ console.log(i); } while(5 > 1){ //do something. //This is a bad condition as it will loop forever } Practice Exercises 1. Write a program in JavaScript that prompts the user for their name, saves it in a variable, and then displays it to the console. 2. Write a program in JavaScript that takes in two numbers from the user. If any number is less than 0, display an error and end the program. If not, add both numbers together and display the output Homework Read Chapters 1 & 2 of your textbook Complete Assignment 1

Use Quizgecko on...
Browser
Browser