In JavaScript, a primitive value is a basic data type that is not an object and has no methods or properties. There are six primitive data types in JavaScript: string, number, boolean, null, undefined, and symbol.
Primitive values are immutable and often used in JavaScript, as they are simpler, faster to access, and can be used as keys in object properties.
There are six primitive data types in JavaScript:
Primitive Value | Definition |
---|---|
String | Represents a sequence of characters, enclosed in quotes (single or double). |
Number | Represents a numeric value, including integers and floating-point numbers. |
Boolean | Represents a logical value, either true or false . |
Null | Represents an intentional absence of any object value. |
Undefined | Represents a variable that has been declared but has not been assigned a value. |
Symbol | Represents a unique identifier that can be used as the key of an object property. |
Primitive value in JavaScript example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
// string
let name = 'Alice';
console.log(typeof name, name);
// number
let age = 30;
console.log(typeof age, age);
// boolean
let hasCar = false;
console.log(typeof hasCar, hasCar);
// null
let result = null;
console.log(typeof result, result);
// undefined
let address;
console.log(typeof address, address);
// symbol
let id = Symbol('id');
</script>
</body>
</html>
Output:
Primitive values are immutable, meaning that their values cannot be changed after they are created. Any operation that appears to change a primitive value actually creates a new value instead.
For example, if we have a string variable:
let name = 'John';
and we try to change it to 'Jane'
:
name[0] = 'J';
This operation will not change the value of the name
variable, but will instead create a new string value that is not stored anywhere.
Comment if you have any doubts or suggestions on this Js data type topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version