Skip to main content

Data Types (Primitive vs Reference)

In Javascipt, Data Types can be categorized into 2 groups: Primitive Types and Reference Types.

  • Primitive types like numbers, strings, booleans, etc...
  • Reference types like objects, arrays, functions, etc...

Primitive Types 🎀

numbers, strings, booleans, undefined, null, symbol

  • Primitive types are immutable data types.
  • They hold a single value.

Example

TypeDescriptionExample
NumberRepresents both integer and floating-point numbers.10
StringRepresents a sequence of characters."Hello"
BooleanRepresents a logical value (true or false).true
UndefinedRepresents an uninitialized variable or a function that doesn't return any value.undefined
NullRepresents an intentional absence of any object value.null
SymbolRepresents a unique identifier (added in ECMAScript 6).Symbol('foo')

Behavior

When you declare a variable of a primitive type and assign it a new value, it copies the value directly.

Reference Types 🎀

objects, arrays, functions

  • Reference types are objects(❗️).
  • They hold a reference to their actual value stored in memory.

Qn: Why are arrays, functions, date ... considered as objects?

When I mentioned "objects" in the definition of reference types, I meant it in a broad sense to encompass all non-primitive types.

However, it's more accurate to say that reference types are composed of objects - which can include arrays, functions, dates, and other specialized object types.

In Summary - objects, arrays, functions, date... are all objects (or special types of objects)

  1. Objects: This is a general term referring to any instance of a JavaScript object, including arrays, functions, dates, regular expressions, etc.
  2. Arrays: Specialized objects used for storing multiple values in a single variable, accessed by numerical indices.
  3. Functions: Objects that can be invoked (called) to perform a specific task.
  4. Date: Objects representing date and time values.
  5. RegExp: Objects representing regular expression patterns.

Example

TypeDescriptionExample
ObjectA collection of key-value pairs.{ name: "John", age: 30 }
ArrayA special kind of object used to store a list of elements.[1, 2, 3]
FunctionA callable object.function greet() { /* code */ }
DateRepresents a date and time.const today = new Date();
RegExpRepresents a regular expression pattern.const regex = /\w+/;
Custom ObjectsObjects defined by the programmer.{ /* custom properties/methods */ }

Behavior

  • When you assign a reference type variable to another, you're copying the reference to the same object in memory, not the object itself.
  • Modifying the referenced object will affect all references pointing to it.

Primitive Types Question

