Functions
This lesson covers the fundamentals of Functions in JavaScript.
We'll cover the following...
Functions are a very important tool we use to perform tasks and calculations of all kinds.
In JavaScript, we can declare a function in different ways.
Let’s have a look at a function definition:
function greet(name){console.log("hello " + name);}greet("Alberto")// hello Alberto
This is a simple function that when called will log a string.
The variable inside the parenthesis at line 1, is called a parameter while the code inside of the curly brackets is a statement, in this case a very simple console.log().
A very important thing to remember is that primitives are passed to a function by value, meaning that the changes done to those values are not reflected globally. On the other hand, if the value is not a primitive, such as an Object or an Array, it is then passed by reference, meaning that any modification done to it will be reflected in the original Object.
let myInt = 1;function increase(value){return value +=1;}console.log(myInt);// 1console.log(increase(myInt));// 2console.log(myInt);// 1
As you can see, we increased the value of the integer, but that didn’t affect the original variable. Let’s look at an example with an Object.
let myCar = {make: "bmw",color: "red"}console.log(myCar)// {make: "bmw", color: "red"}function changeColor(car){car.color = "blue"}changeColor(myCar)console.log(myCar)// {make: "bmw", color: "blue"}
As you can see, since the parameter car was just a reference to the Object myCar, modifying it resulted in a change in the myCar Object.
Another way of declaring a function is by using a function expression.
const greeter = function greet(name){console.log("hello " + name);}greeter("Alberto")// hello Alberto
Here we assigned our function greet to a const, called greeter.
We got the same result as in ...