JavaScript supports several data types, which can be broadly categorized into two groups: primitive and non-primitive (also known as reference types).
- Primitive data types: Primitive data types are the most basic data types in JavaScript, and they are immutable (cannot be changed). There are six primitive data types in JavaScript:
- number: represents numeric values, e.g. 1, 3.14
- string: represents textual data, enclosed in single or double quotes, e.g. 'hello', "world"
- boolean: represents logical values, either- trueor- false
- null: represents a null or empty value
- undefined: represents a variable that has not been assigned a value
- symbol: represents a unique identifier, introduced in ECMAScript 6
Here's an example of defining and using primitive data types in JavaScript:
javascriptlet myNumber = 42;
let myString = 'hello';
let myBoolean = true;
let myNull = null;
let myUndefined;
let mySymbol = Symbol('foo');
console.log(typeof myNumber); // output: 'number'
console.log(typeof myString); // output: 'string'
console.log(typeof myBoolean); // output: 'boolean'
console.log(typeof myNull); // output: 'object' (this is a quirk in JavaScript, typeof null returns 'object')
console.log(typeof myUndefined); // output: 'undefined'
console.log(typeof mySymbol); // output: 'symbol'
- Non-primitive data types: Non-primitive data types are reference types, which are more complex data types and can hold more complex data structures. They are mutable (can be changed). There are three non-primitive data types in JavaScript:
- object: represents a collection of properties, e.g.- {name: 'John', age: 30}
- array: represents a collection of values, e.g.- [1, 2, 3]
- function: represents a reusable block of code that can be called, e.g.- function add(a, b) { return a + b; }
Here's an example of defining and using non-primitive data types in JavaScript:
javascriptlet myObject = {name: 'John', age: 30};
let myArray = [1, 2, 3];
let myFunction = function(a, b) { return a + b; };
console.log(typeof myObject); // output: 'object'
console.log(typeof myArray); // output: 'object'
console.log(typeof myFunction); // output: 'function'