ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 1 · 4లో పాఠం 1కోర్సులో 1/32~8 min
మాడ్యూల్ పాఠాలు (1/4)

వేరియబుల్స్: లెట్ మరియు కాన్స్ట్

In JavaScript, variables are names we bind a value to. Every time you write "real" code, the first thing you do is give names to the things you want to manipulate. Modern JavaScript gives you two keywords:

JS
const numero = 42; // valore fissato per sempre
let contatore = 0; // valore che puoi riassegnare

Read in English: "call numero the value 42". From that moment on, every time you write numero in the same block, JS replaces it with 42.

const: the default you want to use almost always

const declares a non-reassignable variable. Once bound, you cannot point it to another value:

JS
const pi = 3.14;
pi = 3; // TypeError: Assignment to constant variable.

This rigidity is a good thing: the vast majority of names in your code represent a value that should not change during its lifetime, and const makes this explicit to the reader.

let: when the value changes

let declares a reassignable variable. You use it when a name has to point to different values over time:

JS
let punteggio = 0;
punteggio = punteggio + 10;
punteggio = punteggio + 5;
console.log(punteggio); // 15

Scope: where a variable lives

let and const live in the block they are declared in — that is, between curly braces { … }. Outside that block, they simply do not exist:

JS
{
  const segreto = 'shh';
  console.log(segreto); // 'shh'
}
console.log(segreto); // ReferenceError: segreto is not defined

Try it

వ్యాయామం#js.m1.l1.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Declare a constant called `greeting` with the value 'Ciao, mondo!' and then write it as the last expression (so it will be shown as the result).

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

The last expression of a JS block is captured as the 'return value' of the exercise.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#js.m1.l1.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Create a `let` called `total` initialized to 0, add 7 to it and then 5, finally evaluate `total` as the last expression.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

You can reassign a let with `name = name + something` (or with the shortcut `+=`).

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది