Functions

Objects

Object literals and the dot notation

One of the most common ways of building an object in JavaScript is using the object literal syntax: {}.

To be able to access this object literal, it is very common to assign it to a variable, such as:

var user = {}; //create an object

Now an object literal is assigned to the variable user, which means that the object it is bound to can be extended and manipulated in a myriad of ways.

Sometimes, an entire object can be immediately built, using the object literal syntax, by specifying the object’s properties, delimited as key-value pairs, using syntax that was already covered in an earlier lesson item in this lesson.

var assistantManager = {
	rangeTilesPerTurn: 3,
	socialSkills: 30,
	streetSmarts: 30,
	health: 40,
	specialAbility: "young and ambitious",
	greeting: "Let's make some money"
}

It essentially consists of two steps:

  1. Declaring a new variable and assigning an object literal to it - in other words, this: var assistantManager = {} 

  2. Assigning the values to each of the object’s keys, using the assignment operator, =

Notice that it’s very easy to build any kind of an object in JavaScript using this example syntax.

For example, here’s a table object:

var table = {
	legs: 3,
	color: "brown",
	priceUSD: 100,
}

An alternative approach of building objects is to first save an empty object literal to a variable, then use the dot notation to declare new properties on the fly, and use the assignment operator to add values to those properties; for example:

var house2 = {};
house2.rooms = 4;
house2.color = "pink";
house2.priceUSD = 12345;

Additionally, nothing is preventing me from combining the two approaches. For example:

console.log(house); // {rooms: 3, color: "brown", priceUSD: 10000}
house.windows = 10;
console.log(house); // {rooms: 3, color: "brown", priceUSD: 10000, windows: 10}

This flexbility additionally means that I can update already existing properties, not just add new ones:

house.windows = 11;
console.log(house); // {rooms: 3, color: "brown", priceUSD: 10000, windows: 11}

Object Literals and the Brackets Notation

There is an alternative syntax to the dot notation I used up until this point.

This alternative syntax is known as the brackets notation.

var house2 = {};
house2["rooms"] = 4;
house2['color']= "pink";
house2["priceUSD"] = 12345;
console.log(house2); // {rooms: 4, color: 'pink', priceUSD: 12345}

I can both access and update properties on objects using either the dot notation, or the brackets notation, or a combination of both, like in the following example:

var car = {};
car.color = "red";
car["color"] = "green";
car["speed"] = 200;
car.speed = 100;
console.log(car); // {color: "green", speed: 100}

With the brackets notation, I can add space characters inside property names, like this:

car["number of doors"] = 4;
console.log(car); // {color: 'green', speed: 100, number of doors: 4}

Additionally, I can add numbers (as the string data type) as property keys:

car["2022"] = 1901;
console.log(car); // {2022: 1901, color: 'green', speed: 100, number of doors: 4}

Finally, there’s one really useful thing that bracket notation has but is not available in the dot notation: It can evaluate expressions.

var arrOfKeys = ['speed', 'altitude', 'color'];
var drone = {
	speed: 100,
	altitude: 200,
	color: "red"
}

for (var i = 0; i < arrOfKeys.length; i++) {
	console.log(drone[arrOfKeys[i]])
}

Using the fact that brackets notation can evaluate expressions, I accessed the arrOfKeys[i] property on the drone object.

This value changed on each loop while the for loop was running.

Specifically, the first time it ran, it was evaluated like this:

  • The value of i was 0 

  • The value of arrOfKeys[i] was arrOfKeys[0], which was ”speed“ 

  • Thus, drone[arrOfKeys[i]] was evaluated to drone["speed"] which is equal to 100

This allowed me to loop over each of the values stored inside the drone object, based on each of its properties’ keys.

Arrays are Objects

In JavaScript, arrays are objects. That means that arrays also have some built-in properties and methods.

One of the most commonly used built-in methods on arrays are the push() and the pop() methods.

To add new items to an array, I can use the push() method:

var fruits = [];
fruits.push("apple"); // ['apple']
fruits.push('pear'); // ['apple', 'pear']

To remove the last item from an array, I can use the pop() method:

fruits.pop();
console.log(fruits); // ['apple']

Math object cheat sheet

JavaScript has handy built-in objects. One of these popular built-in objects is the Math object.

Number constants

Here are some of the built-in number constants that exist on the Math object:

  • The PI number: Math.PI which is approximately 3.14159
  • The Euler’s constant: Math.E which is approximately 2.718
  • The natural logarithm of 2: Math.LN2 which is approximately 0.693

    Rounding methods

    These include:

  •  Math.ceil() - rounds up to the closest integer
  •  Math.floor() - rounds down to the closest integer
  •  Math.round() - rounds up to the closest integer if the decimal is .5 or above; otherwise, rounds down to the closest integer
  •  Math.trunc() - trims the decimal, leaving only the integer

    Arithmetic and calculus methods

    Here is a non-conclusive list of some common arithmetic and calculus methods that exist on the Math object:

  • Math.pow(2,3) - calculates the number 2 to the power of 3, the result is 8 
  • Math.sqrt(16) - calculates the square root of 16, the result is 4 
  • Math.cbrt(8) - finds the cube root of 8, the result is 2 
  • Math.abs(-10) - returns the absolute value, the result is 10 
  • Logarithmic methods: Math.log(), Math.log2(), Math.log10() 
  • Return the minimum and maximum values of all the inputs: Math.min(9,8,7) returns 7, Math.max(9,8,7) returns 9.
  • Trigonometric methods: Math.sin(), Math.cos(), Math.tan(), etc.

Object Methods

As you might already know, an object consists of key-value pairs, known as properties.

We can add new key-value pairs to existing objects using the dot notation and the assignment operator.

var car = {};
car.color = "red"; //update the value of a property of the car objject

These are known as properties, and can take many data types, including functions.

var car = {};
car.color = "red";

//add a method to the car object so that it can be called as car.turnkey()
car.turnKey = function() {
	console.log('engine running');
}

If the function is a property of an object, it is then referred to as a method.

This is a function that can be accessed only through the JavaScript object that it is a member of. For example, the log method, which belongs to the console object, can only be accessed through the console object.

console.log('Hello world');

Let’s explore this further now. I will create an object using something known as the constructor function.

//example of adding properties and methods to an object
var car = {};
car.mileage = 98765;
car.color = "red";
console.log(car);
car.turnTheKey = function() {
	console.log("The engine is running")
}
car.lightsOn = function() {
	console.log("The lights are on.")
}

console.log(car);
car.turnTheKey();
car.lightsOn()

What’s unique is that the value I’m assigning to it is a function.

Additional resources

Here is a list of resources that may be helpful as you continue your learning journey.

JavaScript Functions

JavaScript Object Basics

typeof operator in JavaScript

Arrays are “list-like objects”


© 2024. knznsmn. All rights reserved.