Category Archives: JavaScript

JavaScript 7 – struttura dei programmi – 5

Continuo da qui a copiare qui.

Indentare il codice
Cioè scriverlo bene, in modo che sia leggibile, come fanno i nerds.
Non è richiesto; si può scrivere tutto il programma in una sola lunga linea ma poi è difficile leggerlo.
With proper indentation, the visual shape of a program corresponds to the shape of the blocks inside it. I like to use two spaces (io di solito 4) for every open block, but tastes differ—some people use four spaces, and some people use tab characters.

Ciclo for
Many loops follow the pattern seen in the previous while examples. First, a “counter” variable is created to track the progress of the loop. Then comes a while loop, whose test expression usually checks whether the counter has reached some boundary yet. At the end of the loop body, the counter is updated to track progress.

Because this pattern is so common, JavaScript and similar languages provide a slightly shorter and more comprehensive form, the for loop (file f0.js).

for (var number = 0; number <= 12; number = number + 2)

This program is exactly equivalent to the earlier even-number-printing example. The only change is that all the statements that are related to the “state” of the loop are now grouped together.

The parentheses after a for keyword must contain two semicolons. The part before the first semicolon initializes the loop, usually by defining a variable. The second part is the expression that checks whether the loop must continue. The final part updates the state of the loop after every iteration. In most cases, this is shorter and clearer than a while construct.

Here is the code that computes 210, using for instead of while (file f1.js):

var result = 1;
for (var counter = 0; counter < 10; counter = counter + 1)
  result = result * 2;

