JavaScript is a popular programming language with various data types essential for writing good code. Knowing these data types is important, especially for technical interviews. In this blog post, we will look at common interview questions about JavaScript data types and provide examples to help you understand them better.
What Are the Different Data Types in JavaScript?
JavaScript has many data types, which can be divided into two main categories: primitive and non-primitive types.
Primitive Data Types:
- Number: Represents both integer and floating-point numbers.
- String: Represents sequences of characters.
- Boolean: Represents
true
orfalse
. - Null: Represents the intentional absence of any object value.
- Undefined: Represents an uninitialized variable.
- Symbol: Represents a unique identifier.
- BigInt: Represents large integers beyond the range of
Number
.
let myString = "Hello, Javascript!"; // string
let myNumber = 1983; // number
let myBoolean = true; // boolean
let myNull = null; // null
let myUndefined = undefined; // undefined
let mySymbol = Symbol("mySymbol"); // symbol
let myBigInt = 123456789n; // bigint
Non-Primitive Data Types:
- Object: Represents collections of data and more complex entities.
How Do You Check the Type of a Variable in JavaScript?
In JavaScript, typeof the operator is used to find out the data type of a value. It returns a string that indicates the type of the given value.
let num = 42;
console.log(typeof num); // "number"
let str = "Hello";
console.log(typeof str); // "string"
let isTrue = true;
console.log(typeof isTrue); // "boolean"
let obj = {};
console.log(typeof obj); // "object"
What Is the Difference Between null and undefined?
- Null: An assignment value, used to represent no value. It represents “nothing”, “empty”, or “unknown value”.
- Undefined: A variable that has been declared but has not been assigned a value.
let x = null;
console.log(x); // null
let y;
console.log(y); // undefined
What Is the Difference Between ==
and ===
in JavaScript?
- ==(Equality Operator): The double equals operator performs a type conversion before comparing the two values.
- ===(Strict Equality Operator): The triple equals operator, on the other hand, does not perform a type conversion.
console.log(5 == '5'); // true
console.log(5 === '5'); // false
In the first console.log
statement, the ==
operator converts the string “5” to a number before comparing, making it true. In the second statement, the ===
operator doesn’t convert, resulting in false.
0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
NaN == NaN or NaN === NaN // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
What Is the Symbol Data Type in JavaScript?
The JavaScript Symbol is a primitive data type, similar to Number, String, and Boolean and used to create unique identifiers for object properties.
- Symbols are created using the
Symbol()
function, and each symbol is unique. - Symbols allow you to create object properties that are hidden from
for...in
loops. - Once created, symbols cannot be changed.
- Symbols can be used as keys for object properties, but not for arrays.Symbols are not shown when you use a
for...in
loop to go through an object’s properties.
const mySymbol = Symbol();
// Create an object with a symbol property
const myObject = {
[mySymbol]: "This is a hidden property"
};
// Access the symbol property
console.log(myObject[mySymbol]); // "This is a hidden property"
// Iterate over the object
for (const key in myObject) {
console.log(key); // "mySymbol" will not be logged
}
//---------------
JSON.stringify({ [Symbol("foo")]: "foo" });
// '{}'
const mySymbol = Symbol();
// Create an object with a symbol property
const myObject = {
[mySymbol]: "This is a hidden property"
};
// Access the symbol property
console.log(myObject[mySymbol]); // "This is a hidden property"
// Iterate over the object
for (const key in myObject) {
console.log(key); // "mySymbol" will not be logged
}
//---------------
JSON.stringify({ [Symbol("foo")]: "foo" });
// '{}'
//----------
const person = {
firstName: "Mind",
lastName: "Hub",
};
let id = Symbol('id');
person[id] = 143;
console.log(person[id])//143
console.log(person.id)//undefined
How Do You Create a BigInt in JavaScript?
BigInt values are a new data type in JavaScript that was introduced in ES2020. To create a BigInt in JavaScript, you can append lowercase ‘n‘ to the end of an integer.
const bigInt = 12345678901234567890n;
You can also create a BigInt value by calling the BigInt() function. The BigInt() function takes an integer or numeric string value as its argument and returns a BigInt value
const bigInt = BigInt('12345678901234567890');
BigInts are used in applications that handle large numbers, such as: Financial calculations, Cryptography and security computing, Scientific computing, and Working with large datasets.
Explain the Difference Between Primitive and Non-Primitive Data Types in JavaScript.
Primitive data types are immutable, meaning their values cannot be changed once assigned. Non-primitive data types are mutable and can be modified.
let x = 5;//Primitive Data Type
x = 10; // This creates a new value for x, it doesn't modify the original value.
let arr = [1, 2, 3]; //Non-Primitive Data Type
arr.push(4); // This modifies the array by adding a new element to it.
Primitive data types are stored directly in memory, whereas non-primitive data types are stored as references to their values in memory.
Primitive data types are compared by value, while non-primitive data types are compared by reference.
Feature | Primitive | Non-Primitive |
---|---|---|
Mutability | Immutable(values cannot be changed) | Mutable(value can be modified) |
Storage | Stored directly in memory | Stored as references to their values in memory |
Comparison | Compared by value | Compared by reference |
Examples | Numbers, strings, booleans, undefined, null, symbol | Objects, arrays, functions |
What is difference in Single quotes (‘), Double quotes (“), and Backticks?
The first two types of quotes are the most common and are used in the same way. The only difference between them is that single quotes are used more often for short strings, while double quotes are used more often for long strings.
Backticks: Backticks, also known as template literals, are a feature introduced in ECMAScript 6 (ES6). They allow for embedding expressions into strings, making string interpolation easier.
// Single quotes
const name = 'Mind Share Hub';
// Double quotes
const age = "30";
// Backticks
const greeting = `Hello, ${name}! You are ${age} years old.`;