PRIMITIVE VALUES AND OBJECTS

JS

In javascript there are several types of values that are divided into primitives and objects.

Tipi di dato


Definition:
An object is a data structure that allows the storage of a set of information. We will look at primitive data one by one. Let’s go to Visual Studio Code.

Console
Copy to Clipboard

JAVASCRIPT OBJECTS

NB: This is only an overview. We will delve into the discussion of javascript objects in later posts.

In JavaScript there are eight types of data. Seven of them are called “primitives” because their values always contain a single element (a string, number, boolean etc.). Objects, on the other hand, are used to catalog various types of data and other more complex items. In JavaScript, they permeate every aspect of the language. Therefore, we must understand them well before proceeding to the in-depth study of any other topic.

JAVASCRIPT OBJECTS, THE CREATION OF AN OBJECT

An object can be created using curly brackets {…}, with an optional list of properties. A property is a “key: value” pair, where “key” is a string (also called “property name”), while “value” can be anything. We can imagine an object as an archive with cataloged documents. Each piece of data is stored using a specific key. It is easy to find a document when you know its name, or to add new ones or remove old ones.

SYNTAX FOR CREATING OBJECTS

An empty object can be created using either syntax:

let user = new Object(); // “object constructor” syntax

let user = {}; // “literal object” syntax

object-user-empty

THE PROPERTIES OF LITERALS

We can immediately put properties in {…} such as a “key: value” pair:

let user = { // an object

name: “John“, // a “name” key stores the value “John”

age:30       // an “age” key stores 30

};

One property has a key (also known as “name” o “identifier“) before the colon “:”, and a value to its right. There are two properties in the user object:

  1. The first property has “name” as its name and “John” as its value.
  2. The second one has “age” as its name and 30 as its value.
object-user

We can add, remove, or read a value at any time. Property values are accessed using dotted notation:

// returns the fields of the object:

alert( user.name ); // John

alert( user.age ); // 30

The value can be of any kind. Let’s add a boolean:

user.isAdmin = true;

object-user-isadmin

REMOVAL OF A PROPERTY

To remove a property, we can use the delete operator:

delete user.age;

We can also use property names composed of multiple words (“multi-word”), but they must be enclosed in quotation marks:

let user = {name: “John“,

age:30,

likes birds“: true // a property name consisting of multiple words must be enclosed in quotation marks

};

The last property in the list can end with a comma

let user = {

name: “John“,

age: 30,

}

It makes it easier to add/remove/move properties because all rows have a comma.

BRACKETS

For properties with “multi-word” names, access with dotted notation does not work, This is because the point requires the following key to be a valid identifier. An identifier must have no spaces (in addition to following the other limitations already studied). To get around this constraint there is a “notation with square brackets.”

let user ={};

// set

user[“likes birds“] = true;

// get

alert(user[“likes birds“]); // true

// delete

delete user[“likes birds“];

Now it works. Note that the string inside the parentheses should still be put in quotation marks (single or double). In real life, a car is an object. A car has properties such as weight and color and methods such as start and stop:

car

All cars have the same properties, but property values differ from car to car. All cars have the same methods, but the methods are performed at different times. You have already learned that JavaScript variables are pointers to values. This code assigns a simple value (fiat) to a variable named car:

let car = “Fiat“;

Objects are also variable. But objects can contain many values. This code assigns many values (Fiat, 500, white) to a variable named car:

const car = {type:”Fiat“, model:”500“, color:”white “};

Values are written as name:value pairs (name and value separated by a colon). It is common practice to declare objects with the keyword
const
.

DEFINITION OF LITERAL OBJECT

You define (and create) a JavaScript object literal:

const person = {firstName:”John“, lastName:”Doe“, age:50, eyeColor:”blue“};

Spaces and line breaks are not important. An object definition can span multiple lines:

const person = {
firstName:”John“,
lastName:”Doe“,
age:50,
eyeColor:”blue
};

PROPERTIES OF OBJECTS

Name:value pairs in JavaScript objects are called properties:

ACCESS THE PROPERTIES OF AN OBJECT

The properties of the object can be accessed in two ways:

  1. objectName.propertyName
  2. objectName[“propertyName”]

JavaScript objects are containers for values called properties.

METHODS OF AN OBJECT

Objects can have methods. Methods are actions that can be performed on objects. They are stored in properties as function definitions.

Methods

A method is a function stored as a property.

const person = {firstName: “John“,
lastName: “Doe“,
id :5566,
fullName: function() {
    return this.firstName + ” ” + this.lastName;
  }
};

In the example above, this refers to the person object, this.firstName indicates the firstName property of person, this.lastName indicates the lastName property of person.

THE KEYWORD THIS

In JavaScript, the this keyword refers to an object. Which object depends on how it is invoked (used or called). The keyword this refers to different objects depending on how it is used:

this

