JavaScript is a dynamically-typed language, which means that variables do not have a fixed type at declaration and can change their type during runtime. There are six primitive data types in JavaScript, which include:
Number: This data type is used to represent both integers and floating-point numbers. Numbers can be positive, negative, or zero.
Example:
var x = 10; // integer
var y = 3.14; // floating-point number
String: This data type is used to represent textual data. Strings are enclosed in single quotes, double quotes, or backticks.
Example:
var greeting = 'Hello, world!'; // single quotes
var message = "It's a beautiful day!"; // double quotes
var template = `The value of x is ${x}.`; // backticks
Boolean: This data type is used to represent logical values. Boolean values can be either true or false.
Example:
var isSunny = true;
var isRaining = false;
Null: This data type is used to represent the intentional absence of any object value. It is often used to indicate that a variable has no value.
Example:
var myVariable = null;
Undefined: This data type is used to represent a variable that has been declared but has not been assigned a value.
Example:
var myVariable;
console.log(myVariable); // Outputs undefined
Symbol: This data type is used to represent unique values that are not equal to any other value. Symbols are often used to create unique identifiers.
Example:
var id1 = Symbol('id');
var id2 = Symbol('id');
console.log(id1 === id2); // Outputs false
In addition to these primitive data types, JavaScript also has two composite data types:
Object: This data type is used to represent a collection of properties. Objects can contain any combination of primitive and composite data types, as well as functions.
Example:
var person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
hobbies: ['reading', 'playing music'],
address: {
street: '123 Main St.',
city: 'Anytown',
state: 'CA'
},
sayHello: function() {
console.log('Hello, my name is ' + this.firstName + ' ' + this.lastName + '.');
}
};
console.log(person.firstName); // Outputs 'John'
console.log(person.hobbies[0]); // Outputs 'reading'
person.sayHello(); // Outputs 'Hello, my name is John Doe.'
Array: This data type is used to represent a collection of values. Arrays are ordered lists of values, and each value is assigned an index starting from 0.
Example:
var fruits = ['apple', 'banana', 'orange'];
console.log(fruits[1]); // Outputs 'banana'
These are the data types available in JavaScript. As a JavaScript expert, I would be happy to provide more information or examples if needed.