MY JOURNEY LEARNING JAVASCRIPT(Week 2: JavaScript Fundamentals Part 2)
Hi and thank you for stopping by. In this article, I am going to cover functions and arrays in JavaScript. These are really important topics to master so pay attention. Let’s get right into it!
FUNCTIONS
Functions are one of the fundamental building blocks in JavaScript programs. A function is a block of code written to perform a task and can be used over and over again. Write it once and use it a million times. Cool, right? This eliminates the need to write the same piece of code over and over again, allowing developers to write neat and efficient code.
Let's write a function that will print hello world to the console
This is an example of a function that does not take a parameter (input) and doesn’t return anything.
function printHello () {
console.log('Hello, world!');
}
To call/ invoke the function you say:
printHello();
The output of the function will be:
Hello, world!
Function Declarations
Before we can use a function, we need to define it. A function definition/ declaration consists of the function
keyword followed by the unique function name, a list of parameters to the function, and a statement block surrounded by curly braces.
An example of a function declaration:
function birthYear(age){
return 2021 - age;
}
The function birthYear
takes one parameter age
. It has one statement in the code block that instructs the function to return the birth year value found by subtracting the parameter, age
from 2021. The task that this particular function is carrying out is to calculate the birth year. I hope this example can help you better understand what a function is.
The function above can be called/invoked as follows:
birthYear(21);//if you want to log the results of the function:
console.log(birthYear(21));//1999 will be logged on the console
Function Expressions
We can also define a JavaScript function using an expression. This way, we store the function in a variable then re-use the variable. With expressions you write the functions anonymously, there is no need to write the function name.
An example of a function expression using the same function from the first example:
const birthYear = function(age){
return 2021 - age;
}
Take note that in this example, the identifier birthYear
is not the name of the function rather it’s the name of the variable that is storing the function. Remember, function expressions are anonymous.
The big difference between function declarations and function expressions is that a function declaration can be declared after it has been used. This feature is call hoisting.
Let’s take a look at an example of hoisting:
yourName('Minnie'); //invoking a function before its declared//declaring the function
function yourName(name){
console.log(`Your name is ${name}`)
}//The code works and it will output: 'Your name is Minnie'.
Arrow Functions
Arrow functions are function expressions that allow us to write short function syntax. They save developers a lot of time and simplify the function scope.
The structure of arrow functions:
(argument1, argument2,..., argumentN) => {
function body
}
An example of arrow functions in use:
const yourName = name => console.log(`Your name is ${name}`);//you do not need to put parentheses over just one argument hence we don't have parentheses over 'name' in this example
Arrow functions mark the end of our discussion on functions. To better understand, read more on functions, write actual code and run it.
ARRAYS
An array is a data structure(data storage format) or single variable that can store more than one value at a time. It is often used when we want to store a list of elements and access them using one variable. Two important things to note about JavaScript arrays:
- An array can hold values of different types. For example, you can have an array store numbers together with strings and boolean values.
- The length of an array in JavaScript is dynamically sized. This means you do not need to specify the size of the array when declaring it. It is auto-growing, its size is not limited unless you limit it by passing the array size in the Array constructor during declaration.
Declaring
There are two syntaxes for creating an empty array:
let arr = new Array();
let arr = [];
To create an array with elements, you have to pass the elements as a comma-separated list:
let arr = new Array('Minnie', 'Phummy', 'Nandi', 12, 8, 24, true);
let arr = ['techit', true, 21);
You can also create an array with an initial size by passing a number into the array constructor, Array():
let arr = new Array(10);//The array created can only store 10 elements
Array elements can be accessed using their index numbers, and they are numbered starting from 0 — zero-based indexing!
let friends = ['Minnie', 'Tino', 'Vimbai'];console.log(friends[0]); //'Minnie'
console.log(friends[1]); //'Tino'
console.log(friends[2]); //'Vimbai'
We can replace an element:
friends[0] = 'Lisa';console.log(friends); //Now logs [Lisa, Tino, Vimbai] to the console
Array Methods
A JavaScript method is a property containing a function definition. This means that methods can alter arrays. Let’s take a look at the common four methods that alter JavaScript arrays:
Push
- A method used to add an element to the end of an Array
let favoriteColors = ['pink', 'blue', 'red'];
favoriteColors.push('white');console.log(favoriteColors);
//logs ['pink', 'blue', 'red', 'white']
Pop
- A method that extracts an element at the end of an Array and returns it
console.log(favoriteColors.pop()); //removes 'white' and logs it to the console
Shift
- A method that removes an element at the beginning of an Array and returns it
console.log(favoriteColors.shift());
//removes 'pink' and logs it to the consoleconsole.log(favoriteColors);//logs ['blue', 'red']
Unshift
- A method that adds an element at the beginning of an Array
favoriteColors.unshift('orange');console.log(favoriteColors);
//logs ['orange', 'blue', 'red'] to the console
Wow, that was a lot to take in. I hope this article was helpful. Stay tuned for more!