JavaScript is a dynamic programming language that supports various data types. Data types are used to define the type of data that can be stored in a variable. In JavaScript, there are two types of data types: primitive and non-primitive.
Primitive data types are the basic data types that are built into the JavaScript language. They are immutable, which means that their values cannot be changed once they are created. The five primitive data types in JavaScript are:
The string data type is used to represent a sequence of characters. Strings are enclosed in single or double quotes. Here is an example:
var name = 'John';
console.log(name); // Output: John
The number data type is used to represent numeric values. Numbers can be integers or floating-point numbers. Here is an example:
var age = 25;
console.log(age); // Output: 25
The boolean data type is used to represent true or false values. Here is an example:
var isStudent = true;
console.log(isStudent); // Output: true
The null data type is used to represent a null or empty value. Here is an example:
var result = null;
console.log(result); // Output: null
The undefined data type is used to represent a variable that has not been assigned a value. Here is an example:
var score;
console.log(score); // Output: undefined
Non-primitive data types are more complex data types that are not built into the JavaScript language. They are mutable, which means that their values can be changed. The three non-primitive data types in JavaScript are:
The object data type is used to represent a collection of related data. Objects are created using curly braces and can contain properties and methods. Here is an example:
var person = {
name: 'John',
age: 25,
isStudent: true,
sayHello: function() {
console.log('Hello!');
}
};
console.log(person.name); // Output: John
person.sayHello(); // Output: Hello!
The array data type is used to represent a collection of values. Arrays are created using square brackets and can contain any combination of data types. Here is an example:
var numbers = [1, 2, 3, 4, 5];
console.log(numbers[2]); // Output: 3
The function data type is used to define a set of instructions that can be executed. Functions are created using the function keyword and can be called with arguments. Here is an example:
function addNumbers(a, b) {
return a + b;
}
console.log(addNumbers(2, 3)); // Output: 5
JavaScript supports various data types that are used to define the type of data that can be stored in a variable. Primitive data types are the basic data types that are built into the JavaScript language, while non-primitive data types are more complex data types that are not built into the JavaScript language.