In JavaScript, variables are containers for storing data values. Data types are the classifications we give to these data. Let’s dive into the basics of variables and data types in JavaScript.
Variables
In JavaScript, you can declare variables using var
, let
, and const
.
var name = 'Junaid'; // declares a variable using var
let age = 28; // declares a variable using let
const pi = 3.14; // declares a constant variable using const
Data Types
JavaScript variables can hold many data types: numbers, strings, objects, and more:
Number
The Number data type is used to represent numeric values. It can be an integer or a floating-point number.
let count = 10; // integer
let price = 9.99; // floating-point number
String
The String data type is used to represent textual data. It is a set of “elements” of 16-bit unsigned integer values.
let greeting = 'Hello, World!';
Boolean
The Boolean data type can hold only two values: true or false. It is typically used to store values like yes (true) or no (false), on (true) or off (false).
let isOnline = true;
Object
The Object data type is used to store collections of data.
let person = {firstName: 'Junaid', lastName: 'Shaikh'};
Undefined
A variable that has not been assigned a value is of type undefined.
let testVar;
console.log(testVar); // Output: undefined
Null
The Null data type has only one value: null. A variable with the value null is considered to be a variable with no value or no object. It is not equivalent to an empty string “” or 0 or undefined, it is simply nothing.
let emptyVar = null;
Understanding variables and data types in JavaScript is fundamental to being able to write JavaScript code. By knowing what data types are available and how to use them, you can write more efficient and effective code.