In the example above, this is the person object that “owns” the fullName function.

ACCESS THE METHODS OF THE OBJECT

An object method is accessed with the following syntax:

objectName.methodName()

name = person.fullName();

If you access a method without the parentheses (), it will return the function definition:

name = person.fullName;

DEEPENING AI

In JavaScript, primitive values and objects are the two main types of data. Although they have different properties and behaviors, together they form the basis of data manipulation in this language.

Primitive Values

Primitive values are immutable (non-changeable) data types and are handled more easily than objects. In JavaScript, there are 7 primitive types:

1. String: represents a sequence of characters.

-Example: ‘hello’, “world”.

2. Number: represents both integer and floating-point numbers.

-Example: 42, 3.14.

3. Boolean: represents a logical value, which can be true or false.

-Example: true, false.

4. Undefined: represents the absence of a value. A variable that is declared but not initialized automatically has the value undefined.

-Example: let x; (the value of x will be undefined).

5. Null: represents the intentional absence of an object or value.

-Example: let x = null; (here, x is explicitly set to null).

6. Symbol: represents a unique, immutable value, introduced in ES6. It is mainly used as a unique identifier for object properties.

– Example: let sym = Symbol(‘description’);.

7. BigInt: represents integers larger than Number.MAX_SAFE_INTEGER (i.e., 2^53 – 1), introduced in ES11.

– Example: let big = 123456789012345678901234567890n;.

Characteristics of Primitive Values.

-Immutable: once a primitive value is created, it cannot be changed. If it appears that a primitive is being “modified,” a new value is actually being created.

-Comparison by value: when comparing two primitive values, you are comparing their actual values. For example, 42 == 42 returns true.

-Pass by value: when passing a primitive to a function, the value of the primitive is passed, not the reference. This means that a copy of the value is passed, not the original.

Objects

Objects in JavaScript are dynamic collections of properties. A property is a key-value pair, where the key is a string (or Symbol) and the value can be of any type (including other objects or functions). Objects can be viewed as complex containers of data and behavior.

Examples of objects include:

1. Standard objects: created directly with the literal notation {} or with new Object().

-Example:

let person = {
      name: ‘John‘,
      age: 30,
      greet: function() {
         console.log(‘Hello!‘);
      }
};

2. Array: In JavaScript, arrays are special objects that allow you to store multiple values in a single variable.

– Example: let arr = [1, 2, 3];.

3. Functions: in JavaScript, functions are treated as first-class objects. They can be assigned to variables, passed as arguments, and returned by other functions.

-Example:

function greet() {
     returnHello!‘;
}

4. Dates: the Date class represents dates and times.

– Example: let now = new Date();.

5. Custom objects: user-defined using constructor functions or ES6 classes.

-Example:

class Car {
     constructor(make, model) {
        this.make = make;
        this.model = model;
     }
}
let myCar = new Car(‘Toyota‘, ‘Corolla‘);

Characteristics of Objects.

-Mutable: unlike primitives, objects are mutable. This means that the properties of an object can be changed even after the object has been created.

-Example:

let person = { name: ‘John‘, age: 30 };
person.age = 31; // Modifica della proprietà age

Comparison by reference: when comparing two objects, you are not comparing their values, but their in-memory references. Even if two objects have the same properties and values, they are considered different if they do not share the same reference.

-Example:

let obj1 = { a: 1 };
let obj2 = { a: 1 };
console.log(obj1 === obj2); // false

-Pass by reference: when passing an object to a function, the reference to the object is passed, not a copy. This means that any changes to the object inside the function will take effect outside.

-Example:

let obj = { value: 10 };
function modify(o) {
o.value = 20;
}
modify(obj);
console.log(obj.value); // 20

Differences between Primitive Values and Objects

1. Mutability:

-Primitive values are immutable.

-Objects are mutable.

2. Comparison:

-Primitive values are compared by value.

-Objects are compared by reference.

3. Passing in parameters:

-Primitive values are passed in by value.

-Objects are passed by reference.

4. Memory:

-Primitives are stored directly in stack memory.

-Objects are stored in heap memory and their reference is in the stack.

Conversion between Primitives and Objects.

In JavaScript, primitives can be temporarily converted to objects when their properties or methods are accessed. This is done automatically through wrapping (encapsulation) in wrapper objects such as String, Number, or Boolean.

let str = ‘hello‘;
console.log(str.length); // 5

Summary

-Primitive values are simple, immutable data types such as numbers, strings, Booleans, etc.

-Objects are complex, mutable, dynamic data structures that can contain other variables (including primitives or other objects).

-Objects are treated by reference, while primitives are treated by value.

These concepts are fundamental to understanding the inner workings of JavaScript and to writing effective and efficient code.

LINKS TO PREVIOUS POSTS

THE JAVASCRIPT LANGUAGE

LINK TO CODE ON GITHUB

GITHUB