Data Types
In JavaScript, variables can store different types of data, such as numbers, strings, booleans, objects, arrays, and functions. These data types are used to represent different kinds of values and can be manipulated using various operations. JavaScript is a dynamically typed language, meaning that variables can change their data type during runtime.
Primitive Data Types
Primitive data types are the basic building blocks of JavaScript and include the following types:
Number
: Represents numeric values (e.g.,10
,3.14
).String
: Represents textual data (e.g.,'Hello, World!'
).Boolean
: Represents logical values (true
orfalse
).Undefined
: Represents an undefined value (e.g.,undefined
).Null
: Represents a null value (e.g.,null
).Symbol
: Represents a unique value (e.g.,Symbol('foo')
).
Non-Primitive Data Types
Non-primitive data types are objects that can store multiple values and have properties and methods. JavaScript has three non-primitive data types:
Object
: Represents a collection of key-value pairs (e.g.,{name: 'John', age: 30}
).Array
: Represents a list of elements (e.g.,[1, 2, 3]
).Function
: Represents a block of code that can be executed (e.g.,function add(a, b) { return a + b; }
).
You can use the typeof
operator to check the data type of a variable:
let x = 10;
console.log(typeof x); // Output: number
Type Conversion
JavaScript automatically converts values from one data type to another when needed. This process is known as type conversion or type coercion. For example, you can concatenate a number with a string, and JavaScript will convert the number to a string:
let x = 10;
let message = 'The number is: ' + x;
console.log(message); // Output: The number is: 10
You can also explicitly convert values from one data type to another using built-in functions like Number()
, String()
, and Boolean()
:
let x = '10';
let y = Number(x); // Convert string to number
console.log(y); // Output: 10
Type conversion is an essential concept in JavaScript and is used in various scenarios to manipulate and transform data.
In the next section, we will the primitive types in more detail. Let's keep going 🚀
Made with ❤️ by Fasakin Henry