You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/15-function-expressions-arrows/article.md
+13-14Lines changed: 13 additions & 14 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -196,19 +196,20 @@ First, the syntax: how to differentiate between them in the code.
196
196
197
197
The more subtle difference is *when* a function is created by the JavaScript engine.
198
198
199
-
**A Function Expression is created when the execution reaches it and is usable from then on.**
199
+
**A Function Expression is created when the execution reaches it and is usable only from that moment.**
200
200
201
201
Once the execution flow passes to the right side of the assignment `let sum = function…` -- here we go, the function is created and can be used (assigned, called, etc. ) from now on.
202
202
203
203
Function Declarations are different.
204
204
205
-
**A Function Declaration is usable in the whole script (or a code block, if it's inside a block).**
205
+
**A Function Declaration can be called earlier than it is defined.**
206
206
207
-
In other words, when JavaScript *prepares* to run the script or a code block, it first looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage".
207
+
For example, a global Function Declaration is visible in the whole script, no matter where it is.
208
208
209
-
And after all of the Function Declarations are processed, the execution goes on.
209
+
That's due to internal algorithms. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an "initialization stage".
210
+
211
+
And after all Function Declarations are processed, the code is executed. So it has access to these functions.
210
212
211
-
As a result, a function declared as a Function Declaration can be called earlier than it is defined.
212
213
213
214
For example, this works:
214
215
@@ -224,7 +225,7 @@ function sayHi(name) {
224
225
225
226
The Function Declaration `sayHi` is created when JavaScript is preparing to start the script and is visible everywhere in it.
226
227
227
-
...If it was a Function Expression, then it wouldn't work:
228
+
...If it were a Function Expression, then it wouldn't work:
228
229
229
230
```js run refresh untrusted
230
231
*!*
@@ -238,13 +239,11 @@ let sayHi = function(name) { // (*) no magic any more
238
239
239
240
Function Expressions are created when the execution reaches them. That would happen only in the line `(*)`. Too late.
240
241
241
-
**When a Function Declaration is made within a code block, it is visible everywhere inside that block. But not outside of it.**
242
-
243
-
Sometimes that's handy to declare a local function only needed in that block alone. But that feature may also cause problems.
242
+
**In strict mode, when a Function Declaration is within a code block, it's visible everywhere inside that block. But not outside of it.**
244
243
245
244
For instance, let's imagine that we need to declare a function `welcome()` depending on the `age` variable that we get during runtime. And then we plan to use it some time later.
246
245
247
-
The code below doesn't work:
246
+
If we use Function Declaration, it won't work as intended:
248
247
249
248
```js run
250
249
let age =prompt("What is your age?", 18);
@@ -350,12 +349,12 @@ welcome(); // ok now
350
349
```
351
350
352
351
353
-
```smart header="When should you choose Function Declaration versus Function Expression?"
354
-
As a rule of thumb, when we need to declare a function, the first to consider is Function Declaration syntax, the one we used before. It gives more freedom in how to organize our code, because we can call such functions before they are declared.
352
+
```smart header="When to choose Function Declaration versus Function Expression?"
353
+
As a rule of thumb, when we need to declare a function, the first to consider is Function Declaration syntax. It gives more freedom in how to organize our code, because we can call such functions before they are declared.
355
354
356
-
It's also a little bit easier to look up `function f(…) {…}` in the code than `let f = function(…) {…}`. Function Declarations are more "eye-catching".
355
+
That's also better for readability, as it's easier to look up `function f(…) {…}` in the code than `let f = function(…) {…}`. Function Declarations are more "eye-catching".
357
356
358
-
...But if a Function Declaration does not suit us for some reason(we've seen an example above), then Function Expression should be used.
357
+
...But if a Function Declaration does not suit us for some reason, or we need a conditional declaration (we've just seen an example), then Function Expression should be used.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/03-string/1-ucfirst/solution.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@ But we can make a new string based on the existing one, with the uppercased firs
6
6
let newStr = str[0].toUpperCase() +str.slice(1);
7
7
```
8
8
9
-
There's a small problem though. If `str` is empty, then `str[0]` is undefined, so we'll get an error.
9
+
There's a small problem though. If `str` is empty, then `str[0]` is `undefined`, and as `undefined` doesn't have the `toUpperCase()` method, we'll get an error.
alert( "\u{20331}" ); // 佫, a rare chinese hieroglyph (long unicode)
89
+
alert( "\u{20331}" ); // 佫, a rare Chinese hieroglyph (long unicode)
90
90
alert( "\u{1F60D}" ); // 😍, a smiling face symbol (another long unicode)
91
91
```
92
92
93
93
All special characters start with a backslash character `\`. It is also called an "escape character".
94
94
95
-
We would also use it if we want to insert a quote into the string.
95
+
We might also use it if we wanted to insert a quote into the string.
96
96
97
97
For instance:
98
98
@@ -305,7 +305,8 @@ if (str.indexOf("Widget") != -1) {
305
305
}
306
306
```
307
307
308
-
````smart header="The bitwise NOT trick"
308
+
#### The bitwise NOT trick
309
+
309
310
One of the old tricks used here is the [bitwise NOT](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT)`~` operator. It converts the number to a 32-bit integer (removes the decimal part if exists) and then reverses all bits in its binary representation.
310
311
311
312
For 32-bit integers the call `~n` means exactly the same as `-(n+1)` (due to IEEE-754 format).
@@ -321,9 +322,9 @@ alert( ~-1 ); // 0, the same as -(-1+1)
321
322
*/!*
322
323
```
323
324
324
-
As we can see, `~n` is zero only if `n == -1`.
325
+
As we can see, `~n` is zero only if `n == -1` (that's for any 32-bit signed integer `n`).
325
326
326
-
So, the test `if ( ~str.indexOf("...") )` is truthy that the result of `indexOf` is not `-1`. In other words, when there is a match.
327
+
So, the test `if ( ~str.indexOf("...") )` is truthy only if the result of `indexOf` is not `-1`. In other words, when there is a match.
327
328
328
329
People use it to shorten `indexOf` checks:
329
330
@@ -338,7 +339,10 @@ if (~str.indexOf("Widget")) {
338
339
It is usually not recommended to use language features in a non-obvious way, but this particular trick is widely used in old code, so we should understand it.
339
340
340
341
Just remember: `if (~str.indexOf(...))` reads as "if found".
341
-
````
342
+
343
+
Technically speaking, numbers are truncated to 32 bits by `~` operator, so there exist other big numbers that give `0`, the smallest is `~4294967295=0`. That makes such check is correct only if a string is not that long.
344
+
345
+
Right now we can see this trick only in the old code, as modern JavaScript provides `.includes` method (see below).
342
346
343
347
### includes, startsWith, endsWith
344
348
@@ -558,7 +562,7 @@ You can skip the section if you don't plan to support them.
558
562
559
563
### Surrogate pairs
560
564
561
-
Most symbols have a 2-byte code. Letters in most european languages, numbers, and even most hieroglyphs, have a 2-byte representation.
565
+
All frequently used characters have 2-byte codes. Letters in most european languages, numbers, and even most hieroglyphs, have a 2-byte representation.
562
566
563
567
But 2 bytes only allow 65536 combinations and that's not enough for every possible symbol. So rare symbols are encoded with a pair of 2-byte characters called "a surrogate pair".
564
568
@@ -567,7 +571,7 @@ The length of such symbols is `2`:
567
571
```js run
568
572
alert( '𝒳'.length ); // 2, MATHEMATICAL SCRIPT CAPITAL X
569
573
alert( '😂'.length ); // 2, FACE WITH TEARS OF JOY
570
-
alert( '𩷶'.length ); // 2, a rare chinese hieroglyph
574
+
alert( '𩷶'.length ); // 2, a rare Chinese hieroglyph
571
575
```
572
576
573
577
Note that surrogate pairs did not exist at the time when JavaScript was created, and thus are not correctly processed by the language!
In reality, this is not always the case. The reason being that the symbol `Ṩ` is "common enough", so UTF-16 creators included it in the main table and gave it the code.
656
+
In reality, this is not always the case. The reason being that the symbol `Ṩ` is "common enough", so UTF-16 creators included it in the main table and gave it the code.
653
657
654
658
If you want to learn more about normalization rules and variants -- they are described in the appendix of the Unicode standard: [Unicode Normalization Forms](http://www.unicode.org/reports/tr15/), but for most practical purposes the information from this section is enough.
: Create the date with the given components in the local time zone. Only the first two arguments are obligatory.
53
53
54
-
Note:
55
-
56
54
- The `year` must have 4 digits: `2013` is okay, `98` is not.
57
55
- The `month` count starts with `0` (Jan), up to `11` (Dec).
58
56
- The `date` parameter is actually the day of month, if absent then `1` is assumed.
@@ -74,7 +72,7 @@ To create a new `Date` object call `new Date()` with one of the following argume
74
72
75
73
## Access date components
76
74
77
-
There are many methods to access the year, month and so on from the `Date` object. But they can be easily remembered when categorized.
75
+
There are methods to access the year, month and so on from the `Date` object:
78
76
79
77
[getFullYear()](mdn:js/Date/getFullYear)
80
78
: Get the year (4 digits)
@@ -217,21 +215,21 @@ The important side effect: dates can be subtracted, the result is their differen
217
215
That can be used for time measurements:
218
216
219
217
```js run
220
-
let start =newDate(); // start counting
218
+
let start =newDate(); // start measuring time
221
219
222
220
// do the job
223
221
for (let i =0; i <100000; i++) {
224
222
let doSomething = i * i * i;
225
223
}
226
224
227
-
let end =newDate(); //done
225
+
let end =newDate(); //end measuring time
228
226
229
227
alert( `The loop took ${end - start} ms` );
230
228
```
231
229
232
230
## Date.now()
233
231
234
-
If we only want to measure the difference, we don't need the `Date` object.
232
+
If we only want to measure time, we don't need the `Date` object.
235
233
236
234
There's a special method `Date.now()` that returns the current timestamp.
237
235
@@ -264,6 +262,8 @@ If we want a reliable benchmark of CPU-hungry function, we should be careful.
264
262
265
263
For instance, let's measure two functions that calculate the difference between two dates: which one is faster?
266
264
265
+
Such performance measurements are often called "benchmarks".
266
+
267
267
```js
268
268
// we have date1 and date2, which function faster returns their difference in ms?
269
269
functiondiffSubtract(date1, date2) {
@@ -280,7 +280,7 @@ These two do exactly the same thing, but one of them uses an explicit `date.getT
280
280
281
281
So, which one is faster?
282
282
283
-
The first idea may be to run them many times in a row and measure the time difference. For our case, functions are very simple, so we have to do it around 100000 times.
283
+
The first idea may be to run them many times in a row and measure the time difference. For our case, functions are very simple, so we have to do it at least 100000 times.
284
284
285
285
Let's measure:
286
286
@@ -310,7 +310,7 @@ Wow! Using `getTime()` is so much faster! That's because there's no type convers
310
310
311
311
Okay, we have something. But that's not a good benchmark yet.
312
312
313
-
Imagine that at the time of running `bench(diffSubtract)` CPU was doing something in parallel, and it was taking resources. And by the time of running `bench(diffGetTime)`the work has finished.
313
+
Imagine that at the time of running `bench(diffSubtract)` CPU was doing something in parallel, and it was taking resources. And by the time of running `bench(diffGetTime)`that work has finished.
314
314
315
315
A pretty real scenario for a modern multi-process OS.
316
316
@@ -368,7 +368,7 @@ for (let i = 0; i < 10; i++) {
Modern JavaScript engines perform many optimizations. They may tweak results of"artificial tests" compared to "normal usage", especially when we benchmark something very small. Soif you seriously want to understand performance, then please study how the JavaScript engine works. And then you probably won't need microbenchmarks at all.
371
+
Modern JavaScript engines perform many optimizations. They may tweak results of"artificial tests" compared to "normal usage", especially when we benchmark something very small, such as how an operator works, or a built-infunction. So if you seriously want to understand performance, then please study how the JavaScript engine works. And then you probably won't need microbenchmarks at all.
372
372
373
373
The great pack of articles about V8 can be found at <http://mrale.ph>.
374
374
```
@@ -415,7 +415,7 @@ alert(date);
415
415
416
416
Note that unlike many other systems, timestamps in JavaScript are in milliseconds, not in seconds.
417
417
418
-
Also, sometimes we need more precise time measurements. JavaScript itself does not have a way to measure time inmicroseconds (1 millionth of a second), but most environments provide it. For instance, browser has [performance.now()](mdn:api/Performance/now) that gives the number of milliseconds from the start of page loading with microsecond precision (3 digits after the point):
418
+
Sometimes we need more precise time measurements. JavaScript itself does not have a way to measure time in microseconds (1 millionth of a second), but most environments provide it. For instance, browser has [performance.now()](mdn:api/Performance/now) that gives the number of milliseconds from the start of page loading with microsecond precision (3 digits after the point):
419
419
420
420
```js run
421
421
alert(`Loading started ${performance.now()}ms ago`);
Sometimes people say that `class` is a "syntax sugar" in JavaScript, because we could actually declare the same without `class` keyword at all:
122
+
Sometimes people say that `class` is a "syntax sugar" (syntax that is designed to make things easier to read, but doesn't introduce anything new) in JavaScript, because we could actually declare the same without `class` keyword at all:
0 commit comments