QuestionWhat the Tester is TestingSolution / Answer
What are primitive data types in JavaScript? Provide examples.Understanding of basic data types in JavaScript.Primitive data types include numbers, strings, booleans, undefined, null, and symbols. Example: let num = 10;
Explain the difference between null and undefined.Understanding of the distinction between null and undefined.Null represents the intentional absence of any object value, while undefined represents a variable that has been declared but not assigned a value.
What is the difference between == and === operators in JavaScript?Understanding of type coercion and strict equality.== performs type coercion, attempting to convert operands to the same type before comparison. === checks for strict equality without type coercion.
(ie '4'== 4 // returns True but '4'=== 4 returns False)
How are primitive types stored in memory in JavaScript?Knowledge of memory storage for primitive types.Primitive values are stored directly in memory locations, as they are immutable and occupy a fixed amount of memory.
Can you explain what a Symbol is and how it differs from other primitive types?Familiarity with the Symbol data type in ES6.Symbols are unique identifiers introduced in ES6. They are immutable and serve as property keys that are guaranteed to be unique.

Reference Type Questions

QuestionWhat the Tester is TestingSolution / Answer
What are reference types in JavaScript? Provide examples.Understanding of reference types and their examples.Reference types include objects, arrays, functions, etc. Example: let obj = { name: "John" };
Explain the difference between pass by value and pass by reference.Understanding of parameter passing mechanisms.Pass by value involves passing a copy of the value to a function, while pass by reference involves passing the reference to the original value.
How do you create an object in JavaScript?Knowledge of object creation syntax.Objects can be created using object literals {}, constructor functions, or with the new keyword etc.
What is the prototype chain in JavaScript, and how does it relate to reference types? *Understanding of prototypal inheritance in JavaScript.The prototype chain allows objects to inherit properties and methods from their prototype. Objects in JavaScript are linked to a prototype object.
Can you explain the difference between shallow and deep copying of objects? *Understanding of object copying techniques.Shallow copying creates a new object but copies the references to nested objects, while deep copying creates a new object and recursively copies all nested objects.

When do i use Null or Undefined ❓

When to Use null:

  • Explicit Absence of Value:
    • Use null when you want to explicitly indicate that a variable or object property has no value or has been intentionally set to an absence of any object value.
    • For example, if a variable represents a user's middle name, and the user doesn't have a middle name, you can set it to null to indicate the absence of a value.
  • As a Placeholder for Missing Values:
    • Sometimes, null is used as a placeholder value when you expect a value but haven't received it yet.
    • For example, a function may return null if it fails to retrieve data from an external API.

When to Use undefined:

  • Implicit Absence of Value:
    • undefined typically represents the absence of a value due to the variable being declared but not initialized.
    • JavaScript initializes variables to undefined by default, and it's often used to indicate that a value is missing or hasn't been assigned yet.
  • As a Default Return Value:
    • Functions that do not explicitly return a value will return undefined by default.
    • It can be used to indicate that a function does not return any meaningful value.

Pass by Value vs Pass by Reference ❓

Pass by Value:

Definition:

  • In pass by value, a copy of the actual value (primitive data type) is passed to the function.
  • Any changes made to the parameter inside the function do not affect the original value outside the function.

Behavior:

  • Modifying the parameter inside the function does not affect the original variable.
  • Each variable has its own memory space, and changes made to the parameter inside the function only affect that memory space.

Example:

function changeValue(x) {
x = 10; // Modifying the parameter inside the function
console.log(x); // Output: 10
}

let num = 5;
changeValue(num);
console.log(num); // Output: 5 (original value remains unchanged)

Pass by Reference

Definition:

  • In pass by reference, a reference (memory address) to the actual value (object or array) is passed to the function.
  • Any changes made to the parameter inside the function affect the original value outside the function.

Behavior:

  • The parameter inside the function refers to the same memory location as the original variable.
  • Modifying the parameter inside the function affects the original value outside the function.

Example:

function changeArray(arr) {
arr.push(4); // Modifying the parameter inside the function
console.log(arr); // Output: [1, 2, 3, 4]
}

let myArray = [1, 2, 3];
changeArray(myArray);
console.log(myArray); // Output: [1, 2, 3, 4] (original array is modified)

Summary:

  • Pass by value is used for primitive data types, where a copy of the value is passed.
  • Pass by reference is used for objects and arrays, where a reference to the original value is passed.
  • Understanding pass by value and pass by reference is crucial for understanding how functions modify data in programming languages.

How do you create an object in JavaScript ❓

In JavaScript, objects are a fundamental data type used to store collections of key-value pairs. There are multiple ways to create objects:

1. Object Literal: 🎈

You can create an object using object literal notation, which is the most common and simplest way:

// Object literal
const person = {
name: 'John',
age: 30,
city: 'New York',
};

2. Constructor Function: 🎈

You can define a constructor function and then create new instances of the object using the new keyword:

// Constructor function
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}

// Creating an object using the constructor function
const person = new Person('John', 30, 'New York');

3. Object.create() method: 🎈

You can use the Object.create() method to create a new object with a specified prototype:

// Creating an object with a specified prototype
const personPrototype = {
greet: function () {
return 'Hello, my name is ' + this.name;
},
};

const person = Object.create(personPrototype);
person.name = 'John';
person.age = 30;
person.city = 'New York';

4. Class Syntax (ES6): 🎈

With ES6, you can use class syntax to create objects:

// Class syntax
class Person {
constructor(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
}

// Creating an object using the class
const person = new Person('John', 30, 'New York');

Conclusion:

These are the main ways to create objects in JavaScript. Each method has its use cases and advantages, so choose the one that best fits your requirements and coding style. Object literals are simple and concise, constructor functions allow for object instantiation with specific parameters, Object.create() provides control over the object's prototype, and ES6 classes offer a more structured and familiar syntax for defining objects with constructors and methods.