[{{mminutes}}:{{sseconds}}] X
Пользователь приглашает вас присоединиться к открытой игре игре с друзьями .
Sites: Javascript: Dictionary - 1
(0)       Используют 4 человека

Комментарии

Ни одного комментария.
Написать тут
Описание:
-
Автор:
Folder2009
Создан:
19 октября 2021 в 01:11 (текущая версия от 1 января 2022 в 20:04)
Публичный:
Нет
Тип словаря:
Фразы
В этом режиме перемешиваться будут не слова, а целые фразы, разделенные переносом строки.
Информация:
-
Содержание:
1 *
2 ^ code of Javascript include as a separate file
3 a) at the end of </body>
4 `it must be after loading of HTML and CSS
5 b) example
6 `<script src = "script.js"></script>
7 ,if script.js is at the same place as index.html
8 c) don't do with old-fashioned code like this
9 `<script src = "script.js" type = "text/javascript"></script>
10 ,validators make warns on it
11 d) we can make several external .js files
12 ^ API-interface DOM (Document Object Model) allows manipulate HTML and CSS
13 ^ Sequence of doing JS
14 a) the order is from up to down
15 b) be careful in choosing of order
16 c) sample
17 `const para = document.querySelector('p');
18 para.addEventListener('click', updateName);
19 function updateName() {
20 let name = prompt('Enter a new name');
21 para.textContent = 'Player 1: ' + name;
22 }
23 ^ making for all buttons
24 `const buttons = document.querySelectorAll('button');
25 `for(let i = 0; i < buttons.length; i++ {
26 `buttons[i].addEventListener('click', createParagraph);
27 } //doesn't work
28 ^ Comments
29 a) // for one line comment
30 b) /* for several lines comment */
31 *
32 ^ Math.floor(); -- rounds number in less integer
33 a) Math.floor(x); // x -- number
34 b) examples
35 `Math.floor(4.8); // 4
36 `Math.floor(-5.1); // -6
37 c) as floor() is a static method, we always must use Math.floor();
38 d) Math.floor(x, n); // n -- number of rounded
39 `Math.floor(5.35, 2); // 5.3 doesn't work
40 ^ Math.round(); -- rounds number like in maths
41 a) Math.round(x); // x -- number
42 b) examples
43 `Math.round(4.5); // 5
44 `Math.round(4.49) // 4
45 `Math.round(-5); // -5
46 `Math.round(-5.1); // -6
47 * const
48 ^ const can't be changed with new assigning
49 ^ const can't be overridden
50 ^ syntax
51 a) const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
52 `nameN -- name of constant
53 ,follows the same rules as ID of usual variables
54 `valueN -- value of constant
55 , can be any typeOf including function()
56 ^ Description
57 a) const can be both global and local
58 b) in contrast variables, const doesn't become of object Window.
59 c) we must show value and name of constant at the same time, because we can't change the value in the future
60 `const FOO; // will give mistake as it must be value
61 ^ Examples
62 a) ID of constants can be uppercase and lowercase, but according to rule, it's much better to use in UPPERCASE
63 b) const MY_FAV = 7;
64 `console.log("my favourite number is " + MY_FAV);
65 `const MY_FAV = 20; // uncaught syntax error
66 ` if (MY_FAV === 7) {
67 const MY_FAV = 20; // so we can override
68 console.log("my favourite number is " + MY_FAV);
69 var/let = 20; // it will give mistake
70 }
71 ^ const works with objects
72 a) const MY_OBJECT = {"key": "value"};
73 `MY_OBJECT = {"other_key": "value"}; //will give mistake
74 `but MY_OBJECT.key = "otherValue"; // properties of object can be changed
75 ^ const works with massive, similar to objects
76 `const MY_ARRAY = [];
77 a) we can add elements into massive
78 `MY_ARRAY.push("A")
79 b) we can't change link on massive
80 `MY_ARRAY = [B]; // will be mistake
81 * Engines of Browsers
82 ^ V8
83 a) chrome
84 b) opera
85 c) edge
86 ^ Spider Monkey
87 a) Firefox
88 ^ Chakra
89 a) IE
90 ^ SquirrelFish
91 a) Safari
92 *
93 ^ How do engines work?
94 a) the embedded in a browser engine reads or parses the script
95 b) then it converts (compiles) the script to the machine language
96 c) then the machine code runs, pretty fast
97 *
98 ^ what do in-browser js
99 a) add new html to the page
100 `change the existent content
101 `modify styles
102 b) react to user actions
103 `run on mouse clicks
104 `pointer movements
105 `key presses
106 c) send requests over the network to remote servers
107 `download and upload files
108 ,so-called AJAX and COMET technologies
109 d) get and set cookies
110 `ask questions to the visitor
111 `show messages
112 e) remember the data on the client-side
113 `local storage
114 *
115 ^ what can't in-browser js do?
116 a) js's abilities are limited for the sake of a user's safety
117 `the aim is to prevent and evil webpage from accessing private information or harming the user's data
118 *
119 ^ Examples of such languages
120 a) coffeeScript -- a syntactic sugar for js
121 `it introduces shorter syntax, allowing us to write clearer and more precise code
122 `usually, ruby devs like it
123 b) typeScript -- is concentrated on adding "strict data typing" to simplify the development and support of complex systems
124 `it's developed by microsoft
125 c) flow -- add data typing, but in a different way
126 `developed by facebook
127 d) dart -- it's a standalone language that has its own engine that runs in non-browser environments (like mobile apps)
128 `can be transpiled to js
129 `developed by google
130 e) brython -- a python transpiler to js
131 `enables the writing of applications in pure python without js
132 f) kotlin -- a modern, concise and safe programming language that can target the browser or node
133 ^ there are more transpiled languages
134 a) before using them, we should know js very well
135 * Manuals and Specifications
136 ^ page to sources: https://javascript.info/manuals-specifications
137 ^ Specification
138 a) the ecma-262 specification contains the most in-depth, detailed and formalized information about js
139 `released every year
140 ^ Manuals
141 a) MDN js reference -- the main manual with examples and other information
142 `it's great to get in-depth information about individual language functions, methods etc.
143 ^ compatibility tables
144 a) in js new features get added regularly
145 b) supports among browsers of different versions
146 `http://caniuse.com
147 * Code editors
148 ^ it's a place where programmers spend most of their time
149 ^ 2 types of editors
150 a) IDEs
151 b) lightweight editors
152 ^ IDE -- integrated development environment
153 a) refers to a powerful editor with many features that usually operates on a "whole project"
154 b) it's a full-scale "development environment"
155 c) an ide loads the project (which can contain lots of files)
156 `allows navigation between files
157 `provides autocompletion based on the whole project
158 `integrates with a version management system (like git)
159 `a testing environment
160 `other "project-level" stuff
161 d) most favourite ides
162 `visual studio code (free)
163 `webStorm (paid)
164 `visual studio (paid) //don't miss with visual studio code
165 ,only for windows
166 ,well-suited for the .NET platform
167 `visual studio community (free)
168 e) the cost of paid IDEs are usually negligible compared to a qualified developer's salary.
169 ^ Lightweight editors
170 a) they're not as powerful as IDEs, but they're fast, elegant and simple
171 b) mainly used to open and edit a file instantly
172 c) the main difference between IDE and lightweight editor
173 `ide works on a project-level, so it loads much more data on start, analyzes the project structure
174 `a lightweight editor is much faster if we need only one file
175 d) in practise, lightweight editors have a lot of plugins including
176 `directory-level syntax analyzers and autocompleters
177 e) there's no strict border between a lightweight editor and ide
178 f) kinds of lightweight editors
179 `atom (free)
180 `sublime text (shareware)
181 `notepad++ (only windows, free)
182 `vim
183 `emacs
184 * Developer Console
185 ^ in browsers have been embedded "developer tools"
186 a) via it we can see errors, examine variables and lots of useful information
187 b) Chrome and Firefox have the best "developer tools"
188 `other browsers usually play "catch-up"
189 ^ Google Chrome
190 a) open/close developer tools (f12)
191 `usually open tab "console"
192 b) example with error on tab "console"
193 `Uncaught ReferenceError: lalala is not defined
194 ,in the right corner we can see bug.html:12
195 'on the line 12 of file html is bug
196 `below we can see blue arrow
197 ,here we can type js commands
198 'when we start type, developer tools will show us commands, like autocomplete
199 c) multi-line input
200 `if we press just "Enter" after command in console, the command will be executed
201 `but if we want several line, press "Shift + Enter"
202 ^ Firefox, Edge and others
203 a) they quite similar to Chrome, opening with f12 too
204 b) if we learn Chrome, we can easily switch to another one
205 ^ Safari is not supported by windows/linux
206 * JS Fundamentals
207 ^ The simplest code
208 `alert( "hellow world" );
209 ^ Modern markup
210 a) <script type=..> -- old-fashioned
211 `now can be used for js modules
212 b) the language attribute: <script language=...> -- was meant to show the language of the script
213 `now doesn't make sense because js is the default language
214 c) comments before and after scripts
215 `<script type="text/javascript"><!-- ... //--></script>
216 ,for old-fashioned browsers to show them not to read code as they didn't know it
217 ,mustn't use them
218 ^ External Scripts -- better always use
219 a) <script src="/path/to/script.js"></script>
220 b) browser will download it and store it in its cache
221 c) other pages that reference the same script will take it from the cache instead of downloading it
222 `the file is actually downloaded only once
223 d) reduces traffic and makes pages faster
224 ^ if src is set, the script content is ignored
225 a) this won't work
226 `<script src="file.js">
227 `alert(1); // the content is ignored
228 `</script>
229 b) we must choose either an external <script src="..."> or a regular <script> with code
230 c) the example above can be split into two scripts to work
231 `<script src="file.js"></script>
232 `<script>
233 `alert(1);
234 `</script>
235 * Code structure
236 ^ Statements -- syntax constructs and commands that perform actions
237 a) statements can be separated with a semicolon
238 `instead of alert("Hello World");
239 ,alert("Hello");
240 ,alert("World");
241 ^ Semicolons
242 a) a semicolon can be omitted in most cases
243 `when a line break exists
244 `it also works
245 ,alert("hello")
246 ,alert("world")
247 `this called Automatic semicolon insertion
248 ^ In most cases a newline implies a semicolon
249 a) but not always
250 b) example
251 `alert(3 +
252 `1
253 `+ 2);
254 ,here output will be 6, because it's intuitively obvious
255 '+ at the end isn't completed action
256 c) there are situations when js "fails" assume semicolon
257 `it's difficult to fix code with these tiny mistakes
258 d) bad example
259 `alert('hello')
260 `[1, 2].forEach(alert);
261 ,in this case browser will show only 'hello' because of missing semicolon
262 ^ Comments
263 a) we must use often comments to describe what code does and why
264 b) comments can be put into any place of a script
265 c) they don't affect its execution because the engine simply ignores them
266 d) one-line comment start with two forward slash characters //
267 `if // at the start of the line, all line will be in comment
268 `if some code, then //, code will work
269 e) multiline comments start with a forward slash and an asterisk /* and end with an asterisk and a forward slash */. example
270 `/* an example with two messages.
271 `this is a multiple comment.
272 `*/
273 `alert('hello');
274 `alert('world');
275 f) sometimes it can be handy to temporarily disable a part of code
276 `/* alert('hello');
277 `*/
278 `alert('world');
279 ^ Comments (part 2)
280 a) use hotkeys
281 `ctrl + / -- one-line comment (vs code)
282 `shift + alt +a -- multiline comment (vs code)
283 b) nested comments aren't supported, example
284 `/*
285 `/* nested comment */
286 `*/
287 ,such code will die with an error
288 c) many tools which minify code before publishing to a production server
289 `they remove comments as well
290 d) if we really need a nested comment
291 `/*
292 `/* a nested comment works with a back slash *\/
293 `*/
294 * The modern mode, "use strict"
295 ^ introduction
296 a) for a long time, js evolved without compatibility issues
297 b) new features were added to the language while old functionality didn't change
298 c) that had the benefit of never breaking existing code
299 d) but the downside was that any mistake or an imperfect decision made by js's creators got stuck in the language forever
300 e) this was the case until 2009 when ECMAScript 5 (ES5) appeared
301 f) it added new features to the language and modified some of the existing ones
302 ^ introduction (part 2)
303 a) to keep the old code working, most such modifications are off by default.
304 b) you need to explicitly enable them with a special directive:
305 `"use strict"
306 ^ "use strict"
307 a) the directive looks like a string "use strict" or 'use strict'
308 b) when it is located at the top of a script, the whole script works the 'modern' way
309 c) example
310 `"use strict";
311 `// this code works the modern way
312 d) "use strict" can be put at the beginning of a function
313 `doing that enables strict mode in that function only
314 `but usually people use it for the whole script
315 e) make sure that "use strict" is at the top of your script
316 `otherwise strict mode may not be enabled
317 `only comments may appear above 'use strict', example
318 ,// any comment
319 ,"use strict"
320 ,alert('hello');
321 f) there's no way to cancel 'use strict'
322 `there's no directive like 'no use strict' that reverts the engine to old behavior
323 `once we enter strict mode, there's no going back
324 ^ Browser console
325 a) when you use a developer console to run code, please note that it doesn't 'use strict' by default
326 b) sometimes, when 'use strict' makes a difference, you'll get incorrect results
327 c) first, you can try to press shift+enter to input multiple lines, and put 'use strict' on top, like this:
328 `"use strict"; <shift+enter for a newline>
329 `//... your code
330 `<enter to run>
331 d) it works in most browsers, namely firefox and chrome
332 `if it doesn't, e.g. in an old browser, there's an ugly, but reliable way to ensure 'use strict'
333 ,(function() {
334 ,"use strict";
335 ,//... your code here
336 ,})()
337 ^ Should we 'use strict'?
338 a) modern js supports classes and modules -- advanced language structures, that enable 'use strict' automatically
339 `we don't need to add the 'use strict' directive, if we use them
340 b) for now 'use strict'; is a welcome guest at the top of your scripts
341 c) later, when your code is all in classes and modules, you may omit it
342 d) as of now, we've got to know about 'use strict' in general
343 e) there aren't many differences between the strict and old modes.
344 * Variables
345 ^ Introduction
346 a) most of the time, a js application needs to work with information, examples
347 `an online shop -- the information might include goods being sold and a shopping cart
348 `a chat application -- the information might include users, messages and much more
349 b) variables are used to store this information
350 ^ A Variable -- a 'named storage' for data.
351 a) we can use variables to store goodies, visitors and other data
352 b) to create a variable in js, use the 'let' keyword
353 c) the statement below creates (in other words: declares) a variable with the name "message"
354 `let message;
355 d) now we can put some data into it by using the assignment operator "="
356 `let message;
357 `message = 'hello'; // store the string 'hello' in the variable named message
358 e) the string is now saved into the memory area associated with variable
359 f) we can access it using the variable name
360 `let message;
361 `message = 'hello';
362 `alert(message); // shows the variable content
363 g) to be concise, we can combine the variable declaration and assignment into a single line
364 `let message = 'hello'; // define the variable and assign the value
365 `alert(message); // hello
366 ^ A Variable (part 2)
367 a) we can also declare multiple variables in one line
368 `let user = 'john', age = 25, message = 'hello';
369 ,that might seem shorter, but we don't recommend it
370 ,for the sake of better readability, please use a single line per variable
371 b) the multiline variant is a bit longer, but easier to read
372 `let user = 'john';
373 `let age = 25;
374 `let message = 'hello';
375 c) some people often define multiple variables in this multiline style
376 `let user = 'john',
377 `age = 25,
378 `message = 'hello';
379 d) or even in the comma-first style
380 `let user = 'john'
381 `, age = 25
382 `, message = 'hello';
383 e) technically, all these variants do the same thing
384 `it's a matter of personal taste and aesthetics.
385 ^ Var instead of let
386 a) in older scripts, you may also find another keyword
387 `var message = 'hello';
388 b) the var keyword is almost the same as let
389 c) it also declares a variable, but in a slightly different, 'old-school' way
390 ^ A real-life analogy
391 a) 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
392 b) for instance, the variable message can be imagined as a box labeled 'message' with the value 'hello' in it
393 c) we can put any value in the box
394 d) we can also change it as many times as we want
395 `let message = 'hello';
396 `message = 'world'; // value changed
397 `alert(message);
398 e) when the value is changed, the old data is removed from the variable
399 f) we can also declare two variables and copy data from one into the other
400 `let hello = 'hello world';
401 `let message;
402 `message = hello; // copy 'hello world' from hello into message
403 `alert(hello); // hello world
404 `alert(message); // hello world
405 ^ Declaring twice triggers an error
406 a) a variable should be declared only once
407 b) a repeated declaration of the same variable is an error
408 `let message = 'this';
409 `let message = 'that'; // repeated 'let' leads to an error
410 ,we should declare a variable once and then refer to it without let
411 ^ Functional languages
412 a) it's interesting to note that there exist functional programming languages
413 `scala
414 `erlang
415 ,they forbid changing variable values
416 b) in such languages, once the value is stored 'in the box', it's there forever
417 c) if we need to store sth else, the language forces us to create a new box (declare a new variable).
418 d) we can't reuse the old one
419 e) though it may seem a little odd at first sight, these languages are quite capable of serious development
420 f) more than that, there are areas like parallel computations where this limitation confers certain benefits.
421 g) studying such a language (even if you aren't planning to use it soon) is recommended to broaden the mind
422 ^ Variable naming
423 a) there are two limitations on variable names in js
424 `the name must contain only letters, digits or the symbols $ and _
425 `the first character mustn't be a digit
426 b) example of valid names
427 `let userName;
428 `let test123;
429 c) when the name contains multiple words, camelCase is commonly used
430 `words go one after another, each word except first starting with a capital letter: myVeryLongName
431 d) what's interesting - the dollar sign '$' and the underscore '_' can also be used in names
432 `they're regular symbols, just like letters, without any special meaning
433 `these names a valid
434 ,let $ = 1; // declared a variable with the name "$"
435 ,let _ = 2; // declared a variable with the nema "_"
436 ,alert($ + _); // 3
437 e) examples of incorrect variables names
438 `let 1a; // can't start with a digit
439 `let my-name; hyphens '-' aren't allowed in the name
440 ^ Case matters
441 a) variables named apple and Apple are two different variables
442 ^ Non-Latin letters are allowed, but not recommend
443 a) it's possible to use any language, including cyrillic letters or even hieroglyphs
444 `let имя = '...';
445 b) technically, there's no error here
446 c) but there's an international convention to use english in variable names
447 d) even if we're writing a small script, it may have a long life ahead.
448 e) people from other countries may need to read it some time.
449 * Reserved Names
450 ^ Reserved keywords as of ECMAScript 2015
451 a) break
452 b) case
453 c) catch
454 d) class
455 e) const
456 f) continue
457 g) debugger
458 ^ Reserved keywords as of ecmascript 2015 (pat 2)
459 a) default
460 b) delete
461 c) do
462 d) else
463 e) export
464 f) extends
465 g) finally
466 ^ Reserved keywords as of ecmascript 2015 (pat 3)
467 a) for
468 b) function
469 c) if
470 d) import
471 e) in
472 f) insteadof
473 g) new
474 ^ Reserved keywords as of ecmascript 2015 (pat 4)
475 a) return
476 b) super
477 c) switch
478 d) this
479 e) throw
480 f) typeof
481 g) var
482 ^ Reserved keywords as of ecmascript 2015 (pat 5)
483 a) void
484 b) while
485 c) with
486 d) yield
487 e) null
488 f) true
489 g) false
490 ^ Future reserved keywords
491 a) enum
492 b) implements
493 c) interface
494 d) let
495 e) package
496 f) private
497 g) protected
498 ^ Future reserved keywords (part 2)
499 a) public
500 b) static
501 ^ Following reserved when it's found in module code
502 a) await
503 ^ Following works but not in older standart
504 a) abstract
505 b) boolean
506 c) byte
507 d) char
508 e) double
509 f) final
510 g) float
511 ^ Following works but not in older standart (part 2)
512 a) goto
513 b) int
514 c) long
515 d) native
516 e) short
517 f) synchronized
518 ^ Following works but not in older standart (part 3)
519 a) throws
520 b) transient
521 c) volatile
522 * An assignment without use strict
523 ^ Introduction
524 a) normally, we need to define a variable before using it
525 b) but in the old times, it was technically possible to create a variable by a mere assignment of the value without using let
526 c) this still works now if we don't put 'use strict' in our scripts to maintain compatibility with old scripts
527 `// in this example no 'use strict'
528 `num = 5; // the variable 'num' is created
529 `alert(num); // 5
530 d) this is a bad practise and would cause an error in strict mode
531 `"use strict";
532 `num = 5; // error: num is not defined
533 ^ Constants
534 a) declare a constant (unchanging) variable, use const instead of let
535 `const myBirthday = '01.09.1986';
536 b) variables declared using const are called 'constants'
537 c) they can't be reassigned
538 d) an attempt to do so would cause an error
539 `const myBirthday = '01.09.1986';
540 `myBirthday = '25.05.1995'; // error
541 e) when a programmer is sure that a variable will never change, they can declare it with const to guarantee and clearly communicate that fact to everyone
542 ^ Uppercase constants
543 a) there's a widespread practise to use constants as aliases for difficult-to-remember values that are known prior to execution
544 b) such constants are named using capital letters and underscores
545 c) for instance, let's make constants for colors in so-called 'web' format
546 `const COLOR_RED = "#F00";
547 `const COLOR_GREEN = "#0F0";
548 ` // when we need to pick a color
549 `let color = COLOR_GREEN;
550 `alert(color);
551 d) Benefits
552 `COLOR_GREEN is much easier to remember than "#0F0"
553 `when reading the code, COLOR_GREEN is much more meaningful than #0F0
554 `it's much easier to mistype "#0F0" than COLOR_GREEN
555 ^ when should we use capitals for a constant and when should we name it normally?
556 a) being a 'constant' just means that a variable's value never changes.
557 b) but there are constants that are known prior to execution (like a hexadecimal value for red)
558 c) there are constants that are calculated in run-time, during the execution, but don't change after their initial assignment
559 d) example
560 `const pageLoadTime; //time taken by a webpage to load
561 ,the value of pageLoadTime is not known prior to the page load, so it's named normally
562 ,but it's still a constant because it doesn't change after assignment
563 ,in other words, capital-named constants are only used as aliases for 'hard-coded' values
564 * Name things right
565 ^ Introduction
566 a) talking about variables, there's one more extremely important thing
567 b) a variable name should have a clean, obvious meaning, describing the data that it stores
568 c) variable naming is one of the most important and complex skills in programming.
569 d) a quick glance at variable names can reveal which code was written by a beginner versus an experience developer
570 e) in a real project, most of the time is spent modifying and extending an existing code base rather than writing sth completely separate from scratch
571 f) when we return to some code after doing sth else for a while, it's much easier to find information that is well-labeled.
572 g) or, in other words, when the variables have good names
573 ^ Introduction (part 2)
574 a) please spend time thinking about the right name for a variable before declaring it.
575 b) doing so will repay you handsomely.
576 ^ Some good-to-follow rules
577 a) use human-readable names like userName or shoppingCart
578 b) stay away from abbreviations or short names like a, b, c, unless you really know what you're doing
579 c) make names maximally descriptive and concise
580 `examples of bad names -- data and value
581 `such names say nothing
582 `it's only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing
583 d) agree on terms within your team and in your own mind
584 e) if a site visitor is called a "user" then we should name related variables
585 `currentUser or newUser instead of currentVisitor or newManInTown
586 f) Sounds simple? Indeed it is, but creating descriptive and concise variable names in practise is not
587 ^ Reuse or create?
588 a) And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones
589 b) as a result, their variables are like boxes into which people throw different things without changing their stickers
590 c) What's inside the box now? Who knows? We need to come closer and check
591 d) Such programmers save a little bit on variable declaration but lose ten times more on debugging.
592 e) An extra variable is good, not evil
593 f) Modern JavaScript minifiers and browsers optimize code well enough, so it won't create performance issues
594 g) Using different variables for different values can even help the engine optimize your code
595 ^ Summary (Variables)
596 a) We can declare variables to store data by using var, const, or let keywords
597 `let -- is a modern variable declaration
598 `var -- is an old-school variable declaration
599 ,Normally we don't use it at all
600 `const -- is like let, but the value of the variable can't be changed
601 b) Variables should be named in a way that allows us to easily understand what's inside them
602 * Tasks
603 ^ Working with variables
604 a) description
605 `Declare two variables: admin and strangeName
606 `Assign the value "John" to strangeName
607 `Copy the value form strangeName to admin
608 `Show the value of admin using alert (must output 'John')
609 b) Solution
610 `let admin;
611 `let strangeName = 'John';
612 `admin = strangeName;
613 `alert(admin);
614 ^ Giving the right name
615 a) task
616 `create a variable with the name of our planet. How would you name such a variable?
617 `create a variable to store the name of a current visitor to a website. How would you name that variable?
618 b) Solution
619 `let ourPlanetName = "Earth";
620 `let currentUserName = "John";
621 c) it's fine when we name a variable via 3 words (currentUserName)
622 d) don't save on understandable variables
623 ^ Uppercase const
624 a) examine the following code
625 `const BIRTHDAY = '18.04.1982'; // important with UPPERCASE
626 `const age = someCode(BIRTHDAY); // not important
627 b) we generally use upper case for constants that are 'hard-coded'.
628 `in other words, when the value is known prior to execution and directly written into the code
629 `in this code, birthday is exactly like that
630 c) in contrast, age is evaluated in run-time
631 `today we have one age, a year after we'll have another one.
632 `it's constant in a sense that it doesn't change through the code execution.
633 `but is's a bit 'less of a constant' than birthday
634 ,it's calculated, so we should keep the lower case for it.
635 * Data Types
636 ^ Description
637 a) A value in js is always of a certain type, e.g. a string or a number
638 b) There are eight basic data types in js.
639 c) here, we'll cover them in general and in the next chapters we'll talk about each of them in detail.
640 d) We can put any type in a variable, e.g. a variable can at one moment be a string and then store a number
641 `let message = 'hello';
642 message = 123456; // no error
643 e) Programming languages that allows such things, such as js, are called 'dynamically typed', meaning that there exist data types, but they're not bound to any of them
644 ^ Number
645 a) let n = 123;
646 `n = 124; // 124 as js shows the last one
647 b) the number type represents both integer and floating point numbers
648 c) There are many operations for numbers, e.g.
649 `multiplication *
650 `division /
651 `subtraction -
652 `addition +
653 d) Besides regular numbers, there are so-called 'special numeric values' which also belong to this data type
654 `Infinity
655 `-Infinity
656 `NaN
657 e) infinity represents the mathematical infinity (sigh of limitlessness)
658 `it's a special value that's greater than any number
659 `we can get it as a result of division by zero
660 ,alert(1/0);
661 `or just reference it directly
662 ,alert(infinity); // infinity
663 f) NaN represents a computational error
664 `it's a result of an incorrect or an undefined mathematical operation
665 ,alert('not a number' / 2); // NaN
666 `NaN is sticky, any further operation on NaN returns NaN
667 ,alert('not a number' / 2 + 5); // NaN
668 `so, if there's a NaN somewhere in a mathematical expression, it propagates to the whole result
669 ^ Mathematical operations are safe
670 a) doing maths is 'safe' in js
671 b) we can do anything
672 `divide by zero
673 `treat non-numeric strings as numbers
674 c) the script will never stop with the fatal error ('die')
675 d) at worst, we'll get NaN as the result
676 e) special numeric values formally belong to the number type
677 `of coarse they aren't numbers in the common sense of this word
678 * BigInt
679 ^ Description
680 a) in js, the number type can't represent integer values larger than (2in53 - 1), or less than -(2in53 - 1) for negatives
681 `it's a technical limitation caused by their internal representation
682 b) for most purposes that's quite enough, but sometimes we need really big numbers
683 `for cryptography or microsecond-precision timestamps.
684 c) BigInt type was recently added to the language to represent integers of arbitrary length.
685 d) a BigInt value is created by appending 'n' to the end of an integer
686 `const BigInt = 123434132414313417512857712851951n;
687 ,the 'n' at the end means it's a BigInt
688 ,otherwise vie exponenta will be result
689 e) as bit numbers are rarely needed, we don't cover them here
690 f) right now, BigInt is supported in Firefox/Chrome/Edge/Safari, but not in IE
691 * String
692 ^ Introduction
693 a) a string in js must be surrounded by quotes
694 `let str = "hello";
695 `let str2 = 'single quotes are ok too';
696 `let phrase = `can embed another ${str}`;
697 b) in js there are 3 types of quotes
698 `double quotes "hello";
699 `single quotes 'hello';
700 `backticks `hello`;
701 c) double and single quotes are 'simple' quotes.
702 `there's practically no difference between them in js
703 d) backticks are 'extended functionality' quotes.
704 `they allows us to embed variables and expressions into a string by wrapping them in ${...}, example
705 `let name = "John";
706 `// embed a variable
707 `alert(`hello, ${name}!`); // hello, John!
708 `// embed an expression
709 `alert(`ther result is ${1 + 2}`); // the result is 3
710 e) the expression inside ${...} is evaluated and the result becomes a part of the string.
711 `we can put anything in there: a variable like name or an arithmetical expression like 1 + 2 or sth more complex
712 `please note that this can only be done in backticks
713 ,other quotes don't have this embedding functionality
714 ^ there's no character type
715 a) in some languages, there's a special 'character' type for a single character
716 b) in the C language and in Java it is called 'char'
717 c) in js, there's no such type
718 `there's only one type: string
719 `a string may consist of
720 ,zero character (be empty)
721 ,one character or many of them
722 * Boolean (logical type)
723 ^ Introduction
724 a) the boolean type has only two values:
725 `true
726 `false
727 b) this type is commonly used to store yes/no values
728 `true means 'yes, correct'
729 `false means 'no, incorrect'
730 c) example
731 `let nameFieldChecked = true; // yes, name field is checked
732 `let ageFieldChecked = false; // no, age field isn't checked
733 d) Boolean values also come as a result of comparisons
734 `let isGreater = 4 > 1;
735 `alert(isGreater); true (the comparison result is 'yes')
736 * the Null value
737 ^ Introduction
738 a) the special null value doesn't belong to any of the types described above
739 b) it forms a separate type of its own which contains only the null value
740 `let age = null;
741 c) in js, null is not a 'reference to a non-existing object' or a 'null pointer' like in some other languages
742 d) it's just a special value which represents 'nothing', 'empty' or 'value unknown'
743 e) the code above states that age is unknown
744 * the 'Undefined' value
745 ^ Introduction
746 a) the special value undefined also stands apart
747 b) it makes a type of its own, just like null
748 c) the meaning of undefined is 'value is not assigned'
749 d) if a variable is declared, but not assigned, then its value is undefined
750 `let age;
751 `alert(age); // shows undefined
752 e) technically, it's possible to explicitly assign undefined to a variable
753 `let age = 100;
754 `// change the value to undefined
755 `age = undefined;
756 `alert(age); // undefined
757 f) but we don't recommend doing that.
758 g) normally, one uses null to assign an 'empty' or 'unknown' value to a variable, while undefined is reserved as a default initial value for unassigned things
759 * Objects and Symbols
760 ^ Object
761 a) the object type is special
762 b) all other types are called 'primitive' because their values can contain only a single thing (be it a string or a number or whatever)
763 c) in contrast, objects are used to store collections of data and more complex entities
764 d) being that important, objects deserve a special treatment
765 ^ Symbol
766 a) the symbol type is used to create unique identifiers for objects.
767 * The typeof operator
768 ^ Introduction
769 a) the typeof operator returns the type of the argument
770 b) it's useful when we want to process values of different types differently or just want to do a quick check
771 c) it supports two forms of syntax
772 `as an operator: typeof x
773 `as a function: typeof(x)
774 d) in other words, it works with parentheses or without them
775 `the result is the same
776 ^
777 a) the call to typeof x returns a string with the type name
778 `typeof undefined // 'undefined'
779 `typeof 0 // 'number'
780 `typeof 10n // 'bigint'
781 `typeof true // 'boolean'
782 `typeof 'foo' // 'string'
783 `typeof Symbol('id') // 'symbol'
784 `typeof Math // 'object'
785 `typeof null // 'object'
786 `typeof alert // 'function'
787 b) Math is a built-on object that provides mathematical operations
788 c) the result of typeof null is object.
789 `that's an officially recognized error in typeof behavior, coming from the early days of js and kept for compatibility
790 `definitely, null is not an object
791 `it's a special value with a separate type of its own
792 d) the result of typeof alert is function.
793 `functions belong to the object type
794 `but typeof treats them differently, returning 'function'
795 * Summary Data Types
796 ^ there are 8 basic data types in js
797 a) number -- for numbers of any kind
798 `integer or floating-point
799 `integers are limited by +-(2in53 - 1)
800 b) bigint -- for integer numbers of arbitrary length
801 c) string -- for strings
802 `a string may have zero or more characters, there's no separate single-character type
803 d) boolean -- for true or false
804 e) null -- for unknown values
805 `a standalone type that has a single value null
806 f) undefined -- for unassigned values
807 `a standalone type that has a single value undefined
808 g) object -- for more complex data structures
809 h) symbol -- for unique identifiers
810 ^ typeof operator -- allows us to see which type is stored in a variable
811 a) two forms: typeof x or typeof(x)
812 b) returns a string with the name of the type, like 'string'
813 c) for null returns 'object' -- this is an error in the language, it's not actually an object
814 * Tasks Data Types
815 ^ what is the output of the script?
816 `let name = 'Ilya';
817 `alert(`hello ${1}`); // hello 1
818 `alert(`hello ${'name'}`); // hello name
819 `alert(`hello ${name}`); // hello Ilya
820 * Interaction: alert, prompt, confirm
821 ^ Introduction
822 a) as we'll be using the browser as our demo environment, let's see a couple of functions to interact with the user
823 `alert
824 `prompt
825 `confirm
826 ^ Alert
827 a) it shows a message and waits for the user to press ok
828 `alert('hello');
829 b) the mini-window with the message is called a modal window
830 c) the word 'modal' means the the visitor can't interact with the rest of the page, press other buttons, etc., until they have deal with the window
831 `in this case, until they press ok
832 ^ Prompt
833 a) the function prompt accepts two arguments
834 `result = prompt(title, [default]);
835 b) it shows a modal window with a text message, an input field for the visitor, and the buttons ok/cancel
836 c) title -- the text to show the visitor
837 d) default -- an optional second parameter, the initial value for the input field
838 e) the square brackets around default in the syntax above denote that the parameter is optional, not required.
839 f) the visitor can type sth in the prompt input field and press ok.
840 `then we get that text in the result
841 `or they can cancel the input by pressing cancel or hitting the esc key, then we get null as the result
842 g) the call to prompt returns the text from the input field or null if the input was cancelled
843 `let age = prompt('how old are you?', 100); // if 100 don't insert, it's ok
844 `alert(`you're ${age} years old`); // you're a 100 years old
845 ^ Prompt (part 2)
846 a) in IE always supply a default
847 `the second parameter is optional, but if we don't supply it, IE will insert the text 'undefined' into the prompt
848 `so, for prompts to look good in IE, we recommend always providing the second argument
849 `let test = prompt('test', ' ');
850 ^ Confirm
851 a) the syntax
852 `result = confirm(question);
853 b) the function confirm shows a modal window with a question and two buttons: ok and cancel
854 c) the result is true if ok is pressed, otherwise false
855 `let isBoss = confirm('are you the boss?');
856 `alert(isBoss); // true if ok is pressed
857 ^ Summary
858 a) we covered 3 browser-specific functions to interact with visitors
859 b) alert -- shows a message
860 c) prompt -- shows a message asking the user to input text
861 `it returns the text or, if cancel button or esc ic clicked, null
862 d) confirm -- shows the message and waits for the user to press 'ok' or 'cancel
863 `it returns true for ok and false for cancel/esc
864 e) all these methods are modal
865 `they pause script execution and don't allow the visitor to interact with the rest of the page until the window has been dismissed
866 f) there are two limitations shared by all the methods above
867 `the exact location of the modal is determined by the browser
868 ,usually, it's in the centre
869 `the exact look of the window also depends on the browser.
870 ,we can't modify it
871 g) that's is the price for simplicity
872 ^ Summary (part 2)
873 a) there are other ways to show nicer windows and richer interaction with the visitor
874 b) but if 'bells and whistles' do not matter much, these methods work just fine
875 ^ Tasks: A simple page
876 a) create a web page that asks for a name and outputs it.
877 `let currentUserName = prompt("What's your name?", "");
878 `alert(currentUserName);
879 * Type Conversions
880 ^ Introduction
881 a) most of the time, operators and functions automatically convert the values given to them to the right type
882 `alert automatically converts any value to a string to show it
883 `mathematical operations convert values to numbers
884 b) there are also cases when we need to explicitly convert a value to the expected type
885 ^ Not talking about objects yet
886 a) in this chapter we won't cover objects
887 b) for now we'll just be talking about primitives
888 ^ String Conversion
889 a) string conversion happens when we need the string form of a value
890 `alert(value) does it to show the value
891 b) we can also call the String(value) function to convert a value to a string
892 `let value = true;
893 `alert(typeof value); // boolean
894 `value = String(value); now value is a string 'true'
895 `alert(typeof value); // string
896 c) string conversion is mostly obvious
897 `a false becomes 'false'
898 `null becomes 'null', etc.
899 ^ Numeric Conversion
900 a) numeric conversion happens in mathematical functions and expressions automatically
901 b) when division / is applied to non-numbers
902 `alert('6' / '2'); // 3, strings are converted to numbers
903 c) we can use the Number(value) function to explicitly convert a value to a number
904 `let str = '123';
905 `alert(typeof str); // string
906 `let num = Number(str);
907 `alert(typeof num); // number
908 d) explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered
909 e) if the string is not a valid number, the result of such a conversion is NaN
910 `let age = Number('an arbitrary string instead of number');
911 `alert(age); // NaN, conversion failed
912 ^ Numeric conversion rules
913 a) value undefined becomes NaN
914 b) value null becomes 0
915 c) value true and false becomes 1 and 0
916 d) value string becomes:
917 `whitespaces from the start and end are removed
918 `if the remaining string is empty, the result is 0
919 `otherwise, the number is 'read' from the string
920 `an error gives NaN
921 e) examples
922 `alert(Number(" 123 ")); // 123
923 `alert(Number("123z")); // NaN (error reading a number at 'z')
924 `alert(Number(true)); // 1
925 `alert(Number(false)); // 0
926 f) please note that null and undefined behave differently here
927 g) most mathematical operators also perform such conversion
928 * Boolean Conversion
929 ^ Introduction
930 a) boolean conversion is the simplest one
931 b) it happens in logical operations, but can also be performed explicitly with a call to Boolean(value)
932 c) the conversion rule
933 `values that are intuitively 'empty', like 0, an empty string, null, undefined and NaN, become false
934 `other values become true
935 d) example
936 `alert(Boolean(1)); // true
937 `alert(Boolean(0)); // false
938 `alert(Boolean('hello')); // true
939 `alert(Boolean("")); // false
940 e) please note the string with zero "0" and spaces " " are true
941 `alert(Boolean('0')); // true
942 `alert(Boolean(' ')); // true
943 f) some languages (namely PHP) treat "0" as false
944 * Summary Type Conversion
945 ^ the three most widely used type conversions are to string, to number, and to boolean
946 ^ String Conversion -- occurs when we output sth.
947 a) can be performed with String(value)
948 b) the conversion to string is usually obvious for primitive values
949 ^ Numeric Conversion -- occurs in math operations.
950 a) can be performed with Number(value)
951 b) the conversion follows the rules: value - becomes
952 `undefined - NaN
953 `null - 0
954 `true/false - 1/0
955 `string - whitespaces from both sides are ignored; an empty string becomes 0; an error gives NaN
956 ^ Boolean Conversion -- occurs in logical operations.
957 a) can be performed with Boolean(value)
958 b) follows the rules: value - becomes
959 `0, null, undefined, NaN, "" - false
960 `any other value - true
961 ^ most of these rules are easy to understand and memorize
962 a) the notable exceptions where people usually make mistakes are
963 `undefined is NaN as a number, not 0
964 `"0" and space-only strings like " " are true as a boola
965 `but in js, a non-emtpy string is always true
966 * Basic operators, maths
967 ^ Introduction
968 a) we know many operators from school.
969 b) they're thinks like addition +, multiplication *, subtraction -, and so on
970 ^ Terms 'unary', 'binary', 'operand'
971 a) An operand -- is what operators are applied to.
972 b) example, in the multiplication of 5 * 2 there are two operands
973 `the left operand is 5
974 `the right operand is 2
975 c) sometimes, people call these 'arguments' instead of 'operands'
976 d) an operator is unary if it has a single operand
977 e) example, the unary negation - reverses the sign of a number
978 `let x = 1;
979 `x = -x;
980 `alert(x); // -1, unary negation was applied
981 f) an operator is binary if it has two operands
982 g) the same minus exists in binary form as well
983 `let x = 1, y = 3;
984 `alert(y - x); // 2, binary minus subtracts values
985 ^ Temrs 'unary', 'binary', 'operand' (part 2)
986 a) formally, in the examples above we have two different operators that share the same symbol
987 `the negation operator, a unary operator that reverses the sign
988 `the subtraction operator, a binary operator that subtracts one number from another
989 ^ Maths
990 a) the following math operations are supported
991 `addition +
992 `subtraction -
993 `multiplication *
994 `division /
995 `remainder %
996 `exponentiation **
997 b) the first four are straightforward, while % and ** need a few words about them
998 ^ Maths > Remainder %
999 a) The remainder operator %, despite its appearance, is not related to percents
1000 b) the result of a % b is the remainder of the integer division of a by b
1001 c) example
1002 `alert(5 % 2); // 1
1003 `alert(8 % 3); // 2
1004 ^ Maths > Exponentiation **
1005 a) the exponentiation operator a ** b raises a to the power of b
1006 b) example
1007 `alert (2 ** 2); // 4
1008 `alert (2 ** 3); // 8
1009 c) just like in maths, the exponentiation operator is defined for non-integer numbers as well
1010 d) example for a square root
1011 `alert(4 ** (1/2)); // 2
1012 * String concatenation with binary +
1013 ^
1014 a) let's meet features of js operators that are beyond school arithmetics
1015 b) usually, the plus operators + sums numbers
1016 c) but, if the binary + is applied to a string, it merges (concatenates) them
1017 `let s = 'my' + 'string';
1018 `alert(s); // mystring
1019 d) note if any of the operands is a string, then the other one is converted to a string too
1020 `alert('1' + 2); // 12 (string)
1021 `alert(2 + '1'); // 21 (string)
1022 e) see, it doesn't matter whether the first operand is a string or the second one
1023 f) here's a more complex example
1024 `alert(2 + 2 + '1'); // 41
1025 g) here operators work one after another
1026 h) the first sums two numbers, so it returns 4, then the next + adds the string 1 to it, so it's like 4 + '1' = 41
1027 ^ String concatenation with binary + (part 2)
1028 a) another example
1029 `alert('1' + 2 + 2); // 122
1030 b) here, ther first operand is a string, the compiler treats the other two operands as strings too.
1031 c) the 2 gets concatenated to '1', so it's like '1' + 2 = '12' and '12' + 2 = '122'
1032 d) the binary plus is the only operator that supports strings in such a way
1033 e) other arithmetic operators work only with numbers and always convert their operands to numbers
1034 f) here's the demo for subtraction and division
1035 `alert(6 - '2'); // 4 converts '2' to a number
1036 `alert('6' / '2'); // 3
1037 * Numeric Conversion, unary +
1038 ^ Introduction
1039 a) the plus + exists in two forms
1040 `the binary form that we used above
1041 `the unary form
1042 ^ Description
1043 a) the unary plus or the plus operator + applied to a single value
1044 `doesn't do anything to numbers
1045 b) if the operand is not a number, the unary plus converts it into a number
1046 `// no effect on numbers
1047 `let x = 1;
1048 `alert(+x); // 1
1049 `// converts non-numbers
1050 `alert(+true); // 1
1051 `alert(+""); // 0
1052 c) it actually does the same thing as Number(...), but is shorter
1053 d) the need to convert strings to numbers arises very often
1054 `if we are getting values from HTML form fields, they're usually strings
1055 `what if we want to sum them?
1056 `the binary plus would add them as strings
1057 e) example
1058 `let apples = '2';
1059 `let oranges = '3';
1060 `alert(apples + oranges); // 23, the binary plus concatenates strings
1061 f) if we want treat them as numbers, we need to convert and then sum them
1062 `let apples = '2';
1063 `let oranges = '3';
1064 `alert(+apples + +oranges); // 5, the unary pluses
1065 `// the longer variant
1066 `// alert(Number(apples) + Number(oranges)); // 5
1067 g) from a mathematician's standpoint, the abundance of pluses may seem strange
1068 h) bur from a programmer's standpoint, there's nothing special
1069 `unary pluses are applied first, they convert strings to numbers
1070 `and then the binary plus sums them up.
1071 ^ Description (part 2)
1072 a) why are unary pluses applied to values before the binary ones?
1073 `as we're going to see, that's because of their higher precedence

Связаться
Выделить
Выделите фрагменты страницы, относящиеся к вашему сообщению
Скрыть сведения
Скрыть всю личную информацию
Отмена