Javascript info Ebook Part 1 The JavaScript language 1st Edition Ilya Kantor - The ebook in PDF format with all chapters is ready for download
Javascript info Ebook Part 1 The JavaScript language 1st Edition Ilya Kantor - The ebook in PDF format with all chapters is ready for download
com
https://textbookfull.com/product/javascript-info-ebook-
part-1-the-javascript-language-1st-edition-ilya-kantor/
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/javascript-info-ebook-
part-3-additional-articles-1st-edition-ilya-kantor/
textbookfull.com
https://textbookfull.com/product/javascript-info-ebook-part-2-browser-
document-events-interfaces-1st-edition-ilya-kantor/
textbookfull.com
https://textbookfull.com/product/javascript-design-
patterns-1-converted-edition-hugo-di-francesco/
textbookfull.com
https://textbookfull.com/product/the-joy-of-javascript-1st-edition-
atencio/
textbookfull.com
https://textbookfull.com/product/practical-modern-javascript-dive-
into-es6-and-the-future-of-javascript-nicolas-bevacqua/
textbookfull.com
https://textbookfull.com/product/simplifying-javascript-writing-
modern-javascript-with-es5-es6-and-beyond-1st-edition-joe-morgan/
textbookfull.com
Part 1
The JavaScript
language
Ilya Kantor
Built at July 10, 2019
The last version of the tutorial is at https://javascript.info.
We constantly work to improve the tutorial. If you find any mistakes, please write at our github.
● An introduction
●
An Introduction to JavaScript
●
Manuals and specifications
● Code editors
●
Developer console
● JavaScript Fundamentals
● Hello, world!
● Code structure
●
The modern mode, "use strict"
● Variables
●
Data types
● Type Conversions
●
Operators
● Comparisons
●
Interaction: alert, prompt, confirm
●
Conditional operators: if, '?'
●
Logical operators
●
Loops: while and for
●
The "switch" statement
●
Functions
● Function expressions and arrows
● JavaScript specials
● Code quality
● Debugging in Chrome
● Coding Style
● Comments
●
Ninja code
● Automated testing with mocha
● Polyfills
●
Objects: the basics
●
Objects
● Garbage collection
● Symbol type
●
Object methods, "this"
● Object to primitive conversion
● Constructor, operator "new"
●
Data types
● Methods of primitives
● Numbers
● Strings
●
Arrays
● Array methods
● Iterables
●
Map, Set, WeakMap and WeakSet
●
Object.keys, values, entries
● Destructuring assignment
● Date and time
●
JSON methods, toJSON
● Advanced working with functions
● Recursion and stack
● Rest parameters and spread operator
● Closure
● The old "var"
● Global object
● Function object, NFE
● The "new Function" syntax
● Scheduling: setTimeout and setInterval
●
Decorators and forwarding, call/apply
● Function binding
● Currying and partials
●
Arrow functions revisited
● Object properties configuration
● Property flags and descriptors
●
Property getters and setters
● Prototypes, inheritance
● Prototypal inheritance
● F.prototype
● Native prototypes
● Prototype methods, objects without __proto__
● Classes
● Class basic syntax
● Class inheritance
● Static properties and methods
● Private and protected properties and methods
● Extending built-in classes
●
Class checking: "instanceof"
● Mixins
● Error handling
●
Error handling, "try..catch"
● Custom errors, extending Error
● Promises, async/await
● Introduction: callbacks
● Promise
● Promises chaining
● Error handling with promises
● Promise API
● Promisification
● Microtasks
● Async/await
● Generators, advanced iteration
●
Generators
● Async iterators and generators
● Modules
●
Modules, introduction
● Export and Import
● Dynamic imports
●
Miscellaneous
●
Proxy and Reflect
● Eval: run a code string
Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP.
We concentrate on the language itself here, with the minimum of environment-specific notes.
An introduction
About the JavaScript language and the environment to develop with it.
An Introduction to JavaScript
Let’s see what’s so special about JavaScript, what we can achieve with it, and which other
technologies play well with it.
What is JavaScript?
The programs in this language are called scripts. They can be written right in a web page’s
HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
In this aspect, JavaScript is very different from another language called Java .
Why JavaScript?
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very
popular at that time, so it was decided that positioning a new language as a “younger
brother” of Java would help.
But as it evolved, JavaScript became a fully independent language with its own specification
called ECMAScript , and now it has no relation to Java at all.
Today, JavaScript can execute not only in the browser, but also on the server, or actually on any
device that has a special program called the JavaScript engine .
The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
The terms above are good to remember because they are used in developer articles on the
internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably
works in Chrome and Opera.
How do engines work?
Engines are complicated. But the basics are easy.
The engine applies optimizations at each step of the process. It even watches the compiled
script as it runs, analyzes the data that flows through it, and applies optimizations to the
machine code based on that knowledge. When it’s done, scripts run quite fast.
Modern JavaScript is a “safe” programming language. It does not provide low-level access to
memory or CPU, because it was initially created for browsers which do not require it.
JavaScript’s capabilities greatly depend on the environment it’s running in. For instance,
Node.js supports functions that allow JavaScript to read/write arbitrary files, perform network
requests, etc.
In-browser JavaScript can do everything related to webpage manipulation, interaction with the
user, and the webserver.
JavaScript’s abilities in the browser are limited for the sake of the user’s safety. The aim is to
prevent an evil webpage from accessing private information or harming the user’s data.
Examples of such restrictions include:
● JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or
execute programs. It has no direct access to OS system functions.
Modern browsers allow it to work with files, but the access is limited and only provided if the
user does certain actions, like “dropping” a file into a browser window or selecting it via an
<input> tag.
There are ways to interact with camera/microphone and other devices, but they require a
user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web-
camera, observe the surroundings and send the information to the NSA .
● Different tabs/windows generally do not know about each other. Sometimes they do, for
example when one window uses JavaScript to open the other one. But even in this case,
JavaScript from one page may not access the other if they come from different sites (from a
different domain, protocol or port).
This is called the “Same Origin Policy”. To work around that, both pages must agree for data
exchange and contain a special JavaScript code that handles it. We’ll cover that in the
tutorial.
This limitation is, again, for the user’s safety. A page from http://anysite.com which a
user has opened must not be able to access another browser tab with the URL
http://gmail.com and steal information from there.
● JavaScript can easily communicate over the net to the server where the current page came
from. But its ability to receive data from other sites/domains is crippled. Though possible, it
requires explicit agreement (expressed in HTTP headers) from the remote side. Once again,
that’s a safety limitation.
Such limits do not exist if JavaScript is used outside of the browser, for example on a server.
Modern browsers also allow plugin/extensions which may ask for extended permissions.
That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating
browser interfaces.
While planning to learn a new technology, it’s beneficial to check its perspectives. So let’s move
on to the modern trends affecting it, including new languages and browser abilities.
The syntax of JavaScript does not suit everyone’s needs. Different people want different
features.
That’s to be expected, because projects and requirements are different for everyone.
Modern tools make the transpilation very fast and transparent, actually allowing developers to
code in another language and auto-converting it “under the hood”.
There are more. Of course, even if we use one of transpiled languages, we should also know
JavaScript to really understand what we’re doing.
Summary
● JavaScript was initially created as a browser-only language, but is now used in many other
environments as well.
●
Today, JavaScript has a unique position as the most widely-adopted browser language with
full integration with HTML/CSS.
● There are many languages that get “transpiled” to JavaScript and provide certain features. It
is recommended to take a look at them, at least briefly, after mastering JavaScript.
Specification
The ECMA-262 specification contains the most in-depth, detailed and formalized information
about JavaScript. It defines the language.
But being that formalized, it’s difficult to understand at first. So if you need the most trustworthy
source of information about the language details, the specification is the right place. But it’s not
for everyday use.
To read about new bleeding-edge features, that are “almost standard”, see proposals at
https://github.com/tc39/proposals .
Also, if you’re in developing for the browser, then there are other specs covered in the second
part of the tutorial.
Manuals
● MDN (Mozilla) JavaScript Reference is a manual with examples and other information. It’s
great to get in-depth information about individual language functions, methods etc.
Although, it’s often best to use an internet search instead. Just use “MDN [term]” in the query,
e.g. https://google.com/search?q=MDN+parseInt to search for parseInt function.
●
MSDN – Microsoft manual with a lot of information, including JavaScript (often referrerd to as
JScript). If one needs something specific to Internet Explorer, better go there:
http://msdn.microsoft.com/ .
Also, we can use an internet search with phrases such as “RegExp MSDN” or “RegExp
MSDN jscript”.
Feature support
All these resources are useful in real-life development, as they contain valuable information
about language details, their support etc.
Please remember them (or this page) for the cases when you need in-depth information about a
particular feature.
Code editors
A code editor is the place where programmers spend most of their time.
There are two main types of code editors: IDEs and lightweight editors. Many people use one
tool of each type.
IDE
The term IDE (Integrated Development Environment) refers to a powerful editor with many
features that usually operates on a “whole project.” As the name suggests, it’s not just an editor,
but a full-scale “development environment.”
An IDE loads the project (which can be many files), allows navigation between files, provides
autocompletion based on the whole project (not just the open file), and integrates with a version
management system (like git ), a testing environment, and other “project-level” stuff.
For Windows, there’s also “Visual Studio”, not to be confused with “Visual Studio Code”. “Visual
Studio” is a paid and mighty Windows-only editor, well-suited for the .NET platform. It’s also
good at JavaScript. There’s also a free version Visual Studio Community .
Many IDEs are paid, but have a trial period. Their cost is usually negligible compared to a
qualified developer’s salary, so just choose the best one for you.
Lightweight editors
“Lightweight editors” are not as powerful as IDEs, but they’re fast, elegant and simple.
The main difference between a “lightweight editor” and an “IDE” is that an IDE works on a
project-level, so it loads much more data on start, analyzes the project structure if needed and
so on. A lightweight editor is much faster if we need only one file.
In practice, lightweight editors may have a lot of plugins including directory-level syntax
analyzers and autocompleters, so there’s no strict border between a lightweight editor and an
IDE.
The editors in the lists above are those that either I or my friends whom I consider good
developers have been using for a long time and are happy with.
There are other great editors in our big world. Please choose the one you like the most.
The choice of an editor, like any other tool, is individual and depends on your projects, habits,
and personal preferences.
Developer console
Code is prone to errors. You will quite likely make errors… Oh, what am I talking about? You are
absolutely going to make errors, at least if you’re a human, not a robot .
But in the browser, users don’t see errors by default. So, if something goes wrong in the script,
we won’t see what’s broken and can’t fix it.
To see errors and get a lot of other useful information about scripts, “developer tools” have been
embedded in browsers.
Most developers lean towards Chrome or Firefox for development because those browsers
have the best developer tools. Other browsers also provide developer tools, sometimes with
special features, but are usually playing “catch-up” to Chrome or Firefox. So most developers
have a “favorite” browser and switch to others if a problem is browser-specific.
Developer tools are potent; they have many features. To start, we’ll learn how to open them,
look at errors, and run JavaScript commands.
Google Chrome
There’s an error in the JavaScript code on it. It’s hidden from a regular visitor’s eyes, so let’s
open developer tools to see it.
Press F12 or, if you’re on Mac, then Cmd+Opt+J .
The exact look of developer tools depends on your version of Chrome. It changes from time to
time but should be similar.
●
Here we can see the red-colored error message. In this case, the script contains an unknown
“lalala” command.
●
On the right, there is a clickable link to the source bug.html:12 with the line number
where the error has occurred.
Below the error message, there is a blue > symbol. It marks a “command line” where we can
type JavaScript commands. Press Enter to run them ( Shift+Enter to input multi-line
commands).
Now we can see errors, and that’s enough for a start. We’ll come back to developer tools later
and cover debugging more in-depth in the chapter Debugging in Chrome.
The look & feel of them is quite similar. Once you know how to use one of these tools (you can
start with Chrome), you can easily switch to another.
Safari
Safari (Mac browser, not supported by Windows/Linux) is a little bit special here. We need to
enable the “Develop menu” first.
Open Preferences and go to the “Advanced” pane. There’s a checkbox at the bottom:
Now Cmd+Opt+C can toggle the console. Also, note that the new top menu item named
“Develop” has appeared. It has many commands and options.
Multi-line input
Usually, when we put a line of code into the console, and then press Enter , it executes.
Summary
●
Developer tools allow us to see errors, run commands, examine variables, and much more.
● They can be opened with F12 for most browsers on Windows. Chrome for Mac needs
Cmd+Opt+J , Safari: Cmd+Opt+C (need to enable first).
Now we have the environment ready. In the next section, we’ll get down to JavaScript.
JavaScript Fundamentals
Let’s learn the fundamentals of script building.
Hello, world!
This part of the tutorial is about core JavaScript, the language itself. Later on, you’ll learn about
Node.js and other platforms that use it.
But we need a working environment to run our scripts and, since this book is online, the
browser is a good choice. We’ll keep the amount of browser-specific commands (like alert )
to a minimum so that you don’t spend time on them if you plan to concentrate on another
environment (like Node.js). We’ll focus on JavaScript in the browser in the next part of the
tutorial.
So first, let’s see how we attach a script to a webpage. For server-side environments (like
Node.js), you can execute the script with a command like "node my.js" .
JavaScript programs can be inserted into any part of an HTML document with the help of the
<script> tag.
For instance:
<!DOCTYPE HTML>
<html>
<body>
<script>
alert( 'Hello, world!' );
</script>
</body>
</html>
The <script> tag contains JavaScript code which is automatically executed when the
browser processes the tag.
Modern markup
The <script> tag has a few attributes that are rarely used nowadays but can still be found in
old code:
<script type="text/javascript"><!--
...
//--></script>
This trick isn’t used in modern JavaScript. These comments hid JavaScript code from old
browsers that didn’t know how to process the <script> tag. Since browsers released in the
last 15 years don’t have this issue, this kind of comment can help you identify really old code.
External scripts
<script src="/path/to/script.js"></script>
Here, /path/to/script.js is an absolute path to the script file (from the site root).
You can also provide a relative path from the current page. For instance, src="script.js"
would mean a file "script.js" in the current folder.
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
…
Please note:
As a rule, only the simplest scripts are put into HTML. More complex ones reside in
separate files.
The benefit of a separate file is that the browser will download it and store it in its cache .
Other pages that reference the same script will take it from the cache instead of
downloading it, so the file is actually downloaded only once.
That reduces traffic and makes pages faster.
A single <script> tag can’t have both the src attribute and code inside.
<script src="file.js">
alert(1); // the content is ignored, because src is set
</script>
<script src="file.js"></script>
<script>
alert(1);
</script>
Summary
● We can use a <script> tag to add JavaScript code to a page.
● The type and language attributes are not required.
●
A script in an external file can be inserted with <script src="path/to/script.js">
</script> .
There is much more to learn about browser scripts and their interaction with the webpage. But
let’s keep in mind that this part of the tutorial is devoted to the JavaScript language, so we
shouldn’t distract ourselves with browser-specific implementations of it. We’ll be using the
browser as a way to run JavaScript, which is very convenient for online reading, but only one of
many.
✔ Tasks
Show an alert
importance: 5
Do it in a sandbox, or on your hard drive, doesn’t matter, just ensure that it works.
To solution
Take the solution of the previous task Show an alert. Modify it by extracting the script content
into an external file alert.js , residing in the same folder.
To solution
Code structure
The first thing we’ll study is the building blocks of code.
Statements
We can have as many statements in our code as we want. Statements can be separated with a
semicolon.
alert('Hello'); alert('World');
Usually, statements are written on separate lines to make the code more readable:
alert('Hello');
alert('World');
Semicolons
Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic
semicolon insertion .
In most cases, a newline implies a semicolon. But “in most cases” does not mean
“always”!
There are cases when a newline does not mean a semicolon. For example:
alert(3 +
1
+ 2);
The code outputs 6 because JavaScript does not insert semicolons here. It is intuitively
obvious that if the line ends with a plus "+" , then it is an “incomplete expression”, so the
semicolon is not required. And in this case that works as intended.
But there are situations where JavaScript “fails” to assume a semicolon where it is really
needed.
Errors which occur in such cases are quite hard to find and fix.
An example of an error
If you’re curious to see a concrete example of such an error, check this code out:
[1, 2].forEach(alert)
No need to think about the meaning of the brackets [] and forEach yet. We’ll study
them later. For now, just remember the result of the code: it shows 1 then 2 .
Now, let’s add an alert before the code and not finish it with a semicolon:
[1, 2].forEach(alert)
Now if we run the code, only the first alert is shown and then we have an error!
[1, 2].forEach(alert)
The error in the no-semicolon variant occurs because JavaScript does not assume a
semicolon before square brackets [...] .
So, because the semicolon is not auto-inserted, the code in the first example is treated as a
single statement. Here’s how the engine sees it:
But it should be two separate statements, not one. Such a merging in this case is just
wrong, hence the error. This can happen in other situations.
Comments
As time goes on, programs become more and more complex. It becomes necessary to add
comments which describe what the code does and why.
Comments can be put into any place of a script. They don’t affect its execution because the
engine simply ignores them.
One-line comments start with two forward slash characters // .
The rest of the line is a comment. It may occupy a full line of its own or follow a statement.
Like here:
Multiline comments start with a forward slash and an asterisk /* and end with an
asterisk and a forward slash */ .
Like this:
Use hotkeys!
In most editors, a line of code can be commented out by pressing the Ctrl+/ hotkey for a
single-line comment and something like Ctrl+Shift+/ – for multiline comments (select a
piece of code and press the hotkey). For Mac, try Cmd instead of Ctrl .
/*
/* nested comment ?!? */
*/
alert( 'World' );
Please, don’t hesitate to comment your code.
Comments increase the overall code footprint, but that’s not a problem at all. There are many
tools which minify code before publishing to a production server. They remove comments, so
they don’t appear in the working scripts. Therefore, comments do not have negative effects on
production at all.
Later in the tutorial there will be a chapter Code quality that also explains how to write better
comments.
“use strict”
The directive looks like a string: "use strict" or 'use strict' . When it is located at
the top of a script, the whole script works the “modern” way.
For example:
"use strict";
Looking ahead, let’s just note that "use strict" can be put at the start of most kinds of
functions instead of the whole script. Doing that enables strict mode in that function only. But
usually, people use it for the whole script.
⚠ Ensure that “use strict” is at the top
Please make sure that "use strict" is at the top of your scripts, otherwise strict mode
may not be enabled.
alert("some code");
// "use strict" below is ignored--it must be at the top
"use strict";
Browser console
For the future, when you use a browser console to test features, please note that it doesn’t use
strict by default.
Sometimes, when use strict makes a difference, you’ll get incorrect results.
You can try to press Shift+Enter to input multiple lines, and put use strict on top, like
this:
If it doesn’t, the most reliable way to ensure use strict would be to input the code into
console like this:
(function() {
'use strict';
// ...your code...
})()
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 later in the tutorial.
2. Strict mode is enabled by placing "use strict" at the top of a script or function. Several
language features, like “classes” and “modules”, enable strict mode automatically.
3. Strict mode is supported by all modern browsers.
4. We recommended always starting scripts with "use strict" . All examples in this tutorial
assume strict mode unless (very rarely) specified otherwise.
Variables
Most of the time, a JavaScript application needs to work with information. Here are two
examples:
1. An online shop – the information might include goods being sold and a shopping cart.
2. A chat application – the information might include users, messages, and much more.
A variable
A variable is a “named storage” for data. We can use variables to store goodies, visitors, and
other data.
The statement below creates (in other words: declares or defines) a variable with the name
“message”:
let message;
Now, we can put some data into it by using the assignment operator = :
let message;
The string is now saved into the memory area associated with the variable. We can access it
using the variable name:
let message;
message = 'Hello!';
alert(message); // shows the variable content
To be concise, we can combine the variable declaration and assignment into a single line:
let message = 'Hello!'; // define the variable and assign the value
alert(message); // Hello!
That might seem shorter, but we don’t recommend it. For the sake of better readability, please
use a single line per variable.
Technically, all these variants do the same thing. So, it’s a matter of personal taste and
aesthetics.
var instead of let
In older scripts, you may also find another keyword: var instead of let :
The var keyword is almost the same as let . It also declares a variable, but in a slightly
different, “old-school” way.
There are subtle differences between let and var , but they do not matter for us yet.
We’ll cover them in detail in the chapter The old "var".
A real-life analogy
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 labeled "message" with the
value "Hello!" in it:
let message;
message = 'Hello!';
alert(message);
When the value is changed, the old data is removed from the variable:
We can also declare two variables and copy data from one into the other.
let hello = 'Hello world!';
let message;
Functional languages
It’s interesting to note that there exist functional programming languages, like Scala
or Erlang that forbid changing variable values.
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 us to create a new box (declare a new variable).
We can’t reuse the old one.
Though it may seem a little 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 you’re not planning to use it
soon) is recommended to broaden the mind.
Variable naming
1. The name must contain only letters, digits, or the symbols $ and _ .
2. The first character must not be a digit.
let userName;
let test123;
When the name contains multiple words, camelCase is commonly used. That is: words go
one after another, each word except first starting with a capital letter: myVeryLongName .
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.
alert($ + _); // 3
Examples of incorrect variable names:
Case matters
Variables named apple and AppLE are two different variables.
Technically, there is no error here, such names are allowed, but there is an international
tradition to use English in variable names. Even if we’re writing a small script, it may have a
long life ahead. People from other countries may need to read it some time.
⚠ Reserved names
There is a list of reserved words , which cannot be used as variable names because they
are used by the language itself.
alert(num); // 5
"use strict";
Constants
Variables declared using const are called “constants”. They cannot be changed. An attempt
to do so would cause an error:
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.
Uppercase constants
There is a widespread practice to use constants as aliases for difficult-to-remember values that
are known prior to execution.
For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:
Benefits:
●
COLOR_ORANGE is much easier to remember than "#FF7F00" .
● It is much easier to mistype "#FF7F00" than COLOR_ORANGE .
●
When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00 .
When should we use capitals for a constant and when should we name it normally? Let’s make
that clear.
Being a “constant” just means that a variable’s value never changes. But there are constants
that are known prior to execution (like a hexadecimal value for red) and there are constants that
are calculated in run-time, during the execution, but do not change after their initial assignment.
For instance:
The value of pageLoadTime is not known prior to the page load, so it’s named normally. But
it’s still a constant because it doesn’t change after assignment.
In other words, capital-named constants are only used as aliases for “hard-coded” values.
Variable naming is one of the most important and complex skills in programming. A quick
glance at variable names can reveal which code was written by a beginner versus an
experienced developer.
In a real project, most of the time is spent modifying and extending an existing code base rather
than writing something completely separate from scratch. When we return to some code after
doing something else for a while, it’s much easier to find information that is well-labeled. Or, in
other words, when the variables have good names.
Please spend time thinking about the right name for a variable before declaring it. Doing so will
repay you handsomely.
Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is
not. Go for it.
Reuse or create?
And the last note. There are some lazy programmers who, instead of declaring new
variables, tend to reuse existing ones.
As a result, their variables are like boxes into which people throw different things without
changing their stickers. What’s inside the box now? Who knows? We need to come closer
and check.
Such programmers save a little bit on variable declaration but lose ten times more on
debugging.
Modern JavaScript minifiers and browsers optimize code well enough, so it won’t create
performance issues. Using different variables for different values can even help the engine
optimize your code.
Summary
We can declare variables to store data by using the var , let , or const keywords.
● 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 The old "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 us to easily understand what’s inside them.
✔ Tasks
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com