JavaScript - Eloquent JavaScript
Folien in diesem Satz (41)
-
- In a JavaScript environment, those chunks are called values.
- Every value has a type that determines its role. There are six basic types of values in JavaScript: numbers, strings, Booleans, objects, functions, and undefined values.
-
- Values of the number type are, unsurprisingly, numeric values.
- Fractional numbers are written with a dot.
- For very big or very small numbers, you can also use scientific notation by adding an “e” (for “exponent”), followed by the exponent of the number: 2.998e8 - That is 2.998 × 108 = 299,800,000. Calculations with whole numbers (also called integers) smaller than the aforementioned 9 quadrillion are guaranteed to always be precise. Unfortunately, calculations with fractional numbers are generally not.
-
- The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them. Here is what they look like in JavaScript:
- 100 + 4 * 11
- The + and * symbols are called operators. + add, * Multiply, - subtract & % divide
- The rules of precedence are not something you should worry about. When in doubt, just add parentheses.
- There is also the Modulus operator - % which essentially returns the remainder of two numbers.
-
- There are three special values in JavaScript that are considered numbers but don’t behave like normal numbers.
- The first two are Infinity and -Infinity, which represent the positive and negative infinities.
- Don’t put too much trust in infinity-based computation. It isn’t mathematically solid, and it will quickly lead to our next special number: NaN.
- NaN stands for “not a number”, even though it is a value of the number type. You’ll get this result when you, for example, try to calculate 0 / 0 (zero divided by zero), Infinity - Infinity, or any number of other numeric operations that don’t yield a precise, meaningful result.
-
- The next basic data type is the string. Strings are used to represent text. They are written by enclosing their content in quotes.
- "Patch my boat with chewing gum"'Monkeys wave goodbye'
- Both single and double quotes can be used to mark strings as long as the quotes at the start and the end of the string match.
- Be careful putting quote between quotes - you need to alternate between singles and doubles.
- Escape characters such \n are also tricky - \n simply means new line. Whatever follows the \ is essentially escaped.
- This is how the string “A newline character is written like "\n".” can be expressed:
- "A newline character is written like \"\\n\"."
- Concatenation is the addition of multiple strings to create one. You use the + operator between strings.
- You can not use -,%,*,/ on strings.
- There are more ways of manipulating strings but these will be discussed later.
-
- Not all operators are symbols. Some are written as words. One example is the typeof operator, which produces a string value naming the type of the value you give it.
- console.log(typeof 4.5)
- // → number
- console.log(typeof "x")
- // → string We will use console.log in example code to indicate that we want to see the result of evaluating something. When you run such code, the value produced should be shown on the screen, though how it appears will depend on the JavaScript environment you use to run it.
- The other operators we saw all operated on two values, but typeof takes only one.
- Operators that use two values are called binary operators . While those that take one are called unary operators.
- The minus operator can be used both as a binary operator and as a unary operator.
-
- Often, you will need a value that simply distinguishes between two possibilities, like “yes” and “no” or “on” and “off”. For this, JavaScript has a Boolean type, which has just two values: true and false (which are written simply as those words).
- Here is one way to produce Boolean values: console.log(3 > 2)
- // → true
- console.log(3 console.log("Aardvark" The way strings are ordered is more or less alphabetic: uppercase letters are always “less” than lowercase ones, so "Z" is true, and non-alphabetic characters (!, -, and so on) are also included in the ordering.
-
- > Is greater than
- => Is greater than or equal to
- == equals
- !== does not equals
-
- There are also some operations that can be applied to Boolean values themselves. JavaScript supports three logical operators: and, or, and not. These can be used to “reason” about Booleans.
- 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
- Not is written as an exclamation mark (!). It is a unary operator that flips the value given to it—!true produces false and !false gives true.
-
- The last logical operator I will discuss is not unary, not binary, but ternary, operating on three values. It is written with a question mark and a colon, like this:
- console.log(true ? 1 : 2);
- // → 1
- console.log(false ? 1 : 2); // → 2
- This one is called the conditional operator (or sometimes just ternary operator since it is the only such operator in the language). The value on the left of the question mark “picks” which of the other two values will come out. When it is true, the middle value is chosen, and when it is false, the value on the right comes out.
-
- There are two special values, written null and undefined, that are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.
- Many operations in the language that don’t produce a meaningful value (you’ll see some later) yield undefined simply because they have to yield some value
-
- When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it wants, using a set of rules that often aren’t what you want or expect.
-
- A fragment of code that produces a value is called an expression.
- Every value that is written literally (such as 22 or "psychoanalysis") is an expression.
- An expression between parentheses is also an expression, as is a binary operator applied to two expressions or a unary operator applied to one.
- If an expression corresponds to a sentence fragment, a JavaScript statementcorresponds to a full sentence in a human language. A program is simply a list of statements.
- The simplest kind of statement is an expression with a semicolon after it. This is a program:
- 1;
- !false;
- In this book, every statement that needs a semicolon will always be terminated by one. I recommend you do the same in your own programs, at least until you’ve learned more about subtleties involved in leaving out semicolons.
-
- To catch and hold values, JavaScript provides a thing called a variable.
- var caught = 5 * 5;
- The special word (keyword) var indicates that this sentence is going to define a variable. It is followed by the name of the variable and, if we want to immediately give it a value, by an =operator and an expression.
- After a variable has been defined, its name can be used as an expression. The value of such an expression is the value the variable currently holds. Here’s an example: var ten = 10;
- console.log(ten * ten);
- // → 100
- Variable names can be any word that isn’t a reserved word (such as var). They may not include spaces. Digits can also be part of variable names—catch22 is a valid name, for example—but the name must not start with a digit. A variable name cannot include punctuation, except for the characters $ and _.
- When you define a variable without giving it a value, the tentacle has nothing to grasp, so it ends in thin air. If you ask for the value of an empty variable, you’ll get the value undefined.
- A single var statement may define multiple variables. The definitions must be separated by commas.
- 1
- var one = 1, two = 2;
- 2
- console.log(one + two);
- 3
- // → 3
-
- Words with a special meaning, such as var, are keywords, and they may not be used as variable names.
- There are also a number of words that are “reserved for use” in future versions of JavaScript. These are also officially not allowed to be used as variable names, though some JavaScript environments do allow them. The full list of keywords and reserved words is rather long.
- break case catch class const continue debugger default delete do else enum export extends false
- finally for function if implements import in
- instanceof interface let new null package private
- protected public return static super switch this
- throw true try typeof var void while with yield
-
- The collection of variables and their values that exist at a given time is called the environment.
- When a program starts up, this environment is not empty.
- It always contains variables that are part of the language standard, and most of the time, it has variables that provide ways to interact with the surrounding system.
- For example, in a browser, there are variables and functions to inspect and influence the currently loaded website and to read mouse and keyboard input.
-
- 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 variable alert holds a function that shows a little dialog box with a message. It is used like this: alert("Good morning!");
- 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 variable that holds the function. The values between the parentheses are given to the program inside the function.
- The example, the alert function uses the string that we give it as the text to show in the dialog box. Values given to functions are called arguments. The alert function needs only one of them, but other functions might need a different number or different types of arguments.
-
- ALERT() is a useful development tool but it can get annoying
- most browsers facilitate a console.log()
- 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 Mac, when you press Command-Option-I. If that does not work, search through the menus for an item named “web console” or “developer tools”.
-
- Showing a dialog box or writing text to the screen is a side effect.
- A lot of functions are useful because of the side effects they produce.
- Functions may also produce values, and in that case, they don’t need to have a side effect to be useful.
- For example, the function Math.max takes any number of number values and gives back the greatest.
- console.log(Math.max(2, 4));// → 4
- When a function produces a value, it is said to return that value. Anything that produces a value is an expression in JavaScript, which means function calls can be used within larger expressions.
- Here a call to Math.min, which is the opposite of Math.max, is used as an input to the plus operator:
- console.log(Math.min(2, 4) + 100);
- // → 102
-
- Browser environments contain other functions besides alert for popping up windows.
- You can ask the user an OK/Cancel question using confirm. This returns a Boolean: true if the user clicks OK and false if the user clicks Cancel.
- confirm("Shall we, then?");
- The prompt function can be used to ask an “open” question. The first argument is the question, the second one is the text that the user starts with. A line of text can be typed into the dialog window, and the function will return this text as a string. prompt("Tell me everything you know.", "...");
- These two functions aren’t used much in modern web programming, mostly because you have no control over the way the resulting windows look, but they are useful for toy programs and experiments.
-
- You now know that a program is built out of statements, which themselves sometimes contain more statements. Statements tend to contain expressions, which themselves can be built out of smaller expressions.
- Putting statements after one another gives you a program that is executed from top to bottom. You can introduce disturbances in the flow of control by using conditional (if, else, and switch) and looping (while, do, and for) statements.
- Variables can be used to file pieces of data under a name, and they are useful for tracking state in your program. The environment is the set of variables that are defined. JavaScript systems always put a number of useful standard variables into your environment.
- Functions are special values that encapsulate a piece of program. You can invoke them by writing functionName(argument1, argument2). Such a function call is an expression, and may produce a value.
-
Control Flow & Conditional Execution
- When your program contains more than one statement, the statements are executed, predictably, from top to bottom.
- Executing statements in straight-line order isn’t the only option we have.
- An alternative is conditional execution, where we choose between two different routes based on a Boolean value.
- Conditional execution is written with the if keyword in JavaScript. In the simple case, we just want some code to be executed if, and only if, a certain condition holds. For example, in the previous program, we might want to show the square of the input only if the input is actually a number. var theNumber = Number(prompt("Pick a number", ""));
- if (!isNaN(theNumber))
- alert("Your number is the square root of " +
- theNumber * theNumber);
- With this modification, if you enter “cheese”, no output will be shown.
- The keyword if executes or skips a statement depending on the value of a Boolean expression. The deciding expression is written after the keyword, between parentheses, followed by the statement to execute.
-
- var num = Number(prompt("Pick a number", "0"));
- if (num alert("Small");
- else if (num alert("Medium");
- else
- alert("Large");
-
- Consider a program that prints all even numbers from 0 to 12. One way to write this is as follows:
- console.log(0);
- console.log(2);
- console.log(4);
- console.log(6);
- console.log(8);
- console.log(10);
- console.log(12);
- That works, but the idea of writing a program is to make something less work, not more. If we needed all even numbers less than 1,000, the previous would be unworkable. What we need is a way to repeat some code. This form of control flow is called a loop:
- Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. If we combine this with a variable that counts, we can do something like this:
- var number = 0;while (number console.log(number);
- number = number + 2;
- }
- // → 0
- // → 2
- // … etcetera
-
- A statement starting with the keyword while creates a loop. The word whileis followed by an expression in parentheses and then a statement, much like if. The loop executes that statement as long as the expression produces a value that is true when converted to Boolean type.
- Braces do for statements what parentheses do for expressions: they group them together, making them count as a single statement. A sequence of statements wrapped in braces is called a block.
- Many JavaScript programmers wrap every single loop or if body in braces. They do this both for the sake of consistency and to avoid having to add or remove braces when changing the number of statements in the body later.
- var number = 0;
- while (number console.log(number);
- number = number + 2;
- }
- // → 0
- // → 2
-
- The do loop is a control structure similar to the while loop.
- It differs only on one point: a do loop always executes its body at least once, and it starts testing whether it should stop only after that first execution.
- To reflect this, the test appears after the body of the loop:
- do {
- var yourName = prompt("Who are you?");
- } while (!yourName);
- console.log(yourName);
- This program will force you to enter a name. It will ask again and again until it gets something that is not an empty string.
- Applying the ! operator will convert a value to Boolean type before negating it, and all strings except ""convert to true.
- This means the loop continues going round until you provide a name that is not the empty string.
-
- You’ve probably noticed the spaces I put in front of some statements.
- In JavaScript, these are not required—the computer will accept the program just fine without them.
- In fact, even the line breaks in programs are optional.
- You could write a program as a single long line if you felt like it.
- The role of the indentation inside blocks is to make the structure of the code stand out.
- In complex code, where new blocks are opened inside other blocks, it can become hard to see where one block ends and another begins.
- With proper indentation, the visual shape of a program corresponds to the shape of the blocks inside it.
- I like to use two spaces for every open block, but tastes differ—some people use four spaces, and some people use tab characters.
-
- Many loops follow the pattern seen in the previous while examples. First, a “counter” variable is created to track the progress of the loop. Then comes awhile loop, whose test expression usually checks whether the counter has reached some boundary yet. At the end of the loop body, the counter is updated to track progress.
- Because this pattern is so common, JavaScript and similar languages provide a slightly shorter and more comprehensive form, the for loop.
- for (var number = 0; number // … etcetera
- The parentheses after a for keyword must contain two semicolons. The part before the first semicolon initializes the loop, usually by defining a variable. The second part is the expression that checks whether the loop must continue. The final part updates the state of the loop after every iteration. In most cases, this is shorter and clearer than a while construct.
-
- Having the loop’s condition produce false is not the only way a loop can finish.
- There is a special statement called break that has the effect of immediately jumping out of the enclosing loop.
- This program illustrates the break statement. It finds the first number that is both greater than or equal to 20 and divisible by 7. for (var current = 20; ; current++) {
- if (current % 7 == 0)
- break;
- }
- console.log(current);
- // → 21
- The for construct in the example does not have a part that checks for the end of the loop. This means that the loop will never stop unless the breakstatement inside is executed.
- ere to leave out that break statement or accidentally write a condition that always produces true, your program would get stuck in an infinite loop. A program stuck in an infinite loop will never finish running, which is usually a bad thing.
- The continue keyword is similar to break, in that it influences the progress of a loop. When continue is encountered in a loop body, control jumps out of the body and continues with the loop’s next iteration.
-
- Especially when looping, a program often needs to “update” a variable to hold a value based on that variable’s previous value.
- counter = counter + 1; JavaScript provides a shortcut for this:
- 1
- counter += 1;
- Similar shortcuts work for many other operators, such as result *= 2 to double result or counter -= 1 to count downward.
- This allows us to shorten our counting example a little more.
- for (var number = 0; number
- For counter += 1 and counter -= 1, there are even shorter equivalents: counter++ and counter--.
-
- There is a construct called switch that is intended to solve such a “dispatch” in a more direct way. Unfortunately, the syntax JavaScript uses for this (which it inherited from the C/Java line of programming languages) is somewhat awkward—a chain of if statements often looks better. Here is an example:
- switch (prompt("What is the weather like?")) {
- case "rainy":
- console.log("Remember to bring an umbrella.");
- break;
- case "sunny":
- console.log("Dress lightly.");
- case "cloudy":
- console.log("Go outside.");
- break;
- default:
- console.log("Unknown weather type!");
- break; }
-
- You may put any number of case labels inside the block opened by switch.
- The program will jump to the label that corresponds to the value that switchwas given or to default if no matching value is found.
- It starts executing statements there, even if they’re under another label, until it reaches a breakstatement.
- In some cases, such as the "sunny" case in the example, this can be used to share some code between cases (it recommends going outside for both sunny and cloudy weather).
- But beware: it is easy to forget such a break, which will cause the program to execute code you do not want executed.
-
- Variable names may not contain spaces, yet it is often helpful to use multiple words to clearly describe what the variable represents. These are pretty much your choices for writing a variable name with several words in it:
- fuzzylittleturtle
- fuzzy_little_turtle
- FuzzyLittleTurtle
- fuzzyLittleTurtle The first style can be hard to read. Personally, I like the look of the underscores, though that style is a little painful to type. The standard JavaScript functions, and most JavaScript programmers, follow the bottom style—they capitalize every word except the first. It is not hard to get used to little things like that, and code with mixed naming styles can be jarring to read, so we will just follow this convention.
- In a few cases, such as the Number function, the first letter of a variable is also capitalized. This was done to mark this function as a constructor. What a constructor is will become clear in Chapter 6. For now, the important thing is not to be bothered by this apparent lack of consistency.
-
- Often, raw code does not convey all the information you want a program to convey to human readers, or it conveys it in such a cryptic way that people might not understand it. At other times, you might just feel poetic or want to include some thoughts as part of your program. This is what comments are for.
- A comment is a piece of text that is part of a program but is completely ignored by the computer. JavaScript has two ways of writing comments. To write a single-line comment, you can use two slash characters (//) and then the comment text after it.
- var accountBalance = calculateBalance(account);
- // It's a green hollow where a river sings
- accountBalance.adjust();
- // Madly catching white tatters in the grass.
- var report = new Report();
- // Where the sun on the proud mountain rings:
- addToReport(accountBalance, report);
- // It's a little valley, foaming like light in a glass.
- A // comment goes only to the end of the line. A section of text between /*and */ will be ignored, regardless of whether it contains line breaks. This is often useful for adding blocks of information about a file or a chunk of program.
-
- - Functions are the bread and butter of JavaScript.
- - The concept of wrapping a piece of program in a value has many uses.
- - It is a tool to structure larger programs, to reduce repetition, to associate names with subprograms, and to isolate these subprograms from each other.
-
- - A function definition is just a regular variable definition where the value given to the variable happens to be a function.
- - For example, the following code defines the variable square to refer to a function that produces the square of a given number:
- var square = function(x) { return x * x;
- };
- console.log(square(12));
- // → 144
- A function is created by an expression that starts with the keyword function.
- Functions have a set of parameters (in this case, only x) and a body, which contains the statements that are to be executed when the function is called.
- Must always be wrapped in braces, even when it consists of only a single statement (as in the previous example).
-
- Some functions produce a value, such as power and square, and some don’t, such as makeNoise, which produces only a side effect.
- A return statement determines the value the function returns.
- When control comes across such a statement, it immediately jumps out of the current function and gives the returned value to the code that called the function.
- The return keyword without an expression after it will cause the function to return undefined.
-
- The parameters to a function behave like regular variables, but their initial values are given by the caller of the function, not the code in the function itself.
- An important property of functions is that the variables created inside of them, including their parameters, are local to the function.
- This means, for example, that the result variable in the power example will be newly created every time the function is called, and these separate incarnations do not interfere with each other.
- This “localness” of variables applies only to the parameters and to variables declared with the var keyword inside the function body.
- Variables declared outside of any function are called global, because they are visible throughout the program.
- It is possible to access such variables from inside a function, as long as you haven’t declared a local variable with the same name.
- This behavior helps prevent accidental interference between functions.
- If all variables were shared by the whole program, it’d take a lot of effort to make sure no name is ever used for two different purposes.
- And if you did reuse a variable name, you might see strange effects from unrelated code messing with the value of your variable. By treating function-local variables as existing only within the function, the language makes it possible to read and understand functions as small universes, without having to worry about all the code at once.
-
- - JavaScript distinguishes not just between global and local variables. Functions can be created inside other functions, producing several degrees of locality.
Informationen
- Beschreibung
- Professional JavaScript Folienset am JavaScript - Eloquent JavaScript, erstellt von lukepunnett am 03/12/2015.
- Erstellt von
- lukepunnett · Dez 2015
- Aktualisiert
- 3 Dez 2016
- Aufrufe
- 26
- Bewertung