Note that even though no block is opened with a {, the statement in the loop is still indented two spaces to make it clear that it “belongs” to the line before it.

Uscire dal ciclo
Having the loop’s condition produce false is not the only way a loop can finish. There is a special statement called break that has the effect of immediately jumping out of the enclosing loop.

This program illustrates the break statement. It finds the first number that is both greater than or equal to 20 and divisible by 7 (f2.js).

for (var current = 20; ; current++) {
  if (current % 7 == 0)

Using the remainder (%) operator is an easy way to test whether a number is divisible by another number. If it is, the remainder of their division is zero.

The for construct in the example does not have a part that checks for the end of the loop. This means that the loop will never stop unless the break statement inside is executed.

If you were to leave out that break statement or accidentally write a condition that always produces true, your program would get stuck in an infinite loop. A program stuck in an infinite loop will never finish running, which is usually a bad thing.

If you create an infinite loop in one of the examples on these pages, you’ll usually be asked whether you want to stop the script after a few seconds. If that fails, you will have to close the tab that you’re working in, or on some browsers close your whole browser, in order to recover.

The continue keyword is similar to break, in that it influences the progress of a loop. When continue is encountered in a loop body, control jumps out of the body and continues with the loop’s next iteration.

Visto che Marijn non fa l’esempio per continue lo faccio io: scrivo solo i numeri pari da 0 a 10, file f3.js:

for (var current = 0; current < 11 ; current++) {
  if (current % 2 == 1)


Ancora sulle conversioni di JavaScript

OK, quasi lolloso, anzi certamente ma chissà 😙

Su Twitter si divertono con i calcoli aritmetici strani di JavaScript –troppo volonteroso– per esempio qui e qui.

Io sono del parere che dovrebbe imparare a dire di no, quando necessario.
M siccome non lo fa tocca al programmatore controllarlo, non è censura ma richiamo alla deontologia –secondo me 🐙

C’è un caso che a prima vista mi lascia perpluto

Eh!? 🤖  cosa succede a complessificare l’espressione (solo la prima parte, il resto è sensato):

non ci sono; sembra venire da qui

ma attenzione:

No, non ci sono 😡

Anche con altri linguaggi posso avere risultati errati:

Perl 5

🤖 sbagliato; la versione 6 non funziona (con questo script).

Python invece

🤖 sbagliato anche questo; tutti sanno che la risposta giusta è

41 monkeys and 1 fat snake

(qui) 🐙


JavaScript 6 – struttura dei programmi – 4

Continuo da qui a copiare qui.

Cicli while e do
Consider a program that prints all even numbers from 0 to 12. One way to write this is as follows:


lo salvo nel file c0.js e lo eseguo nel terminale, viene meglio

That works, but the idea of writing a program is to make something less work, not more. If we needed all even numbers less than 1,000, the previous would be unworkable. What we need is a way to repeat some code. This form of control flow is called a loop (ciclo):

Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. If we combine this with a variable that counts, we can do something like this (come sopra, lo metto nel file c1.js):

var number = 0;
while (number <= 12) {
  number = number + 2;

A statement starting with the keyword while creates a loop. The word while is followed by an expression in parentheses and then a statement, much like if. The loop executes that statement as long as the expression produces a value that is true when converted to Boolean type.

In this loop, we want to both print the current number and add two to our variable. Whenever we need to execute multiple statements inside a loop, we wrap them in curly braces ({ and }). Braces do for statements what parentheses do for expressions: they group them together, making them count as a single statement. A sequence of statements wrapped in braces is called a block.

Many JavaScript programmers wrap every single loop or if body in braces. They do this both for the sake of consistency and to avoid having to add or remove braces when changing the number of statements in the body later. In this book, I will write most single-statement bodies without braces, since I value brevity. You are free to go with whichever style you prefer.

The variable number demonstrates the way a variable can track the progress of a program. Every time the loop repeats, number is incremented by 2. Then, at the beginning of every repetition, it is compared with the number 12 to decide whether the program has done all the work it intended to do.

Nota: si può scrivere la { su una riga a sé come fanno i C-isti, così:

var number = 0;
while (number <= 12) 
  number = number + 2;

As an example that actually does something useful, we can now write a program that calculates and shows the value of 210 (2 to the 10th power). We use two variables: one to keep track of our result and one to count how often we have multiplied this result by 2. The loop tests whether the second variable has reached 10 yet and then updates both variables (file c2.js). Ovviamente si tratta solo di un esempio, lo stesso risultato si ottiene con Math.pow(2, 10).

// file c2.js (questo è un commento)
var result = 1;
var counter = 0;
while (counter < 10) {
  result = result * 2;
  counter = counter + 1;

The counter could also start at 1 and check for <= 10, but, for reasons that will that will become apparent in Chapter 4, it is a good idea to get used to counting from 0.

The do loop is a control structure similar to the while loop. It differs only on one point: a do loop always executes its body at least once, and it starts testing whether it should stop only after that first execution. To reflect this, the test appears after the body of the loop:

do {
  var yourName = prompt("Who are you?");
} while (!yourName);

This program will force you to enter a name. It will ask again and again until it gets something that is not an empty string. Applying the ! operator will convert a value to Boolean type before negating it, and all strings except “” convert to true. This means the loop continues going round until you provide a name that is not the empty string.

L’esempio può essere eseguito solo nel browser perché c’è la chiamata a prompt; propongo di rifare il precedente usando do al posto di while, file c3.js:

// file c3.js

var result = 1;
var counter = 0;

do {
  result = result * 2;
  counter = counter + 1;
} while (counter < 10)



JavaScript 5 – struttura dei programmi – 3

Continuo da qui con le istruzioni copiando qui.

Controllo del flusso
When your program contains more than one statement, the statements are executed, predictably, from top to bottom. As a basic example, this program has two statements. The first one asks the user for a number, and the second, which is executed afterward, shows the square of that number.

var theNumber = Number(prompt("Pick a number", ""));
alert("Your number is the square root of " +
      theNumber * theNumber);

Nota: viene eseguita solo nel browser, ho costruito il collage 😊

The function Number converts a value to a number. We need that conversion because the result of prompt is a string value, and we want a number. There are similar functions called String and Boolean that convert values to those types.

Here is the rather trivial schematic representation of straight control flow:

Esecuzione condizionale
Executing statements in straight-line order isn’t the only option we have. An alternative is conditional execution, where we choose between two different routes based on a Boolean value, like this:

Conditional execution is written with the if keyword in JavaScript. In the simple case, we just want some code to be executed if, and only if, a certain condition holds. For example, in the previous program, we might want to show the square of the input only if the input is actually a number.

var theNumber = Number(prompt("Pick a number", ""));
if (!isNaN(theNumber))
  alert("Your number is the square root of " +
        theNumber * theNumber);

With this modification, if you enter “cheese” [o “otto” o qualunque cosa che non sia un numero], no output will be shown.

The keyword if executes or skips a statement depending on the value of a Boolean expression. The deciding expression is written after the keyword, between parentheses, followed by the statement to execute.

The isNaN function is a standard JavaScript function that returns true only if the argument it is given is NaN. The Number function happens to return NaN when you give it a string that doesn’t represent a valid number. Thus, the condition translates to “unless theNumber is not-a-number, do this”.

You often won’t just have code that executes when a condition holds true, but also code that handles the other case. This alternate path is represented by the second arrow in the diagram. The else keyword can be used, together with if, to create two separate, alternative execution paths.

var theNumber = Number(prompt("Pick a number", ""));
if (!isNaN(theNumber))
  alert("Your number is the square root of " +
        theNumber * theNumber);
  alert("Hey. Why didn't you give me a number?");

If we have more than two paths to choose from, multiple if/else pairs can be “chained” together. Here’s an example:

var num = Number(prompt("Pick a number", "0"));

if (num < 10)
else if (num < 100)

The program will first check whether num is less than 10. If it is, it chooses that branch, shows “Small”, and is done. If it isn’t, it takes the else branch, which itself contains a second if. If the second condition (< 100) holds, that means the number is between 10 and 100, and “Medium” is shown. If it doesn’t, the second, and last, else branch is chosen.

The flow chart for this program looks something like this:


JavaScript 4 – struttura dei programmi – 2

Continuo copiando qui.

The collection of variables and their values that exist at a given time is called the environment. When a program starts up, this environment is not empty. It always contains variables that are part of the language standard, and most of the time, it has variables that provide ways to interact with the surrounding system. For example, in a browser, there are variables and functions to inspect and influence the currently loaded website and to read mouse and keyboard input.

Qui Marijn la fa lunga, più del necessario per un corso introduttivo. Inoltre fa spesso riferimento al browser che io non uso (qui). Ma le cose fondamentali saltano comunque fuori.

A lot of the values provided in the default environment have the type function. A function is a piece of program wrapped in a value. Such values can be applied in order to run the wrapped program. For example, in a browser environment, the variable alert holds a function that shows a little dialog box with a message. It is used like this:

alert("Good morning!");

Executing a function is called invoking, calling, or applying it. You can call a function by putting parentheses after an expression that produces a function value. Usually you’ll directly use the name of the variable that holds the function. The values between the parentheses are given to the program inside the function. In the example, the alert function uses the string that we give it as the text to show in the dialog box. Values given to functions are called arguments. The alert function needs only one of them, but other functions might need a different number or different types of arguments.

La funzione console.log
The alert function can be useful as an output device when experimenting, but clicking away all those little windows will get on your nerves. In past examples, we’ve used console.log to output values. Most JavaScript systems (including all modern web browsers and Node.js) provide a console.log function that writes out its arguments to some text output device. In browsers, the output lands in the JavaScript console. This part of the browser interface is hidden by default, but most browsers open it when you press F12 or, on Mac, when you press Command-Option-I. If that does not work, search through the menus for an item named “web console” or “developer tools”.

When running the examples, or your own code, on the pages of this book, console.log output will be shown after the example, instead of in the browser’s JavaScript console. Nel sito da cui copio, nel browser per eseguire gli fare click sul codice e premere Ctrl-Invio.

Though variable names cannot contain period characters, console.log clearly has one. This is because console.log isn’t a simple variable. It is actually an expression that retrieves the log property from the value held by the console variable. We will find out exactly what this means [prossimamente].

Valori ritornati
Showing a dialog box or writing text to the screen is a side effect. A lot of functions are useful because of the side effects they produce. Functions may also produce values, and in that case, they don’t need to have a side effect to be useful. For example, the function Math.max takes any number of number values and gives back the greatest.

When a function produces a value, it is said to return that value. Anything that produces a value is an expression in JavaScript, which means function calls can be used within larger expressions. Here a call to Math.min, which is the opposite of Math.max, is used as an input to the plus operator:

Prossimamente vedremo come scrivere le nostre funzioni.

prompt e confirm
Browser environments contain other functions besides alert for popping up windows. You can ask the user an OK/Cancel question using confirm. This returns a Boolean: true if the user clicks OK and false if the user clicks Cancel.

confirm("Shall we, then?");

The prompt function can be used to ask an “open” question. The first argument is the question, the second one is the text that the user starts with. A line of text can be typed into the dialog window, and the function will return this text as a string.

prompt("Tell me everything you know.", "...");

These two functions aren’t used much in modern web programming, mostly because you have no control over the way the resulting windows look, but they are useful for toy programs and experiments.

Continua :mrgreen:

JavaScript 3 – struttura dei programmi – 1

Continuo da qui, copio qui.

Qui partiamo –dice Marijn– a fare quello che viene chiamata programmazione. We will expand our command of the JavaScript language beyond the nouns and sentence fragments we’ve seen so far, to the point where we can express some meaningful prose.

Espressioni e istruzioni
In Chapter 1 [post precedente, quello linkato], we made some values and then applied operators to them to get new values. Creating values like this is an essential part of every JavaScript program, but it is only a part.

A fragment of code that produces a value is called an expression. Every value that is written literally (such as 22 or "psychoanalysis") is an expression. An expression between parentheses is also an expression, as is a binary operator applied to two expressions or a unary operator applied to one.

This shows part of the beauty of a language-based interface. Expressions can nest in a way very similar to the way subsentences in human languages are nested—a subsentence can contain its own subsentences, and so on. This allows us to combine expressions to express arbitrarily complex computations.

If an expression corresponds to a sentence fragment, a JavaScript statement [in italiano “istruzione”] corresponds to a full sentence in a human language. A program is simply a list of statements.

The simplest kind of statement is an expression with a semicolon after it. This is a program:

It is a useless program, though. An expression can be content to just produce a value, which can then be used by the enclosing expression. A statement stands on its own and amounts to something only if it affects the world. It could display something on the screen—that counts as changing the world—or it could change the internal state of the machine in a way that will affect the statements that come after it. These changes are called side effects. The statements in the previous example just produce the values 1 and true and then immediately throw them away. This leaves no impression on the world at all. When executing the program, nothing observable happens.

In some cases, JavaScript allows you to omit the semicolon at the end of a statement. In other cases, it has to be there, or the next line will be treated as part of the same statement. The rules for when it can be safely omitted are somewhat complex and error-prone. In this book, every statement that needs a semicolon will always be terminated by one. I recommend you do the same in your own programs, at least until you’ve learned more about subtleties involved in leaving out semicolons.

How does a program keep an internal state? How does it remember things? We have seen how to produce new values from old values, but this does not change the old values, and the new value has to be immediately used or it will dissipate again. To catch and hold values, JavaScript provides a thing called a variable.

And that gives us our second kind of statement. The special word (keyword) var indicates that this sentence is going to define a variable. It is followed by the name of the variable and, if we want to immediately give it a value, by an = operator and an expression.

The previous statement creates a variable called caught and uses it to grab hold of the number that is produced by multiplying 5 by 5.

After a variable has been defined, its name can be used as an expression. The value of such an expression is the value the variable currently holds. Here’s an example:

Variable names can be any word that isn’t a reserved word (such as var). They may not include spaces. Digits can also be part of variable names—catch22 is a valid name, for example—but the name must not start with a digit. A variable name cannot include punctuation, except for the characters $ and _.

When a variable points at a value, that does not mean it is tied to that value forever. The = operator can be used at any time on existing variables to disconnect them from their current value and have them point to a new one.

You should imagine variables as tentacles, rather than boxes. They do not contain values; they grasp them—two variables can refer to the same value. A program can access only the values that it still has a hold on. When you need to remember something, you grow a tentacle to hold on to it or you reattach one of your existing tentacles to it.

umorismo marijniano

Let’s look at an example. To remember the number of dollars that Luigi still owes you, you create a variable. And then when he pays back $35, you give this variable a new value.

When you define a variable without giving it a value, the tentacle has nothing to grasp, so it ends in thin air. If you ask for the value of an empty variable, you’ll get the value undefined.

A single var statement may define multiple variables. The definitions must be separated by commas.

Parole chiave [keywords] e riservate [reserved words]
Words with a special meaning, such as var, are keywords, and they may not be used as variable names. There are also a number of words that are “reserved for use” in future versions of JavaScript. These are also officially not allowed to be used as variable names, though some JavaScript environments do allow them. The full list of keywords and reserved words is rather long.

break case catch class const continue debugger
default delete do else enum export extends false
finally for function if implements import in
instanceof interface let new null package private
protected public return static super switch this
throw true try typeof var void while with yield

Don’t worry about memorizing these, but remember that this might be the problem when a variable definition does not work as expected.

Qui è ancora lungo (assay), pausa 😙


Conversioni, a volte esagerate

La serie di posts –appena iniziata– su JavaScript piace 😜
Anche se parecchi lettori (OK, due) mi hanno fatto modificare quel che volevo fare: racconta per i nuovi, dicono. Ragazzi sono niubbo anch’io (me) 😜

OK, quando si dice la serendipità, oggi un tweet di Sebastian mooolto mysteryouso (assay). Uh! si riferisce a un argomento già trattato, adesso mi spiego.

??? da indagare

??? ma –forse– aspetta non è che…

ottengo una stringa; l’operatore + converte (casta, direbbe un Cista) a stringhe i due oggetti; quindi

altra conversione per via dell’operatore - che è disponibile solo per i numeri.

Siamo passati con solo due operatori da oggetti a stringhe a numeri 😯

Adesso è tutto chiaro,  logico  –NO, logico no!
Cioè bisogna fare attenzione a quello che si fa: non si possono sommare le pere con le mele. Certi linguaggi di programmazione controllano per te, a differenza di JavaScript. Devi conoscere gli strumenti che usi 😜

Pensa che Sebastian dice

I think I’ll quit programming and become priest now and then I’ll pray for forgiveness for our sins against logic and math and common sense.

No, Sebastian, non farlo. Altrimenti ti unfollowo, nèh! 🐙


JavaScript 2 – Valori, tipi e operatori

Continuo da qui a copiare qui.

Per il computer sono tutti dati ma per noi è comodo rappresentarceli suddivisi in categorie (OK, Marijn lo dice meglio ma ho riassunto).

Immagina un mare di dati… To be able to work with such quantities of bits without getting lost, you can separate them into chunks that represent pieces of information. In a JavaScript environment, those chunks are called values. Though all values are made of bits, they play different roles. Every value has a type that determines its role. There are six basic types of values in JavaScript: numbers, strings, Booleans, objects, functions, and undefined values.

This chapter introduces the atomic elements of JavaScript programs, that is, the simple value types and the operators that can act on such values.

Sono numeri 42, 9.81, 2.998e8 (that is 2.998 × 108 = 299,800,000).
Gli interi sono esatti fino a 9 miliardi di miliardi, gli altri possono essere approssimati, prendi per esempio π.

Con i numeri si fanno calcoli aritmetici

+, -, *, e / sono chiamati operatori. Valgono le regole imparate a scuola, precedenza alle espressioni in parentesi e * e /.

C’è ancora un altro operatore, %, chiamato modulo (o resto):

Numeri speciali
Ci sono Infinity, -Infinity e NaN (not a number).

Strings are used to represent text. They are written by enclosing their content in quotes.

Il carattere \ è speciale: per esempio per andare a capo si usa \n

Per scrivere \ devo scrivere \\
In gergo si dice che \ quota (escape) il carattere che segue, cioè se questo è speciale diventa normale:

Le stringhe si possono unire con +

Operatori unari
Not all operators are symbols. Some are written as words. One example is the typeof operator, which produces a string value naming the type of the value you give it.

Ah! io l’ho già fatto senza dirlo ma adesso rimedio: We will use console.log in example code to indicate that we want to see the result of evaluating something. When you run such code, the value produced should be shown on the screen […].

The other operators we saw all operated on two values, but typeof takes only one. Operators that use two values are called binary operators, while those that take one are called unary operators. The minus operator can be used both as a binary operator and as a unary operator.

Valori booleani
Often, you will need a value that simply distinguishes between two possibilities, like “yes” and “no” or “on” and “off”. For this, JavaScript has a Boolean type, which has just two values: true and false.


Ovviamente > significa “maggiore di” e < “minore di”. Si possono comparare anche le stringhe, alfabeticamente:

The actual comparison is based on the Unicode standard. This standard assigns a number to virtually every character you would ever need, including characters from Greek, Arabic, Japanese, Tamil, and so on. Having such numbers is useful for storing strings inside a computer because it makes it possible to represent them as a sequence of numbers. When comparing strings, JavaScript goes over them from left to right, comparing the numeric codes of the characters one by one.

Other similar operators are >= (greater than or equal to), <= (less than or equal to), == (equal to), and != (not equal to).

Attenzione che NaN non è uguale a niente:

Operatori logici
There are also some operations that can be applied to Boolean values themselves. JavaScript supports three logical operators: and, or, and not. These can be used to “reason” about Booleans.

The && operator represents logical and. It is a binary operator, and its result is true only if both the values given to it are true.

The || operator denotes logical or. It produces true if either of the values given to it is true.

not is written as an exclamation mark (!). It is a unary operator that flips the value given to it— !true produces false and !false gives true.

When mixing these Boolean operators with arithmetic and other operators, it is not always obvious when parentheses are needed. In practice, you can usually get by with knowing that of the operators we have seen so far, || has the lowest precedence, then comes &&, then the comparison operators (>, ==, and so on), and then the rest. This order has been chosen such that, in typical expressions like the following one, as few parentheses as possible are necessary: 1 + 1 == 2 && 10 * 10 > 50. Quanto vale? lasciata come esercizio 😊

The last logical operator I will discuss is not unary, not binary, but ternary, operating on three values. It is written with a question mark and a colon, like this:

This one is called the conditional operator (or sometimes just ternary operator since it is the only such operator in the language). The value on the left of the question mark “picks” which of the other two values will come out. When it is true, the middle value is chosen, and when it is false, the value on the right comes out.

Valori indefiniti
There are two special values, written null and undefined, that are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.

Many operations in the language that don’t produce a meaningful value (you’ll see some later) yield undefined simply because they have to yield some value.

The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In the cases where you actually have to concern yourself with these values, I recommend treating them as interchangeable (more on that in a moment).

Nota: undefined c’è nei miei screenshots nelle chiamate a console.log.

Conversione automatica dei tipi
JavaScript goes out of its way to accept almost any program you give it, even programs that do odd things. This is nicely demonstrated by the following expressions:

When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it wants, using a set of rules that often aren’t what you want or expect. This is called type coercion. So the null in the first expression becomes 0, and the “5” in the second expression becomes 5 (from string to number). Yet in the third expression, + tries string concatenation before numeric addition, so the 1 is converted to “1” (from number to string).

When something that doesn’t map to a number in an obvious way (such as "five" or undefined) is converted to a number, the value NaN is produced. Further arithmetic operations on NaN keep producing NaN, so if you find yourself getting one of those in an unexpected place, look for accidental type conversions.

When comparing values of the same type using ==, the outcome is easy to predict: you should get true when both values are the same, except in the case of NaN. But when the types differ, JavaScript uses a complicated and confusing set of rules to determine what to do. In most cases, it just tries to convert one of the values to the other value’s type. However, when null or undefined occurs on either side of the operator, it produces true only if both sides are one of null or undefined.

That last piece of behavior is often useful. When you want to test whether a value has a real value instead of null or undefined, you can simply compare it to null with the == (or !=) operator.

But what if you want to test whether something refers to the precise value false? The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string (“”) count as false, while all the other values count as true. Because of this, expressions like 0 == false and "" == false are also true. For cases like this, where you do not want any automatic type conversions to happen, there are two extra operators: === and !==. The first tests whether a value is precisely equal to the other, and the second tests whether it is not precisely equal. So "" === false is false as expected.

Quando il gioco si fa duro l’operatore tre-caratteri torna utile –raccomandato.

Short-circuit degli operatori logici
The logical operators && and || handle values of different types in a peculiar way. They will convert the value on their left side to Boolean type in order to decide what to do, but depending on the operator and the result of that conversion, they return either the original left-hand value or the right-hand value.

The || operator, for example, will return the value to its left when that can be converted to true and will return the value on its right otherwise. This conversion works as you’d expect for Boolean values and should do something analogous for values of other types.

This functionality allows the || operator to be used as a way to fall back on a default value. If you give it an expression that might produce an empty value on the left, the value on the right will be used as a replacement in that case.

The && operator works similarly, but the other way around. When the value to its left is something that converts to false, it returns that value, and otherwise it returns the value on its right.

Another important property of these two operators is that the expression to their right is evaluated only when necessary. In the case of true || X, no matter what X is —even if it’s an expression that does something terrible— the result will be true, and X is never evaluated. The same goes for false && X, which is false and will ignore X. This is called short-circuit evaluation.

The conditional operator works in a similar way. The first expression is always evaluated, but the second or third value, the one that is not picked, is not.

OK, post (troppo) lungo ma è per finire il capitolo 😊


JavaScript 1 – Introduzione

Come raccontato qui parto con l’esame di JavaScript usando Eloquent JavaScript. Inizio qui.

This is a book about getting computers to do what you want them to do 😄
Marijn non poteva iniziare in modo migliore, bravo 🚀
Poi l’intro prosegue in modo altamente raccomandabile, da leggere, specie chi ancora non è dentro il magico mondo della programmazione.

In the beginning, at the birth of computing, there were no programming languages. Programs looked something like this:

00110001 00000000 00000000
00110001 00000001 00000001
00110011 00000001 00000010
01010001 00001011 00000010
00100010 00000010 00001000
01000011 00000001 00000000
01000001 00000001 00000001
00010000 00000010 00000000
01100010 00000000 00000000

That is a program to add the numbers from 1 to 10 together and print out the result: 1 + 2 + ... + 10 = 55. No, non sta lollando ma le cose sono –OK, lo so che lo sapete– mooolto cambiate 😜
Non riporto il sottocapitolo “On Programming” ma i nuovi dovrebbero leggerlo attentamente. Dalla definizione del problema si arriva allo script JavaScript pubblicato nel post precedente.

Cos’è JavaScript?
JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape Navigator browser. The language has since been adopted by all other major graphical web browsers. It has made modern web applications possible—applications with which you can interact directly, without doing a page reload for every action. But it is also used in more traditional websites to provide various forms of interactivity and cleverness.

It is important to note that JavaScript has almost nothing to do with the programming language named Java. The similar name was inspired by marketing considerations, rather than good judgment. When JavaScript was being introduced, the Java language was being heavily marketed and was gaining popularity. Someone thought it was a good idea to try to ride along on this success. Now we are stuck with the name.

After its adoption outside of Netscape, a standard document was written to describe the way the JavaScript language should work to make sure the various pieces of software that claimed to support JavaScript were actually talking about the same language. This is called the ECMAScript standard, after the Ecma International organization that did the standardization. In practice, the terms ECMAScript and JavaScript can be used interchangeably—they are two names for the same language.

JavaScript può sembrare terribile; sì a volte, questo perché [t]he idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder because the system will not point them out to you.

This flexibility also has its advantages, though. It leaves space for a lot of techniques that are impossible in more rigid languages, and as you will see [prossimamente] it can be used to overcome some of JavaScript’s shortcomings. After learning the language properly and working with it for a while, I have learned to actually like JavaScript.

Ah! ci sono diverse versioni… chissà che non capitino le solite incompatibilità 😡

Web browsers are not the only platforms on which JavaScript is used. Some databases, such as MongoDB and CouchDB, use JavaScript as their scripting and query language. Several platforms for desktop and server programming, most notably the Node.js project (the subject of Chapter 20) are providing a powerful environment for programming JavaScript outside of the browser.

Scrivere codice e cosa fare con esso
Code is the text that makes up programs. Most chapters in this book contain quite a lot of it. In my experience, reading code and writing code are indispensable parts of learning to program, so try to not just glance over the examples. Read them attentively and understand them. This may be slow and confusing at first, but I promise that you will quickly get the hang of it. The same goes for the exercises. Don’t assume you understand them until you’ve actually written a working solution.

I recommend you try your solutions to exercises in an actual JavaScript interpreter. Io uso Node.js, disponibile qui.

Inoltre: [w]hen reading this book in your browser, you can edit (and run) all example programs by clicking them.

If you want to run the programs defined in this book outside of the book’s sandbox, some care is required. Many examples stand on their own and should work in any JavaScript environment. But code in later chapters is mostly written for a specific environment (the browser or Node.js) and can run only there. In addition, many chapters define bigger programs, and the pieces of code that appear in them depend on each other or on external files. The sandbox on the website provides links to Zip files containing all of the scripts and data files necessary to run the code for a given chapter.

Good luck! dice Marijn –rockz 🚀
E prossimamente… 😉


JavaScript – mi manca e nel frattempo a Stanford…

Adapting to industry shifts and student feedback, the computer science department has implemented various changes to its introductory courses, CS106 and CS107.
This spring, a pilot version of CS106A, tentatively called CS106J, will be taught in Javascript instead of Java.

Uh! qui.
Forse –anzi ci provo, dai!– è il momento per acquisire i rudimenti del linguaggio, come faccio con altri, anche se poi non è detto che lo usi davvero.
E vorrei seguire –al solito– un tutor che mi guidi, possibilmente senza dover trafficare con browser, HTML e roba online. Se poi si potesse usare Node.js sarebbe il massimo.
Non è detto che poi non si amplii il progetto, con l’aiuto dei miei amici… 😉

Googlando ho trovato al volo un paio di documenti ufficiali:

JavaScript Guide e JavaScript reference di Mozilla Developer Network.
Da tener presenti per consultazione ma sono attirato da Eloquent JavaScript di Marijn Haverbeke.

Marijn l’ho già incontrato in passato, rockz! 🚀
Allora provo a veder se si può fare…

L’introduzione è tutta da leggere, chiara, completa e informata. Contiene uno snippet da provare:

var total = 0, count = 1;
while (count <= 10) {
  total += count;
  count += 1;

Oppure, fuori dalla REPL, mettere il codice nel file js0.js e

OK, ma si potrebbe anche scrivere più economicamente

ahemmmno, mancano le funzioni range() e sum(), Marijn ci dice che poi impareremo a farle, prossimamente.
Anzi andando a curiosare scopro che dovrò scriverle io, con la sua assistenza, spero.

OK, si comincia –prossimamente 😙