0% found this document useful (0 votes)
146 views

Javascript Info

Uploaded by

Subhangi Agawal
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views

Javascript Info

Uploaded by

Subhangi Agawal
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 18

LiveScript <-> JavaScript <-> ECMAScript

—————————————————————————

JavaScript was initially created to “make web pages alive”. Today,


JavaScript can execute not only in the browser, but also on the server,
or on any device that has the JavaScript engine.

Example ->

V8 – in Chrome
SpiderMonkey – in Firefox.

How do engines work?

1 The engine (embedded in a browser) reads/parses the script. Then it


converts (compiles) the script to machine code.And then the machine
code runs. 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 further optimizes the machine code
based on that knowledge.

What can in-browser Javascript do?


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.
For instance, in-browser JavaScript is able to:
- Add new HTML to the page, change the existing content, modify
styles.
- React to user actions, run on mouse clicks, pointer movements,
key presses.
- Send requests over the network to remote servers
- Get and set cookies, ask questions to the visitor, show messages.
- Remember the data on the client-side (“local storage”).

What cant in-browser Javascript do?


JavaScript’s abilities in the browser are limited to protect the user’s
safety. The aim is to prevent an evil webpage from accessing private
information or harming the user’s data.

Restrictions from Javascript are:


⁃ 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
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 the 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.
⁃ when one window uses JavaScript to open the other one. JavaScript
from one page may not access the other page 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 must
contain special JavaScript code that handles it. 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, for example, 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 limitations do not exist if
JavaScript is used outside of the browser, for example on a server.
Modern browsers also allow plugins/extensions which may ask for
extended permissions.

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

If src is set, the script content is ignored.

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>

We must choose either an external <script src="…"> or a


regular <script> with code.
The example above can be split into two scripts to work:
<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>.
Code Structure
——————————
Semicolon

A semicolon may be omitted in most cases when a line break exists.


alert('Hello')
alert('World')
JavaScript interprets the line break as an “implicit” semicolon. This is
called an automatic semicolon insertion.
But there are situations where JavaScript “fails” to assume a
semicolon where it is really needed.

An example of an error

alert("Hello");
[1, 2].forEach(alert);

Now let’s remove the semicolon after the alert:


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.

Here’s how the engine sees it:


alert("Hello")[1, 2].forEach(alert);

Modern mode: “use strict”


JavaScript evolved without compatibility issues. New features were
added to the language while old functionality didn’t change.
That had the benefit of never breaking existing code. But the
downside was that any mistake or an imperfect decision made by
JavaScript’s creators got stuck in the language forever.
This was the case until 2009 when ECMAScript 5 (ES5) appeared. It
added new features to the language and modified some of the existing
ones. To keep the old code working, most such modifications are off
by default. You need to explicitly enable them with a special
directive: "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";
// this code works the modern way
...

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";

// strict mode is not activated


Only comments may appear above "use strict".
NOTE
There’s no way to cancel use strict
There is no directive like "no use strict" that reverts the engine to old
behavior.
Once we enter strict mode, there’s no going back.
NOTE
Modern JavaScript supports “classes” and “modules” – advanced
language structures (we’ll surely get to them), that enable use
strict automatically. So we don’t need to add the "use strict" directive,
if we use them.

Variables
let:
let message;
message= ‘Hi’;

We can also declare multiple variables in one line:


let user = 'John', age = 25, message = 'Hello';

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";

- 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.
- capital-named constants are only used as aliases for “hard-coded”
values.

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;

The Null value


The special null value does not belong to any of the types.
It forms a separate type of its own which contains only the null value.
let age = null;

In JavaScript, null is not a “reference to a non-existing object” or a


“null pointer” like in some other languages.
It’s just a special value which represents “nothing”, “empty” or “value
unknown”.

The Undefined value:


The special value undefined also stands apart. It makes a type of its
own, just like null.
The meaning of undefined is “value is not assigned”.
If a variable is declared, but not assigned, then its value is undefined:
let age;
alert(age); // shows "undefined"

NOTE
it is possible to explicitly assign undefined to a variable:
let age = 100;

// change the value to undefined


age = undefined;

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.

Objects and Symbols:


All other types are called “primitive” because their values can contain
only a single thing (be it a string or a number or whatever). In
contrast, objects are used to store collections of data and more
complex entities.
The symbol type is used to create unique identifiers for objects.

Type of operator :

The typeof operator returns the type of the operand.


A call to typeof x returns a string with the type name:

typeof undefined // "undefined"


typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (1)
typeof null // "object" (2)
typeof alert // "function" (3)

The last three lines may need additional explanation:


1 Math is a built-in object that provides mathematical operations.
2 The result of typeof null is "object". That’s an officially recognized
error in typeof, coming from very early days of JavaScript and kept
for compatibility. Definitely, null is not an object. It is a special value
with a separate type of its own. The behavior of typeof is wrong here.
3 The result of typeof alert is "function", because alert is a function.
there’s no special “function” type in JavaScript. Functions belong to
the object type. But typeof treats them differently,
returning "function". That also comes from the early days of
JavaScript. Technically, such behavior isn’t correct, but can be
convenient in practice.

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.

The typeof operator allows us to see which type is stored in a


variable.
- Usually used as typeof x, but typeof(x) is also possible.
- Returns a string with the name of the type, like "string".
- For null returns "object" – this is an error in the language, it’s not
actually an object.

Interaction: alert, prompt, confirm

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 function prompt accepts two arguments:


result = prompt(title, [default]);
It shows a modal window with a text message, an input field for the
visitor, and the buttons OK/Cancel.
title
The text to show the visitor.
default
An optional second parameter, the initial value for the input field.

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

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.
If the string is not a valid number, the result of such a conversion
is NaN. For instance:
let age = Number("an arbitrary string instead of a number");
alert(age); // NaN, conversion failed

alert( Number(" 123 ") ); // 123


alert( Number("123z") ); // NaN (error reading a number at "z")
alert( Number(true) ); // 1
alert( Number(false) ); // 0
Please note that null and undefined behave differently
here: null becomes zero while undefined becomes NaN.
Boolean conversion:
Boolean conversion is the simplest one.
It happens in logical operations (later we’ll meet condition tests and
other similar things) but can also be performed explicitly with a call
to Boolean(value).
The conversion rule:
Values that are intuitively “empty”, like 0, an empty
string, null, undefined, and NaN, become false.
Other values become true.

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:

undefined is NaN as a number, not 0.


"0" and space-only strings like " " are true as a boolean.

You might also like