JAVASCRIPT STATEMENT
In this post we will discuss variables declared can var or let while also taking a look at the nomenclature commonly used by programmers for variable naming. Let us introduce the topic regarding the “Javascript syntax” by talking first about statements (instructions).
let a, b, c; // Statement 1
a = 5; // Statement 2
b = 6; // Statement 3
c = a + b; // Statement 4
The statement (instruction)
let a, b, c
declares three variables. A program is a list of “statements” that are to be “executed” by a computer. In HTML, JavaScript programs are executed by the web browser, more specifically there is an interpreter and a JIT (Just In Time) compiler that speeds up code execution. JavaScript statements (instructions) are composed of:
- values
- operators
- expressions
- keywords
Example:
document.getElementById(“demo“).innerHTML= “Hello World.“;
Most JavaScript programs contain many statements. Instructions are executed, one by one, in the same order in which they are written. (here the analogy with the post office worker who has to serve people in line one at a time Single-Thread) returns.
SEMICOLONS
Semicolons separate JavaScript instructions.
let a, b, c;
// Declare three variables
a = 5;
// Assigns the value 5 to a
b = 6;
// Assigns the value 6 to b
c = a + b;
// Assigns the sum of a and b to c
If separated by semicolon, multiple instructions are allowed on one line:
a = 5; b = 6; c = a + b;
On the Web, you might see examples without a semicolon. Semicolon ending instructions are not mandatory, But highly recommended. Another good practice is to put spaces around operators ( = + – * / ):
let x = y + z;
For better readability, programmers often prefer to avoid lines of code longer than 80 characters. If a JavaScript statement does not fit a line, the best place to break it is after an operator:
BLOCKS OF CODE
A block instruction (or a compound instruction in other languages) is used to group zero or more instructions. The block is delimited by a pair of curly brackets and can optionally be labeled: One place you will find instructions grouped into blocks is in JavaScript functions:
function myFunction() {
let a = 5;
console.log(a);
}
JavaScript statements often begin with a keyword to identify the JavaScript action to be performed. Keywords talking about JavaScript syntax are reserved words. Such words cannot be used as names for variables. Here is a list of some of the keywords you will learn in this tutorial:
JAVASCRIPT SYNTAX
JAVASCRIPT VALUES
JavaScript syntax defines two types of values:
- Fixed values
- Variable values
Fixed values are called literals. Variable values are called variables.
LITERALAS VALUES
The two most important syntactic rules for fixed values are:
- Numbers are written with or without decimals:
40.50
1401
- Strings are text, written in double or single quotes:
“Mario Rossi”
‘Mario Rossi’
JAVASCRIPT VARIABLES
In a programming language, variables are used to store data values. JavaScript uses the keywords
var, let and const to declare variables. An equal sign = is used to assign values to variables.
In this example, x is defined as a variable. Thus, x is assigned (given) the value 16:
let x;
x = 16;
JAVASCRIPT OPERATORS
- JavaScript uses arithmetic operators (+ – * / ) to calculate values:
(15 + 6) * 10
- Uses an assignment operator ( = ) to assign values to variables:
let x, y;
x = 25;
y = 26;
Values can be of various types, such as numbers and strings.
For example, “
Mario” + ” “ + “Rossi“, returns “Mario Rossi“: In this case, the + operator is the chaining operator.
JAVASCRIPT IDENTIFIERS
Identifiers are JavaScript names. Identifiers are used to name variables, keywords and functions. The rules for legal names are the same in most programming languages. A JavaScript name must begin with:
- One letter (A-Z or a-z)
- A dollar sign ($)
- Or an underscore (_)
The next characters can be letters, digits, underscores or $.
All JavaScript identifiers are case-sensitive. The variables lastName and lastname, are two different variables. JavaScript does not interpret LET or Let as a keyword. Historically, programmers have used several ways to combine multiple words into a variable name:
dashes:
- first-name, last-name, master-card, inter-city.
- Dashes are not allowed in JavaScript. They are reserved for subtraction
Underscore:
first_name, last_name, master_card, inter_city are valid variable names.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use the camel case that begins with a lowercase letter:
firstName, lastName, masterCard, interCity.
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