Merge pull request #130 from jmbothe/master
Grammar/usage/punctuation edits, Part 1, sections 2.1 - 2.8
This commit is contained in:
commit
e3b35f852a
8 changed files with 62 additions and 62 deletions
|
@ -11,7 +11,7 @@ So first, let's see how to attach a script to a webpage. For server-side environ
|
|||
|
||||
## The "script" tag
|
||||
|
||||
JavaScript programs can be inserted in any place of HTML with the help of the `<script>` tag.
|
||||
JavaScript programs can be inserted in any part of an HTML document with the help of the `<script>` tag.
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -49,7 +49,7 @@ The `<script>` tag has a few attributes that are rarely used nowadays, but we ca
|
|||
|
||||
The `type` attribute: <code><script <u>type</u>=...></code>
|
||||
|
||||
: The old standard HTML4 required a script to have a type. Usually it was `type="text/javascript"`. The modern HTML standard assumes this `type` by default, no attribute is required.
|
||||
: The old standard HTML4 required a script to have a type. Usually it was `type="text/javascript"`. The modern HTML standard assumes this `type` by default. No attribute is required.
|
||||
|
||||
The `language` attribute: <code><script <u>language</u>=...></code>
|
||||
: This attribute was meant to show the language of the script. As of now, this attribute makes no sense, the language is JavaScript by default. No need to use it.
|
||||
|
@ -105,7 +105,7 @@ That saves traffic and makes pages faster.
|
|||
```
|
||||
|
||||
````warn header="If `src` is set, the script content is ignored."
|
||||
A single `<script>` tag can't have both `src` attribute and the code inside.
|
||||
A single `<script>` tag can't have both the `src` attribute and the code inside.
|
||||
|
||||
This won't work:
|
||||
|
||||
|
|
|
@ -61,9 +61,9 @@ If you're curious to see a concrete example of such an error, check this code ou
|
|||
[1, 2].forEach(alert)
|
||||
```
|
||||
|
||||
No need to think about the meaning of the brackets `[]` and `forEach` yet. We'll study them later, for now -- it does not matter. Let's just remember the result: it shows `1`, then `2`.
|
||||
No need to think about the meaning of the brackets `[]` and `forEach` yet. We'll study them later, for now it does not matter. Let's just remember the result: it shows `1`, then `2`.
|
||||
|
||||
Now let's add an `alert` before the code. And *not* finish it with a semicolon:
|
||||
Now let's add an `alert` before the code and *not* finish it with a semicolon:
|
||||
|
||||
```js run no-beautify
|
||||
alert("There will be an error")
|
||||
|
@ -94,11 +94,11 @@ alert("There will be an error")[1, 2].forEach(alert)
|
|||
But it should be two separate statements, not a single one. Such a merging in this case is just wrong, hence the error. There are other situations when such a thing happens.
|
||||
````
|
||||
|
||||
It's recommended to put semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer, especially for a beginner -- to use them.
|
||||
It's recommended to put semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer -- especially for a beginner -- to use them.
|
||||
|
||||
## Comments
|
||||
|
||||
As the time goes, the program becomes more and more complex. It becomes necessary to add *comments* which describe what happens and why.
|
||||
As time goes on, the program becomes more and more complex. It becomes necessary to add *comments* which describe what happens and why.
|
||||
|
||||
Comments can be put into any place of the script. They don't affect the execution, because the engine simply ignores them.
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
For a long time JavaScript was evolving without compatibility issues. New features were added to the language, but the old functionality did not change.
|
||||
|
||||
That had the benefit of never breaking the existing codes. But the downside was that any mistake or an imperfect decision made by JavaScript creators got stuck in the language forever.
|
||||
That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript creators got stuck in the language forever.
|
||||
|
||||
It had been so until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most modifications are off by default. One needs to enable them explicitly with a special directive `"use strict"`.
|
||||
|
||||
|
@ -55,7 +55,7 @@ The differences of `"use strict"` versus the "default" mode are still to be cove
|
|||
|
||||
In the next chapters, as we learn language features, we'll make notes about the differences of the strict mode. Luckily, there are not so many. And they actually make our life better.
|
||||
|
||||
At this point of time it's enough to know about it in general:
|
||||
At this point in time it's enough to know about it in general:
|
||||
|
||||
1. The `"use strict"` directive switches the engine to the "modern" mode, changing the behavior of some built-in features. We'll see the details as we study.
|
||||
2. The strict mode is enabled by `"use strict"` at the top. Also there are several language features like "classes" and "modules" that enable strict mode automatically.
|
||||
|
|
|
@ -95,7 +95,7 @@ There are subtle differences between `let` and `var`, but they do not matter for
|
|||
|
||||
## A real-life analogy
|
||||
|
||||
We can easily grasp the concept of a "variable" if we imagine it as a "box" for data, with a unique-named sticker on it.
|
||||
We can easily grasp the concept of a "variable" if we imagine it as a "box" for data, with a uniquely-named sticker on it.
|
||||
|
||||
For instance, the variable `message` can be imagined as a box labelled `"message"` with the value `"Hello!"` in it:
|
||||
|
||||
|
@ -139,9 +139,9 @@ alert(message); // Hello world!
|
|||
```smart header="Functional languages"
|
||||
It may be interesting to know that there also exist [functional](https://en.wikipedia.org/wiki/Functional_programming) programming languages that forbid changing a variable value. For example, [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/).
|
||||
|
||||
In such languages, once the value is stored "in the box" -- it's there forever. If we need to store something else -- the language forces to create a new box (declare a new variable), we can't reuse the old one.
|
||||
In such languages, once the value is stored "in the box", it's there forever. If we need to store something else, the language forces to create a new box (declare a new variable). We can't reuse the old one.
|
||||
|
||||
Though it may seem a little bit odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits. Studying of such a language (even if not planning to use it soon) is recommended to broaden the mind.
|
||||
Though it may seem a little bit odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits. Studying such a language (even if not planning to use it soon) is recommended to broaden the mind.
|
||||
```
|
||||
|
||||
## Variable naming [#variable-naming]
|
||||
|
@ -160,7 +160,7 @@ let test123;
|
|||
|
||||
When the name contains multiple words, [camelCase](https://en.wikipedia.org/wiki/CamelCase) is commonly used. That is: words go one after another, each word starts with a capital letter: `myVeryLongName`.
|
||||
|
||||
What's interesting -- the dollar sign `'$'` and the underscore `'_'` also can be used in names. They are regular symbols, just like letters, without any special meaning.
|
||||
What's interesting -- the dollar sign `'$'` and the underscore `'_'` can also be used in names. They are regular symbols, just like letters, without any special meaning.
|
||||
|
||||
These names are valid:
|
||||
|
||||
|
@ -209,7 +209,7 @@ let return = 5; // also can't name it "return", error!
|
|||
|
||||
````warn header="An assignment without `use strict`"
|
||||
|
||||
Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value, without `let`. This still works now if we don't put `use strict`, the behavior is kept for compatibility with old scripts.
|
||||
Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value, without `let`. This still works now if we don't put `use strict`. The behavior is kept for compatibility with old scripts.
|
||||
|
||||
```js run no-strict
|
||||
// note: no "use strict" in this example
|
||||
|
@ -239,7 +239,7 @@ To declare a constant (unchanging) variable, one can use `const` instead of `let
|
|||
const myBirthday = '18.04.1982';
|
||||
```
|
||||
|
||||
The variable declared using `const` are called "constants". They can not be changed. An attempt to do it would cause an error:
|
||||
Variables declared using `const` are called "constants". They cannot be changed. An attempt to do it would cause an error:
|
||||
|
||||
```js run
|
||||
const myBirthday = '18.04.1982';
|
||||
|
@ -254,7 +254,7 @@ When a programmer is sure that the variable should never change, he can use `con
|
|||
|
||||
There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.
|
||||
|
||||
Such constants are named using capitals and underscores.
|
||||
Such constants are named using capital letters and underscores.
|
||||
|
||||
Like this:
|
||||
|
||||
|
@ -273,9 +273,9 @@ Benefits:
|
|||
|
||||
- `COLOR_ORANGE` is much easier to remember than `"#FF7F00"`.
|
||||
- It is much easier to mistype in `"#FF7F00"` than in `COLOR_ORANGE`.
|
||||
- When reading the code -- `COLOR_ORANGE` is much more meaningful than `#FF7F00`.
|
||||
- When reading the code, `COLOR_ORANGE` is much more meaningful than `#FF7F00`.
|
||||
|
||||
When should we use capitals for a constant, and when -- name them normally? Let's make that clear.
|
||||
When should we use capitals for a constant, and when should we name them normally? Let's make that clear.
|
||||
|
||||
Being a "constant" just means that the value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red), and there are those that are *calculated* in run-time, during the execution, but do not change after the assignment.
|
||||
|
||||
|
@ -296,7 +296,7 @@ Please name the variables sensibly. Take time to think if needed.
|
|||
|
||||
Variable naming is one of the most important and complex skills in programming. A quick glance at variable names can reveal which code is written by a beginner and which by an experienced developer.
|
||||
|
||||
In a real project, most of the time is spent on modifying and extending the existing code base, rather than writing something completely separate from the scratch. And when we return to the code after some time of doing something else, it's much easier to find the information that is well-labelled. Or, in other words, when the variables have good names.
|
||||
In a real project, most of the time is spent on modifying and extending the existing code base, rather than writing something completely separate from the scratch. And when we return to the code after some time of doing something else, it's much easier to find information that is well-labelled. Or, in other words, when the variables have good names.
|
||||
|
||||
Please spend some time thinking about the right name for a variable before declaring it. That will repay you a lot.
|
||||
|
||||
|
@ -326,7 +326,7 @@ Modern JavaScript minifiers and browsers optimize code well enough, so it won't
|
|||
We can declare variables to store data. That can be done using `var` or `let` or `const`.
|
||||
|
||||
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8).
|
||||
- `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case if you'll need them.
|
||||
- `const` -- is like `let`, but the value of variable can't be changed.
|
||||
- `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case you need them.
|
||||
- `const` -- is like `let`, but the value of the variable can't be changed.
|
||||
|
||||
Variables should be named in a way that allows to easily understand what's inside.
|
||||
Variables should be named in a way that allows us to easily understand what's inside.
|
||||
|
|
|
@ -10,7 +10,7 @@ message = 123456;
|
|||
|
||||
Programming languages that allow such things are called "dynamically typed", meaning that there are data types, but variables are not bound to any of them.
|
||||
|
||||
There are 7 basic data types in JavaScript. Here we'll study the basics, and in next chapters we'll talk about each of them in detail.
|
||||
There are seven basic data types in JavaScript. Here we'll study the basics, and in the next chapters we'll talk about each of them in detail.
|
||||
|
||||
[cut]
|
||||
|
||||
|
@ -62,7 +62,7 @@ The script will never stop with a fatal error ("die"). At worst we'll get `NaN`
|
|||
|
||||
Special numeric values formally belong to the "number" type. Of course they are not numbers in a common sense of this word.
|
||||
|
||||
We'll see more into working with numbers in the chapter <info:number>.
|
||||
We'll see more about working with numbers in the chapter <info:number>.
|
||||
|
||||
## A string
|
||||
|
||||
|
@ -82,7 +82,7 @@ In JavaScript, there are 3 types of quotes.
|
|||
|
||||
Double and single quotes are "simple" quotes. There's no difference between them in JavaScript.
|
||||
|
||||
Backticks are "extended functionality" quotes. They allow to embed variables and expressions into a string by wrapping them in `${…}`, for example:
|
||||
Backticks are "extended functionality" quotes. They allow us to embed variables and expressions into a string by wrapping them in `${…}`, for example:
|
||||
|
||||
```js run
|
||||
let name = "John";
|
||||
|
@ -96,7 +96,7 @@ alert( `the result is *!*${1 + 2}*/!*` ); // the result is 3
|
|||
|
||||
The expression inside `${…}` is evaluated and the result becomes a part of the string. We can put anything there: a variable like `name` or an arithmetical expression like `1 + 2` or something more complex.
|
||||
|
||||
Please note that this only can be done in backticks, other quotes do not allow such embedding!
|
||||
Please note that this can only be done in backticks. Other quotes do not allow such embedding!
|
||||
```js run
|
||||
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)
|
||||
```
|
||||
|
@ -113,7 +113,7 @@ In JavaScript, there is no such type. There's only one type: `string`. A string
|
|||
|
||||
The boolean type has only two values: `true` and `false`.
|
||||
|
||||
This type is commonly used to store yes/no values: `true` means "yes, correct", and `false` means the "no, incorrect".
|
||||
This type is commonly used to store yes/no values: `true` means "yes, correct", and `false` means "no, incorrect".
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -178,7 +178,7 @@ alert(x); // "undefined"
|
|||
|
||||
The `object` type is special.
|
||||
|
||||
All other types are called "primitive", because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections data and more complex entities. We'll deal with them later in the chapter <info:object> after we know enough about primitives.
|
||||
All other types are called "primitive", because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities. We'll deal with them later in the chapter <info:object> after we know enough about primitives.
|
||||
|
||||
The `symbol` type is used to create unique identifiers for objects. We have to mention it here for completeness, but it's better to study them after objects.
|
||||
|
||||
|
@ -238,10 +238,10 @@ There are 7 basic types in JavaScript.
|
|||
- `object` for more complex data structures.
|
||||
- `symbol` for unique identifiers.
|
||||
|
||||
The `typeof` operator allows to see which type is stored in the variable.
|
||||
The `typeof` operator allows us to see which type is stored in the variable.
|
||||
|
||||
- Two forms: `typeof x` or `typeof(x)`.
|
||||
- Returns a string with the name of the type, like `"string"`.
|
||||
- For `null` returns `"object"` -- that's the error in the language, it's not an object in fact.
|
||||
- For `null` returns `"object"` -- that's an error in the language, it's not an object in fact.
|
||||
|
||||
In the next chapters we'll concentrate on primitive values and once we're familiar with that, then we'll move on to objects.
|
||||
In the next chapters we'll concentrate on primitive values and once we're familiar with them, then we'll move on to objects.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# Type Conversions
|
||||
|
||||
Most of time, operators and functions automatically convert a value to the right type. That's called "type coercion".
|
||||
Most of the time, operators and functions automatically convert a value to the right type. That's called "type coercion".
|
||||
|
||||
For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers.
|
||||
|
||||
|
@ -14,7 +14,7 @@ In this chapter we don't cover objects yet. Here we study primitives first. Late
|
|||
|
||||
## ToString
|
||||
|
||||
The string conversion happens when we need a string form of a value.
|
||||
String conversion happens when we need the string form of a value.
|
||||
|
||||
For example, `alert(value)` does it to show the value.
|
||||
|
||||
|
@ -30,7 +30,7 @@ alert(typeof value); // string
|
|||
*/!*
|
||||
```
|
||||
|
||||
The string conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"` etc.
|
||||
String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"` etc.
|
||||
|
||||
## ToNumber
|
||||
|
||||
|
@ -53,7 +53,7 @@ let num = Number(str); // becomes a number 123
|
|||
alert(typeof num); // number
|
||||
```
|
||||
|
||||
The explicit conversion is usually required when we read a value from a string-based source like a text form, but we expect a number to be entered.
|
||||
Explicit conversion is usually required when we read a value from a string-based source like a text form, but we expect a number to be entered.
|
||||
|
||||
If the string is not a valid number, the result of such conversion is `NaN`, for instance:
|
||||
|
||||
|
@ -70,7 +70,7 @@ Numeric conversion rules:
|
|||
|`undefined`|`NaN`|
|
||||
|`null`|`0`|
|
||||
|<code>true and false</code> | `1` and `0` |
|
||||
| `string` | Whitespaces from the start and the end are removed. Then, if the remaining string is empty, the result is `0`, otherwise -- the number is "read" from the string. An error gives `NaN`. |
|
||||
| `string` | Whitespaces from the start and the end are removed. Then, if the remaining string is empty, the result is `0`. Otherwise, the number is "read" from the string. An error gives `NaN`. |
|
||||
|
||||
Examples:
|
||||
|
||||
|
@ -131,9 +131,9 @@ alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
|
|||
|
||||
There are three most widely used type conversions: to string, to number and to boolean.
|
||||
|
||||
**`ToString`** -- occurs when we output something, can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
|
||||
**`ToString`** -- Occurs when we output something, can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
|
||||
|
||||
**`ToNumber`** -- occurs in math operations, can be performed with `Number(value)`.
|
||||
**`ToNumber`** -- Occurs in math operations, can be performed with `Number(value)`.
|
||||
|
||||
The conversion follows the rules:
|
||||
|
||||
|
@ -144,7 +144,7 @@ The conversion follows the rules:
|
|||
|<code>true / false</code> | `1 / 0` |
|
||||
| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. |
|
||||
|
||||
**`ToBoolean`** -- occurs in logical operations, or can be performed with `Boolean(value)`.
|
||||
**`ToBoolean`** -- Occurs in logical operations, or can be performed with `Boolean(value)`.
|
||||
|
||||
Follows the rules:
|
||||
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
# Operators
|
||||
|
||||
Many operators are known to us from school. It is an addition `+`, a multiplication `*`, a subtraction `-` and so on.
|
||||
Many operators are known to us from school. They are addition `+`, a multiplication `*`, a subtraction `-` and so on.
|
||||
|
||||
In this chapter we concentrate on aspects that are not covered by the school arithmetic.
|
||||
In this chapter we concentrate on aspects that are not covered by school arithmetic.
|
||||
|
||||
[cut]
|
||||
|
||||
|
@ -28,7 +28,7 @@ Before we move on, let's grasp the common terminology.
|
|||
alert( y - x ); // 2, binary minus subtracts values
|
||||
```
|
||||
|
||||
Formally, we're talking about the two different operators here: the unary negation (single operand, reverses the sign) and the binary subtraction (two operands, subtracts).
|
||||
Formally, we're talking about two different operators here: the unary negation (single operand, reverses the sign) and the binary subtraction (two operands, subtracts).
|
||||
|
||||
## Strings concatenation, binary +
|
||||
|
||||
|
@ -43,7 +43,7 @@ let s = "my" + "string";
|
|||
alert(s); // mystring
|
||||
```
|
||||
|
||||
Note that if any of operands is a string, then the other one is converted to string too.
|
||||
Note that if any of operands is a string, then the other one is converted to a string too.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -52,9 +52,9 @@ alert( '1' + 2 ); // "12"
|
|||
alert( 2 + '1' ); // "21"
|
||||
```
|
||||
|
||||
See, it doesn't matter whether the first operand is a string or the second one. The rule is simple: if any of operands is a string, then convert the other one into a string as well.
|
||||
See, it doesn't matter whether the first operand is a string or the second one. The rule is simple: if either operand is a string, then convert the other one into a string as well.
|
||||
|
||||
The string concatenation and conversion is the special feature of the binary plus `"+"`. Other arithmetic operators work only with numbers. They always convert their operands to numbers.
|
||||
String concatenation and conversion is a special feature of the binary plus `"+"`. Other arithmetic operators work only with numbers. They always convert their operands to numbers.
|
||||
|
||||
For instance, subtraction and division:
|
||||
|
||||
|
@ -88,7 +88,7 @@ alert( +"" ); // 0
|
|||
|
||||
It actually does the same as `Number(...)`, but shorter.
|
||||
|
||||
A need to convert string to number arises very often. For example, if we are getting values from HTML form fields, then are usually strings.
|
||||
A need to convert string to number arises very often. For example, if we are getting values from HTML form fields, then they are usually strings.
|
||||
|
||||
What if we want to sum them?
|
||||
|
||||
|
@ -116,7 +116,7 @@ alert( +apples + +oranges ); // 5
|
|||
// alert( Number(apples) + Number(oranges) ); // 5
|
||||
```
|
||||
|
||||
From a mathematician's standpoint the abundance of pluses may seem strange. But from a programmer's standpoint -- there's nothing special: unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up.
|
||||
From a mathematician's standpoint the abundance of pluses may seem strange. But from a programmer's standpoint, there's nothing special: unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up.
|
||||
|
||||
Why are unary pluses applied to values before the binary one? As we're going to see, that's because of their *higher precedence*.
|
||||
|
||||
|
@ -124,11 +124,11 @@ Why are unary pluses applied to values before the binary one? As we're going to
|
|||
|
||||
If an expression has more than one operator, the execution order is defined by their *precedence*, or, in other words, there's an implicit priority order among the operators.
|
||||
|
||||
From the school we all know that the multiplication in the expression `1 + 2 * 2` should be calculated before the addition. That's exactly the precedence thing. The multiplication is said to have *a higher precedence* than the addition.
|
||||
From school we all know that the multiplication in the expression `1 + 2 * 2` should be calculated before the addition. That's exactly the precedence thing. The multiplication is said to have *a higher precedence* than the addition.
|
||||
|
||||
Parentheses override any precedence, so if we're not satisfied with the order, we can use them, like: `(1 + 2) * 2`.
|
||||
|
||||
There are many operators in JavaScript. Every operator has a corresponding precedence number. The one with the bigger number executes first. If the precedence is same -- the execution order is from left to right.
|
||||
There are many operators in JavaScript. Every operator has a corresponding precedence number. The one with the bigger number executes first. If the precedence is the same, the execution order is from left to right.
|
||||
|
||||
An extract from the [precedence table](https://developer.mozilla.org/en/JavaScript/Reference/operators/operator_precedence) (you don't need to remember this, but note that unary operators are higher than corresponding binary ones):
|
||||
|
||||
|
@ -145,7 +145,7 @@ An extract from the [precedence table](https://developer.mozilla.org/en/JavaScri
|
|||
| 3 | assignment | `=` |
|
||||
| ... | ... | ... |
|
||||
|
||||
As we can see, the "unary plus" has a priority of `16`, higher than `13` for the "addition" (binary plus). That's why in the expression `"+apples + +oranges"` unary pluses work first, and then the addition.
|
||||
As we can see, the "unary plus" has a priority of `16`, which is higher than `13` for the "addition" (binary plus). That's why in the expression `"+apples + +oranges"` unary pluses work first, and then the addition.
|
||||
|
||||
## Assignment
|
||||
|
||||
|
@ -180,7 +180,7 @@ An operator always returns a value. That's obvious for most of them like an addi
|
|||
|
||||
The call `x = value` writes the `value` into `x` *and then returns it*.
|
||||
|
||||
Here's the demo that uses an assignment as the part of a more complex expression:
|
||||
Here's the demo that uses an assignment as part of a more complex expression:
|
||||
|
||||
```js run
|
||||
let a = 1;
|
||||
|
@ -272,7 +272,7 @@ Is there any difference? Yes, but we can only see it if we use the returned valu
|
|||
|
||||
Let's clarify. As we know, all operators return a value. Increment/decrement is not an exception here. The prefix form returns the new value, while the postfix form returns the old value (prior to increment/decrement).
|
||||
|
||||
To see the difference -- here's the example:
|
||||
To see the difference, here's the example:
|
||||
|
||||
```js run
|
||||
let counter = 1;
|
||||
|
@ -296,7 +296,7 @@ In the line `(*)` the *postfix* form `counter++` also increments `i`, but return
|
|||
|
||||
To summarize:
|
||||
|
||||
- If the result of increment/decrement is not used, then there is no difference which form to use:
|
||||
- If the result of increment/decrement is not used, then there is no difference in which form to use:
|
||||
|
||||
```js run
|
||||
let counter = 0;
|
||||
|
@ -403,7 +403,7 @@ alert( n ); // 16 (right part evaluated first, same as n *= 8)
|
|||
|
||||
The comma operator `','` is one of most rare and unusual operators. Sometimes it's used to write shorter code, so we need to know it in order to understand what's going on.
|
||||
|
||||
The comma operator allows to evaluate several expressions, dividing them with a comma `','`. Each of them is evaluated, but result of only the last one is returned.
|
||||
The comma operator allows us to evaluate several expressions, dividing them with a comma `','`. Each of them is evaluated, but the result of only the last one is returned.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -436,4 +436,4 @@ for (*!*a = 1, b = 3, c = a * b*/!*; a < 10; a++) {
|
|||
}
|
||||
```
|
||||
|
||||
Such tricks are used in many JavaScript frameworks, that's why we mention about them. But usually they don't improve the code readability, so we should think well before writing like that.
|
||||
Such tricks are used in many JavaScript frameworks, that's why we mention them. But usually they don't improve the code readability, so we should think well before writing like that.
|
||||
|
|
|
@ -86,7 +86,7 @@ alert( false == 0 ); // true
|
|||
```
|
||||
|
||||
````smart header="A funny consequence"
|
||||
It is possible that in the same time:
|
||||
It is possible that at the same time:
|
||||
|
||||
- Two values are equal.
|
||||
- One of them is `true` as a boolean and the other one is `false` as a boolean.
|
||||
|
@ -103,7 +103,7 @@ alert( Boolean(b) ); // true
|
|||
alert(a == b); // true!
|
||||
```
|
||||
|
||||
From JavaScript standpoint that's quite normal. An equality check converts using the numeric conversion (hence `"0"` becomes `0`), while `Boolean` conversion uses another set of rules.
|
||||
From JavaScript's standpoint that's quite normal. An equality check converts using the numeric conversion (hence `"0"` becomes `0`), while `Boolean` conversion uses another set of rules.
|
||||
````
|
||||
|
||||
## Strict equality
|
||||
|
@ -126,7 +126,7 @@ What to do if we'd like to differentiate `0` from `false`?
|
|||
|
||||
**A strict equality operator `===` checks the equality without type conversion.**
|
||||
|
||||
In other words, if `a` and `b` are of different types then `a === b` immediately returns `false`, without an attempt to convert them.
|
||||
In other words, if `a` and `b` are of different types, then `a === b` immediately returns `false` without an attempt to convert them.
|
||||
|
||||
Let's try it:
|
||||
|
||||
|
@ -142,7 +142,7 @@ The strict equality check operator is a bit longer to write, but makes it obviou
|
|||
|
||||
Let's see more edge cases.
|
||||
|
||||
There's a non-intuitive behavior when `null` or `undefined` is compared with other values.
|
||||
There's a non-intuitive behavior when `null` or `undefined` are compared with other values.
|
||||
|
||||
|
||||
For a strict equality check `===`
|
||||
|
@ -174,7 +174,7 @@ alert( null == 0 ); // (2) false
|
|||
alert( null >= 0 ); // (3) *!*true*/!*
|
||||
```
|
||||
|
||||
Yeah, mathematically that's strange. The last result states that "`null` is equal or greater than zero". Then one of the comparisons above must be correct, but they are both falsy.
|
||||
Yeah, mathematically that's strange. The last result states that "`null` is greater than or equal to zero". Then one of the comparisons above must be correct, but they are both falsy.
|
||||
|
||||
The reason is that an equality check `==` and comparisons `> < >= <=` work differently. Comparisons convert `null` to a number, hence treat it as `0`. That's why (3) `null >= 0` is true and (1) `null > 0` is false.
|
||||
|
||||
|
@ -199,7 +199,7 @@ We've got these results because:
|
|||
|
||||
### Evade problems
|
||||
|
||||
Why did we observe these examples? Should we remember these pecularities all the time? Well, not really. Actually, these tricky things will gradually become familiar over the time, but there's a solid way to evade any problems with them.
|
||||
Why did we observe these examples? Should we remember these peculiarities all the time? Well, not really. Actually, these tricky things will gradually become familiar over time, but there's a solid way to evade any problems with them.
|
||||
|
||||
Just treat any comparison with `undefined/null` except the strict equality `===` with exceptional care.
|
||||
|
||||
|
@ -211,4 +211,4 @@ Don't use comparisons `>= > < <=` with a variable which may be `null/undefined`,
|
|||
- Strings are compared letter-by-letter in the "dictionary" order.
|
||||
- When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).
|
||||
- Values `null` and `undefined` equal `==` each other and do not equal any other value.
|
||||
- Be careful when using comparisons like `>` or `<` with variables that can occasionaly be `null/undefined`. Making a separate check for `null/undefined` is a good idea.
|
||||
- Be careful when using comparisons like `>` or `<` with variables that can occasionally be `null/undefined`. Making a separate check for `null/undefined` is a good idea.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue