Memorizzazione delle informazioni necessarie - Variabili

Dopo aver letto gli ultimi due articoli, ora dovresti sapere cos'è JavaScript, cosa può fare per te, come lo usi insieme ad altre tecnologie web e quali sono le sue caratteristiche principali da un livello elevato. In questo articolo, passeremo alle basi reali, esaminando come lavorare con i blocchi di base di JavaScript - Variabili.

Prerequisiti: Nozioni di base di informatica, comprensione di base di HTML e CSS, comprensione di cosa sia JavaScript
Obiettivo: Acquisire familiarità con le basi delle variabili JavaScript.

Strumenti di cui hai bisogno

In questo articolo ti verrà chiesto di digitare righe di codice per testare la tua comprensione del contenuto. Se si utilizza un browser desktop, il posto migliore per digitare il codice di esempio è la console JavaScript del browser (vedere Quali sono gli strumenti di sviluppo del browser per ulteriori informazioni su come accedere a questo strumento).

Cosa è una variabile?

Una variabile è un contenitore per un valore, come un numero che potremmo usare in una somma o una stringa che potremmo usare come parte di una frase. Ma una cosa speciale delle variabili è che i loro valori possono cambiare. Diamo un'occhiata a un semplice esempio:

<button>Press me</button>
const button = document.querySelector('button');

button.onclick = function() {
  let name = prompt('What is your name?');
  alert('Hello ' + name + ', nice to see you!');
}

In questo esempio, premendo il bottone viene eseguito un paio di righe di codice. La prima riga apre una finestra sullo schermo che chiede al lettore di inserire il proprio nome, quindi memorizza il valore in una variabile. La seconda riga mostra un messaggio di benvenuto che include il loro nome, preso dal valore della variabile.

Per capire perché questo è così utile, pensiamo a come scrivere questo esempio senza usare una variabile. Finirebbe per assomigliare a questo:

let name = prompt('What is your name?');

if (name === 'Adam') {
  alert('Hello Adam, nice to see you!');
} else if (name === 'Alan') {
  alert('Hello Alan, nice to see you!');
} else if (name === 'Bella') {
  alert('Hello Bella, nice to see you!');
} else if (name === 'Bianca') {
  alert('Hello Bianca, nice to see you!');
} else if (name === 'Chris') {
  alert('Hello Chris, nice to see you!');
}

// ... and so on ...

Potresti non comprendere appieno la sintassi che stiamo usando (ancora!), ma dovresti essere in grado di farti un'idea - se non avessimo variabili disponibili, dovremmo implementare un blocco di codice gigante che controlla quale sia il nome inserito e quindi visualizzare il messaggio appropriato per quel nome. Questo è ovviamente molto inefficiente (il codice è molto più grande, anche solo per cinque scelte), e semplicemente non funzionerebbe - non è possibile memorizzare tutte le possibili scelte.

Le variabili hanno senso e, man mano che impari di più su JavaScript, inizieranno a diventare una seconda natura.

Un'altra cosa speciale delle variabili è che possono contenere qualsiasi cosa, non solo stringhe e numeri. Le variabili possono anche contenere dati complessi e persino intere funzioni per fare cose sorprendenti. Imparerai di più su questo mentre procedi.

Nota:Diciamo che le variabili contengono valori. Questa è una distinzione importante da fare. Le variabili non sono i valori stessi; sono contenitori per valori. Puoi pensare che siano come piccole scatole di cartone in cui puoi riporre le cose.

Dichiarare una variabile

Per usare una variabile, devi prima crearla - più precisamente, dobbiamo dichiarare la variabile. Per fare ciò, utilizziamo la parola chiave var o let seguita dal nome che vuoi chiamare la tua variabile:

let myName;
let myAge;

Qui stiamo creando due variabili chiamate myName e myAge. Prova a digitare queste righe nella console del tuo browser web. Successivamente, prova a creare una (o due) variabili chiamandole a tuo piacimento.

Nota: In JavaScript, tutte le istruzioni del codice dovrebbero terminare con un punto e virgola (;) - il codice potrebbe funzionare correttamente per singole righe, ma probabilmente non funzionerà quando si scrivono più righe di codice insieme. Cerca di prendere l'abitudine di includerlo.

Puoi verificare se questi valori ora esistono nell'ambiente di esecuzione digitando solo il nome della variabile, ad es.

myName;
myAge;

Al momento non hanno valore; sono contenitori vuoti. Quando si immettono i nomi delle variabili, è necessario ottenere un valore undefined. Se non esistono, verrà visualizzato un messaggio di errore: "try typing in

scoobyDoo;

Nota: Non confondere una variabile esistente ma che non ha alcun valore definito con una variabile che non esiste affatto: sono cose molto diverse. Nell'analogia della scatola che hai visto sopra, non esistere significherebbe che non esiste una scatola (variabile) in cui inserire un valore. Nessun valore definito significherebbe che c'è una scatola, ma non ha alcun valore al suo interno.

Initializing a variable

Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (=), followed by the value you want to give it. For example:

myName = 'Chris';
myAge = 37;

Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by simply typing their name into the console — try these again:

myName;
myAge;

You can declare and initialize a variable at the same time, like this:

let myDog = 'Rover';

This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.

The difference between var and let

At this point you may be thinking "why do we need two keywords for defining variables?? Why have var and let?".

The reasons are somewhat historical. Back when JavaScript was first created, there was only var. This works basically fine in most cases, but it has some issues in the way it works — its design can sometimes be confusing or downright annoying. So, let was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.

A couple of simple differences are explained below. We won't go into all the differences now, but you'll start to discover them as you learn more about JavaScript (if you really want to read about them now, feel free to check out our let reference page).

For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example:

myName = 'Chris';

function logName() {
  console.log(myName);
}

logName();

var myName;

Note: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.

This works because of hoisting — read var hoisting for more detail on the subject.

Hoisting no longer works with let. If we changed var to let in the above example, it would fail with an error. This is a good thing — declaring a variable after you initialize it results in confusing, harder to understand code.

Secondly, when you use var, you can declare the same variable as many times as you like, but with let you can't. The following would work:

var myName = 'Chris';
var myName = 'Bob';

But the following would throw an error on the second line:

let myName = 'Chris';
let myName = 'Bob';

You'd have to do this instead:

let myName = 'Chris';
myName = 'Bob';

Again, this is a sensible language decision. There is no reason to redeclare variables — it just makes things more confusing.

For these reasons and more, we recommend that you use let as much as possible in your code, rather than var. There is no reason to use var, unless you need to support old versions of Internet Explorer with your code (it doesn't support let until version 11; the modern Windows Edge browser supports let just fine).

Note: We are currently in the process of updating the course to use let rather than var. Bear with us!

Updating a variable

Once a variable has been initialized with a value, you can change (or update) that value by simply giving it a different value. Try entering the following lines into your console:

myName = 'Bob';
myAge = 40;

An aside on variable naming rules

You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.

  • You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.
  • Don't use underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.
  • Don't use numbers at the start of variables. This isn't allowed and causes an error.
  • A safe convention to stick to is so-called "lower camel case", where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.
  • Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
  • Variables are case sensitive — so myage is a different variable from myAge.
  • One last point: you also need to avoid using JavaScript reserved words as your variable names — by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words like var, function, let, and for as variable names. Browsers recognize them as different code items, and so you'll get errors.

Note: You can find a fairly complete list of reserved keywords to avoid at Lexical grammar — keywords.

Good name examples:

age
myAge
init
initialColor
finalOutputValue
audio1
audio2

Bad name examples:

1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongstupidvariablenameman

Error-prone name examples:

var
Document

Try creating a few more variables now, with the above guidance in mind.

Variable types

There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.

So far we've looked at the first two, but there are others.

Numbers

You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:

let myAge = 17;

Strings

Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name.

let dolphinGoodbye = 'So long and thanks for all the fish';

Booleans

Booleans are true/false values — they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:

let iAmAlive = true;

Whereas in reality it would be used more like this:

let test = 6 < 3;

This is using the "less than" operator (<) to test whether 6 is less than 3. As you might expect, it returns false, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.

Arrays

An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:

let myNameArray = ['Chris', 'Bob', 'Jim'];
let myNumberArray = [10, 15, 40];

Once these arrays are defined, you can access each value by their location within the array. Try these lines:

myNameArray[0]; // should return 'Chris'
myNumberArray[2]; // should return 40

The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.

You'll learn a lot more about arrays in a future article.

Objects

In programming, an object is a structure of code that models a real-life object. You can have a simple object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.

Try entering the following line into your console:

let dog = { name : 'Spot', breed : 'Dalmatian' };

To retrieve the information stored in the object, you can use the following syntax:

dog.name

We won't be looking at objects any more for now — you can learn more about those in a future module.

Dynamic typing

JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc).

For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:

let myString = 'Hello';

Even if the value contains numbers, it is still a string, so be careful:

let myNumber = '500'; // oops, this is still a string
typeof myNumber;
myNumber = 500; // much better — now this is a number
typeof myNumber;

Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called typeof — this returns the data type of the variable you type after it. The first time it is called, it should return string, as at that point the myNumber variable contains a string, '500'. Have a look and see what it returns the second time you call it.

Constants in JavaScript

Many programming languages have the concept of a constant — a value that once declared can never be changed. There are many reasons why you'd want to do this, from security (if a third party script changed such values it could cause problems) to debugging and code comprehension (it is harder to accidentally change values that shouldn't be changed and mess things up).

In the early days of JavaScript, constants didn't exist. In modern JavaScript, we have the keyword const, which lets us store values that can never be changed:

const daysInWeek = 7;
const hoursInDay = 24;

const works in exactly the same way as let, except that you can't give a const a new value. In the following example, the second line would throw an error:

const daysInWeek = 7;
daysInWeek = 8;

Summary

By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math in JavaScript.

In this module