One of the main features of Javascript is its ability to work with variables and data types. Variables are used to store values that can change during code execution, while data types define the type of information being stored.
In Javascript, variables are declared using the "var" keyword, followed by the variable name and, optionally, the initial value. For example:
var name = "John"; var age = 30; var height;
In the example above, the variable "name" receives the value "John", the variable "age" receives the value 30 and the variable "height" is declared with no initial value.
The most common data types in Javascript are:
- String: used to store text such as names and phrases. Strings are delimited by single or double quotes. Example: "Hello world!"
- Number: used to store numerical values, such as integers and decimals. Example: 10 or 3.14
- Boolean: used to store true or false values. Example: true or false
- Array: used to store a list of values, which can be of different types. Example: [1, "John", true]
- Object: used to store a set of properties and their values. Example: {name: "John", age: 30, height: 1.75}
- Undefined: used to indicate that a variable has no initial value. Example: var height;
- Null: used to indicate that a variable has no value. Example: var name = null;
In addition to these data types, Javascript also has the "function" type, used to store functions that can be executed in different parts of the code.
To find out the data type of a variable in Javascript, we can use the "typeof" operator. For example:
var name = "John"; var age = 30; console.log(typeof name); // string console.log(typeof age); // number
With the use of variables and data types, it is possible to create more dynamic and flexible codes in Javascript, allowing the manipulation of information in a more efficient and organized way.