VALUES AND VARIABLES IN JAVASCRIPT
In this introductory part, some concepts are repeated. It is useful to fix well what are the basic elements of language. Values are fundamental units of any program. To understand what a value is, let’s take a culinary example. To make a dish we need various ingredients that properly combined together provide us with the desired dish. Similarly in javascript we need a whole set of information units which are the values, without the values it is as if we want to prepare that delicious dish but without having the ingredients available.
VARIABLES
The javascript values are deposited in the computer’s memory and we need to be able to access them when needed. For this need javascript like any other programming language provides us with the variables.They are somewhat like cardboard containers in which to deposit objects. Variables do not contain the value, but they are the reference to the information that is in memory.
For example, suppose we want to declare a variable anni. The word alone is not enough but must be preceded by var, let or const. let and const were introduced in ES2015. We declare the variable with var.
var anni;
We have declared a variable, that is, an in-memory reference to a value, but we have not assigned anything. We assign 36.
IDENTIFIERS
From now on in our javascript program we can access that value through the years identifier. Let’s give some examples.
var years = 36;
let name = “Mark”;
const profession = “web developer”
We have declared three perfectly valid variables. But the following statement declaring an uninitialized variable is also valid.
var food;
let age = 20;
const lastname; //Error a variable declared with const we need to assign a value.
const lastname =”Rossi”;
Let us try changing the variable years.
years = 30;
console.log(years); //will print 30, the value 36 has been overwritten.
name = “Luigi”;
console.log(name) //ok will print out Luigi
If we try to change the variable last name declared with const we get an error, to a constant cannot be reassigned a new value.
Let us now talk about identifiers. Write the following assignment: let 32 = “hello” is not a valid identifier, to be valid an identifier must begin with a letter, underscore or dollar, must not contain spaces, must not begin with a number. The number cannot be the first character but can be within the name. Javascript is case-sensitive.
let a = 10;
let A = 20;
LET’S GIVE SOME EXAMPLES WITH THE VARIABLES
var x = 15;
var y = 26;
var z = x + y;
In this other example, x, y and z are variables, declared with the let keyword:
let x = 15;
let y = 26;
let z = x + y;
From all the examples above, we have that:
x stores the value 15
y stores the value 26
z stores the value 41
Always declare JavaScript variables with var or let . The keyword var is used throughout JavaScript code from 1995 to 2015.The keywords let e const were added in 2015. If you want your code to run in an older browser, you need to use var.
WHEN TO USE THE CONST KEYWORD
If the data value changes, use let or var. In this example, price1 and price2 are constants and total is a variable:
const price1 = 15;
const price2 = 16;
let total = price1 + price2 + 30;
The two constants price1 and price2 are declared with the keyword const.These are values that do not change and cannot be changed. The variable total is declared with the keyword let.This is a value that can be changed. Use
const when you need to store data that does not change during program execution, such as the pi value.
SOME MORE INFORMATION ABOUT IDENTIFIERS
All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (such as x and y) or more descriptive names (age, sum, volume, total). The general rules for constructing names for variables (unique identifiers) are:
- Names may contain letters, digits, underscores and dollar signs.
- Names must begin with a letter
- Names can also begin with $ and _
- Names are case-sensitive (x and X are different variables)
- Reserved words cannot be used as names
ASSIGNMENT OPERATOR
In JavaScript, the equal sign (=) is an “assignment” operator, not an “equals to” operator. This is different from algebra. The following does not make sense in ‘algebra:
x = x + 15
In JavaScript, however, it makes perfect sense: it assigns the value of x + 15 to x. The above expression reads: (Calculates the value of x + 15 and enters the result of the operation in x. The value of x is incremented by 15.). The “equals to” operator is written as ==.
DATA TYPES
JavaScript variables can contain numbers such as 100 and text values such as “Mario Rossi“. In programming, text values are called strings. JavaScript can handle many types of data, but for now just think of numbers and strings. Text values are written in double or single quotation marks. Numbers are written without quotation marks; if you put them in quotation marks, they will be treated as text strings.
DECLARATION OF VARIABLES
The creation of a variable in JavaScript is called a “declaration.” You declare a variable with the var or let keyword:
let carName;
After the declaration, the variable has no value (technically it is called undefined). To assign a value to the variable, the equal sign is used:
carName = “Volvo”;
You can also assign a value to the variable when you declare it:
let carName = “Volvo“;
It is good programming practice to declare all variables at the beginning of a script.
Many variables can be declared in a single statement. You start the instruction with the keyword let and you separate the variables with a comma:
let person = ” Mario Rossi“, car = “Volvo“, price =200;
A statement can span multiple lines:
let person = “Mario Rossi“,
machine = “Volvo“,
price = 200;
THE VALUE UNDEFINED
In computer programs, variables are often declared without a value. The value can be something that needs to be calculated or something that will be provided later, such as user input. A variable declared without a value will be undefined. The variable carName will have that value after the execution of this instruction:
let carName;
If you re-declare a JavaScript variable declared with var, it will not lose its value. The variable carName will still have the value “Volvo” after executing these instructions:
var carName = “Volvo“;
var carName;
whereas
you cannot re-declare a variable or constant declared with let or const.
DEEPENING AI
In JavaScript, variables are used to store values and data that can be retrieved, manipulated, or used within a program. They are one of the fundamental concepts of programming, as they allow us to manage and store information dynamically. The following is a detailed description of variables in JavaScript, explaining the different types of declarations, their scope, and how assignment and update concepts work.
1. Declaring Variables
In JavaScript, there are three main keywords to declare a variable: var, let, and const.
a. var
•This is the traditional way to declare a variable in JavaScript (before let and const were introduced in ECMAScript 6).
•Variables declared with var are functional or global. This means that if they are declared inside a function, they are only visible within the function (local scope), while if they are declared outside a function, they become global variables.
•Supports hoisting, which means that the variable declaration is moved to the top of the execution context, but the initialization is not. This can lead to unexpected behavior.
Example:
var x = 5;
if (true) {
var x = 10; // Modifica la variabile x globale
}
console.log(x); // Output: 10
b. let
•Introduced in ECMAScript 6, let allows you to declare variables with block scope. This means that the variable only exists within the {} block in which it was declared.
•Unlike var, it does not support hoisting in the same way, making the code more predictable.
Example:
let x = 5;
if (true) {
let x = 10; // Variabile diversa, scope di blocco
}
console.log(x); // Output: 5
c. const
• Also const was introduced in ECMAScript 6. It is used to declare variables that cannot be reassigned. The variable declared with const must be initialized immediately and cannot be updated later.
• It is also bound to the block scope, like let.
• Even if the reference to an object or array is constant, the internal properties can be modified.
const x = 10;
x = 20; // Errore: non si può riassegnare una costante
const obj = { name: “Alice” };
obj.name = “Bob“; // Questo è permesso perché stiamo modificando una proprietà interna dell’oggetto
2. Scope of variables
The scope of a variable defines the context in which it is accessible.
•Global Scope: A variable declared outside of any function or block is global and accessible from anywhere in the code.
•Function Scope: Variables declared inside a function with var are accessible only within the function itself.
•Block Scope: With let and const, a variable is accessible only within the block in which it is declared (within {}). This includes blocks such as for loops, while loops, and if conditional blocks.
Block scope example:
if (true) {
let x = 5;
}
console.log(x); // Errore: x non è definita al di fuori del blocco
3. Hoisting
Hoisting is the JavaScript behavior that moves variable (var) declarations and functions to the top of their execution context. However, only the declaration is moved to the top, not the initialization.
Hoisting example with var:
console.log(x); // Output: undefined (non errore)
var x = 5;
Example with let:
console.log(y); // Errore: y non è definita
let y = 10;
4. Assigning and Updating Variables
Once you declare a variable, you can assign a value to it and then update it (except for const constants, which cannot be reassigned).
Example:
let x = 5;
x = 10; // Variabile aggiornata
console.log(x); // Output: 10
With const, as mentioned, once you assign a value, the variable cannot be changed.
5. Data Types Associated with Variables
Variables in JavaScript can contain different types of data:
•Numbers (number): e.g. 42, 3.14
• Strings (string): e.g. “Hello, world!”
• Booleans (boolean): e.g. true, false
•Arrays: e.g. [1, 2, 3]
• Objects: e.g. { name: “Alice”, age: 30 }
•Null: An intentionally empty value.
•Undefined: Indicates that a variable has been declared but does not yet have a value assigned to it.
•Symbol: A unique, immutable primitive data type introduced in ECMAScript 6.
6. Naming Rules
Variables in JavaScript must follow certain rules regarding names:
•They must start with a letter, an underscore _, or a dollar sign $.
•They cannot start with a number.
•Variable names are case-sensitive, which means that myVariable and myvariable are two different variables.
Example of valid names:
let _var = 1;
let $element = “div“;
let myVariable = 10;
7. Best practices
•Use let or const instead of var: It is considered a good modern practice to use let for variables that can be reassigned and const for constants, as it prevents scope and hosting issues.
•Meaningful assignment: Give variables clear and descriptive names to make your code easier to read.
•Minimize global variables: Declaring too many global variables can create conflicts and errors that are difficult to spot.
Conclusion
Variables in JavaScript are powerful tools for storing and managing data within your programs. Understanding how var, let, and const work, along with concepts like scope and hoisting, is essential to writing efficient, error-free JavaScript code.
Leave A Comment