2. Variables
Variables are used to store content in memory that you'll need to read or modify later: text, numbers, booleans or dictionaries.
The syntax is structured as follows:
[type] [key] = [value];
for example
const nombre = 'Andrea';
Keys cannot contain spaces, accents, special characters or start with a number.
const nombre = 'Andrea'; // Good
const 2nombre = 'Joan'; // Bad
const nombre con apellido = 'Joan Chamorro'; // Bad
const nombreConApellido = 'Andrea Motis'; // Good, using camelCase format
Instead of spaces, by convention, the camel case format is used: each following word must start with a capital letter.
const musicoConInstrumento = 'Joan Chamorro';
const musicoYCantante = 'Andrea Motis';
Types
Now that you understand how it's structured, it's time to understand the 3 types you can use:
- const: local access, read-only.
- let: local access, readable and editable.
- var: global access, readable and editable.
Local access means that the variable can only be accessed in the context where the application is running. In other words, you can't use it outside a pair of {}.
Notice how the types have been applied to 3 different variables:
const discografica = 'jazztojazz';
let pistas = 16;
var titulo = 'Feeling good';
Content types
The value of a variable can be of different types.
Text (String)
Can use single or double quotes.
const nombre = 'Lucia';
Whole numbers (Integer)
const edad = 31;
Decimals (Float)
Using a dot instead of a comma.
const altura = 1.72;
True or false (Boolean)
const mayorEdad = true;
const fumador = false;
Null (null)
const dieta = null;
Undefined (undefined)
Absence of a value. We shouldn't assign it.
const salud = undefined;
JSON (object)
This is a value that contains other values. It's used to store a complex structure in a variable.
[type] [key] = {
[subkey]: [value],
[subkey]: [value]
};
Subkeys are separated from each other by commas.
for example
let disco = {
pistas: 16,
titulo: 'Feeling good',
discografica: 'jazztojazz'
};
Don't make the mistake of adding a comma (
,) on the last line.
Arithmetic operations
The same elements you already know are used. For example, to add 2 variables, we'd use the + symbol.
const num1 = 10;
const num2 = 5;
const resultado = num1 + num2;
console.log(resultado);
// 15
Although it's also possible to work directly with values.
const resultado = 20 + 3;
console.log(resultado);
// 23
Other available operations:
Addition
const resultado = num1 + num2;
Subtraction
const resultado = num1 - num2;
Division
const resultado = num1 / num2;
Multiplication
const resultado = num1 * num2;
Remainder
const resultado = num1 % num2;
Power (raised to...)
const resultado = num1 ** num2;
Parentheses
If you need to perform more complex operations, you can rely on parentheses.
const resultado = (5 * 2) + (10 / 2)
console.log(resultado);
// 15
Increment or decrement
If you want to increase a number, or reduce it, you can use the following approach.
let numero = 1;
numero += 1;
// 2
This is the equivalent of doing:
let numero = 1;
numero = numero + 1;
// 2
A very common shortcut is to use ++ or --. A heads-up: the variable can't be a constant.
let numero = 1;
numero++;
// 2
let segundoNumero = 1;
numero--;
// 0
It changes the value by increasing or decreasing it by 1.
You should also know that it's possible to use it as a prefix or a suffix, with different return values.
//// Incrementing with suffix ++
let numero = 5;
console.log(numero++)
// 5
console.log(numero)
// 6
//// Incrementing with prefix ++
let numero = 5;
console.log(++numero)
// 6
console.log(numero)
// 6
The difference is:
numero++: Increments but returns the value before the change, the previous one.++numero: Increments and returns the changed value.
The same applies, in the same way, to --.
Manipulation
Concatenation
To join several strings we have several options.
With the + symbol.
const nombre = 'Atila';
const apodo = ' el huno';
const completo = nombre + apodo;
console.log(completo);
// Atila el huno
With tagged templates (Tagged templates).
const zona = 'Mancha';
const libro = `En un lugar de la ${zona} cuyo nombre no me quiero acordar...`;
console.log(libro);
// En un lugar de la Mancha cuyo nombre no me quiero acordar...
Or with the concat() function.
const lugar = 'Notre-Dame tiene una altura de ';
const altura = 128;
const medida = ' metros';
const textoCompuesto = ''.concat(lugar, altura, medida);
console.log(textoCompuesto);
// Notre-Dame tiene una altura de 128 metros
These are 3 ways to do the same thing, but whenever you can, use tagged templates since they're more modern and easier to read.
Manipulating strings
A string has a large number of features for transforming text.
const cadenaNormal = 'El 90% de nuestras decisiones las toma nuestro subconsciente';
// Converts to uppercase
const cadenaMayusculas = cadenaNormal.toUpperCase();
// Converts to lowercase
const cadenaMinusculas = cadenaNormal.toLowerCase();
// Number of characters
const longitud = cadenaNormal.length;
You can learn about other features in the Mozilla documentation.
Converting between types
At times you'll need to change one type into another to perform arithmetic operations or transformations. A common case: I have a number and I want to know how many digits it has. I should convert it to a string and then use .length (a number doesn't have the feature to know its length).
When the time comes to change types, you'll find several tools.
Integer/Float to String
To transform a number into text you have 2 options.
Using the + operator.
const miTexto = 45.3 + '';
or the .toString() function.
const miTexto = (45.3).toString();
String to Integer/Float
To go from text to a decimal or whole number, we'll use two functions.
// Whole number
const miNumero = parseInt('45');
// Decimal number
const miDecimal = parseFloat('45.3');
Activity 1
Manipulate the following quote by Richard Stallman:
"Sharing knowledge is the most fundamental act of friendship. Because it is a way of giving something without losing anything."- Save the text in a variable.
- Transform it to uppercase.
- Print it to the console (
console.log). - Transform it to lowercase.
- Print it to the console (
console.log).
Nightmare level 👹
- How many characters does it have?
- And how long is it without spaces?
Activity 2
How old is Madonna? Here's a fact: she was born in 1958.
- Calculate it and save the result in a variable.
- Print the age with a nicer format: "Madonna is xx years old".
Nightmare level 👹
Get the current year with JavaScript.
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.