Hi there,
Over the past 3 series of this topic. You have been introduced to core elements in JavaScript's syntax. In this final series, we will be rounding up by looking at Objects and Functions.
Objects in JavaScript
These are generally regarded as a key -> value pair of items. In the previous lesson, where we looked at Arrays. We mentioned that arrays contain inidividual items in a list. Also, that the JavaScript engine, automatically assigns numbers to each item in an array based on their position within the array. i.e. the first item is at position zero (0), second item at position one (1) etc. Those numbers (positions) can be called the keys, while the actual item (in the array) can be called the values.
For Objects, the differences is that the key are not automatically generated by the engine. The developer (who is coding) specifies what the key of an item should be.
Here is the syntax for defining Objects.
let myObject = {key1: "value1", key2: "value2", key3: "value3"}
For instance, let's assume we want to define an Object which describes an employee profile. We can do this.
let employeeObject = {
name: "idris",
position: "software engineer",
level: "intermediate",
employee_number: 1234
}
In the example above, we just defined an object to describe an employee. If we want to access any property from the object we can do that in two ways!
Accessing the values of Objects
For instance, if we want to output the name
of the employee defined above on the console (terminal). we can do this.
let employeeObject = {
name: "idris",
position: "software engineer",
level: "intermediate",
employee_number: 1234
}
console.log(employeeObject.name) // "idris"
Or we could do this
let employeeObject = {
name: "idris",
position: "software engineer",
level: "intermediate",
employee_number: 1234
}
console.log(employeeObject["name"]) // "idris"
Using any of the two methods above, we can access any value by using the key!
In the examples above, name
is the key, "idris"
is the value!
We can also perform a number of other operations on an Object.
Adding Items to an existing Object
Using the previous example, if we wanted to added a new key called year_of_employment
with a value "12-3-2021"
. Here is how to do that.
let employeeObject = {
name: "idris",
position: "software engineer",
level: "intermediate",
employee_number: 1234
}
//adding year of employement
employeeObject["year_of_employment"] = "12-3-2021"
console.log(employeeObject)
// {
name: "idris",
position: "software engineer",
level: "intermediate",
employee_number: 1234,
year_of_employment: "12-3-2021"
}
The employeeObject now has the new key and value we have added as seen above.
Replacing / Removing Items in an existing Object To replace the value of items, you can reassign the key a new value, similar to the way we added a new key -> value pair above. But in this case you be using an existing key.
example: (changing the name of the employee)
let employeeObject = {
name: "idris",
position: "software engineer",
level: "intermediate",
employee_number: 1234
}
//replacing name
employeeObject["name"] = "David"
console.log(employeeObject)
// {
name: "David",
position: "software engineer",
level: "intermediate",
employee_number: 1234,
year_of_employment: "12-3-2021"
}
To remove an item from the object, you need to use the delete
keyword.
example: (removing the employee_number
)
let employeeObject = {
name: "idris",
position: "software engineer",
level: "intermediate",
employee_number: 1234
}
//deleting employee_number
delete employeeObject.employee_number
console.log(employeeObject)
// {
name: "idris",
position: "software engineer",
level: "intermediate",
year_of_employment: "12-3-2021"
}
The key and value of the employee_number has been deleted.
Checking for existence of key JavaScript also provides a number of methods to manipulate objects. There is the Object.hasOwnProperty() which is used to check the presence of a key within an Object.
example:
let myObj = {first: "egg", second: "yam", third: "rice"}
// checking for the presence of third
myObj.hasOwnProperty("third") // true
myObj.hasOwnProperty("fourth") // false
Functions
Functions are piece of code 'grouped' together to perform a single action. The primary intention of defining functions is to be able to re-use the same block of code for similar actions.
The syntax for function is:
function nameOfFunction() {
// do something
}
For example: if we want to determine average of two numbers using a function
function averageCalculator() {
let firstNumber = 12
let secondNumber = 14
let result = (firstNumber + secondNumber) / 2
return result
}
In the function above we have a function called averageCalculator
basically calculates the average of two numbers (firstNumber
, secondNumber
) and returns the result. The return
keyword sends back the result of what the function calculates.
Calling the function After defining our function above, in other to actual make it work, we need to call it! Here is how to call a function.
Using the previous example:
//defining the function
function averageCalculator() {
let firstNumber = 12
let secondNumber = 14
let average = (firstNumber + secondNumber) / 2
return average
}
//calling the function
let result = averageCalculator()
//outputting the result to console
console.log(result) // 18
In the function above averageCalculator()
will always return 18 as the result. What if we want to calculate average for another set of numbers?
In the case above, our function can only calculate the average number that is defined within the function. So, how can we re-use this function to calculate the average of other numbers? A good way to do that is to make use of arguments!
Function Arguments
Using the previous example, the averageCalculator()
can be better utilized by allowing the use of arguments, which will allow for us to be able to pass in the number we want it to calculate.
The syntax for functions with arguments is:
function nameOfFunction(argument1, argument2) {
//some code to do stuff goes here
}
Hence, we will change the structure of the averageCalculator
, like this:
function averageCalculator(firstNumber, secondNumber) {
let result = (firstNumber + secondNumber) / 2
return result
}
Now, in the new change, the firstNumber
and secondNumber
are no longer variables defined within the function, they are now arguments.
So when we want to call the function, we will have to pass in the arguments it will use to calculate average.
example:
function averageCalculator(firstNumber, secondNumber) {
let result = (firstNumber + secondNumber) / 2
return result
}
//calling the function with arguments
let result = averageCalculator (2,4)
console.log(result) // 3
//calling the same function but with different arguments
let result2 = averageCalculator(10, 12)
console.log(result2) // 11
Hence, we now have a re-usable function! That can give new results based on what new arguments we pass into it!
Oh wow! We've covered quite a bit!
A Quick Recap
We looked at Objects and how the help us hold special kinds of data, known as key, value pairs. Then we looked at functions and how they can be used to help us make our code more re-usable.