Javascript Info
Javascript Info
—————————————————————————
Example ->
V8 – in Chrome
SpiderMonkey – in Firefox.
Summary
- JavaScript was initially created as a browser-only language, but it
is now used in many other environments as well.
- Today, JavaScript has a unique position as the most widely-
adopted browser language, fully integrated 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.
JavaScript Fundamentals
———————————————
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.
<script src="/js/script1.js"></script>
NOTE
A single <script> tag can’t have both the src attribute and
code inside.
This won’t work:
<script src="file.js">
alert(1); // the content is ignored, because src is set
</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>.
Code Structure
——————————
Semicolon
An example of an error
alert("Hello");
[1, 2].forEach(alert);
The difference compared to the code above is only one character: the
semicolon at the end of the first line is gone.
If we run this code, only the first Hello shows (and there’s an error,
you may need to open the console to see it). There are no numbers
any more.
That’s because JavaScript does not assume a semicolon before square
brackets [...]. So, the code in the last example is treated as a single
statement.
NOTE
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.
Strict mode isn’t enabled here:
alert("some code");
// "use strict" below is ignored--it must be at the top
"use strict";
Variables
let:
let message;
message= ‘Hi’;
const:
Variables declared using const are called “constants”. They cannot be
reassigned. An attempt to do so would cause an error:
const myBirthday = '18.04.1982';
myBirthday = '01.01.2001'; // error, can't reassign the constant!
Uppercase constants:
There is a widespread practice to use constants as aliases for difficult-
to-remember values that are known prior to execution.
Such constants are named using capital letters and underscores.
const COLOR_RED = "#F00";
const COLOR_GREEN = "#0F0";
NOTE
When should we use capitals for a constant and when should we
name it normally?
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:
const pageLoadTime = /* time taken by a webpage to load */;
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.
Summary
We can declare variables to store data by using the var, let,
or const keywords.
let – is a modern variable declaration.
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.
Data types:
JavaScript is “dynamically typed” language, meaning that variables
are not bound to any data type.
We can put any type in a variable. For example, a variable can at one
moment be a string and then store a number:
// no error
let message = "hello";
message = 123456;
NOTE
it is possible to explicitly assign undefined to a variable:
let age = 100;
alert(age); // "undefined"
NOTE
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.
Type of operator :
NOTE
The typeof(x) syntax
You may also come across another syntax: typeof(x). It’s the same
as typeof x.
To put it clear: typeof is an operator, not a function. The parentheses
here aren’t a part of typeof. It’s the kind of parentheses used for
mathematical grouping.
Usually, such parentheses contain a mathematical expression, such
as (2 + 2), but here they contain only one argument (x). Syntactically,
they allow to avoid a space between the typeof operator and its
argument, and some people like it.
Some people prefer typeof(x), although the typeof x syntax is much
more common.
Summary
There are 8 basic data types in JavaScript.
Seven primitive data types:
- number for numbers of any kind: integer or floating-point,
integers are limited by ±(253-1).
- bigint for integer numbers of arbitrary length.
- string for strings. A string may have zero or more characters,
there’s no separate single-character type.
- boolean for true/false.
- null for unknown values – a standalone type that has a single
value null.
- undefined for unassigned values – a standalone type that has
a single value undefined.
- symbol for unique identifiers.
And one non-primitive data type:
- object for more complex data structures.
alert:
alert("Hello");
The mini-window with the message is called a modal window. The
word “modal” means that the visitor can’t interact with the rest of the
page, press other buttons, etc, until they have dealt with the window.
In this case – until they press “OK”.
Prompt:
The square brackets around default in the syntax above denote that the
parameter is optional, not required.
The visitor can type something in the prompt input field and press
OK. Then we get that text in the result. Or they can cancel the input
by pressing Cancel or hitting the Esc key, then we get null as
the result.The call to prompt returns the text from the input field
or null if the input was canceled.
For instance:
let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`); // You are 100 years old!
NOTE
In IE: always supply a default
The second parameter is optional, but if we don’t supply it, Internet
Explorer will insert the text "undefined" into the prompt.
let test = prompt("Test", ''); // <-- for IE
Confirm:
The syntax:
result = confirm(question);
The function confirm shows a modal window with a question and two
buttons: OK and Cancel. The result is true if OK is pressed
and false otherwise.
For example:
let isBoss = confirm("Are you the boss?");
alert( isBoss ); // true if OK is pressed
Summary
We covered 3 browser-specific functions to interact with visitors:
alert: shows a message.
prompt : shows a message asking the user to input text. It returns the
text or, if Cancel button or Esc is clicked, null.
confirm : shows a message and waits for the user to press “OK” or
“Cancel”. It returns true for OK and false for Cancel/Esc.
All these methods are modal: they pause script execution and don’t
allow the visitor to interact with the rest of the page until the window
has been dismissed.
There are two limitations shared by all the methods above:
1 The exact location of the modal window is determined by the
browser. Usually, it’s in the center.
2 The exact look of the window also depends on the browser. We can’t
modify it.
Type Conversions:
Most of the time, operators and functions automatically convert the
values given to them to the right type.
For example, alert automatically converts any value to a string to
show it. Mathematical operations convert values to numbers.
There are also cases when we need to explicitly convert a value to the
expected type.
String conversion:
String conversion happens when we need the string form of a value.
let value = true;
alert(typeof value); // boolean
value = String(value); // now value is a string "true"
alert(typeof value); // string
Number conversion:
Numeric conversion in mathematical functions and expressions
happens automatically.
For example, when division / is applied to non-numbers:
alert( "6" / "2" ); // 3, strings are converted to numbers
We can use the Number(value) function to explicitly convert
a value to a number.
let str = "123";
alert(typeof str); // string
let num = Number(str); // becomes a number 123
alert(typeof num); // number
NOTE
In JavaScript, a non-empty string is always true.
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
Summary
The three most widely used type conversions are to string, to number,
and to boolean.
String Conversion – Occurs when we output something. Can be
performed with String(value). The conversion to string is usually
obvious for primitive values.
Numeric Conversion – Occurs in math operations. Can be performed
with Number(value).
The conversion follows the rules:
Value Becomes…
undefined NaN
null 0
true / false 1/0
The string is read “as is”,
whitespaces (includes spaces,
tabs \t, newlines \n etc.) from
string
both sides are ignored. An
empty string becomes 0. An
error gives NaN.
Boolean Conversion – Occurs in logical operations. Can be
performed with Boolean(value).
Follows the rules:
Value Becomes…
0, null, undefined, NaN, "" false
any other value true
Most of these rules are easy to understand and memorize. The notable
exceptions where people usually make mistakes are: