Javascript Bootcamp | Basics | Part 5–9

Mastering the Basics

Angel Mondragon
10 min readApr 2, 2021

Intro

I still need to edit the videos, however, these are supplementing the articles. I already prerecorded the whole series and expanded various parts into multiple videos. I hope to get you prepped as I finish writing our advanced App Tutorial. Now that we understand types we are going to create functions that are like the action or behavior of the noun (object).

Methods & Functions

Function Expression vs Declarations

In the previous part of this section, we talked about the various ways to write a function and the various ways functions can be created.

First, let's talk about function expression. This is where the function is created but not declared the difference between declared functions and expression is the assignment to a variable usually using the const declaration. Here is a function expression:

const anon = function() {  return 1995; }// Or es6const anon = () => { return 1995; }

These are some function declarations:

function funName() { return 1995; }
// Or
(function() { return 1995; } ())
// or es6
(() => { return 1995; } )

Function expressions are can be remembered in terms of math. an expression usually has an equals sign and in our instance is when we name the function. Whereas, function declarations are declared without being assigned a variable.

The unique difference between the two other than assigning the return value to a variable in expressions is found in something called hoisting.

You don't need to worry about hoisting too much instead ill give an example to demonstrate the differences between the two. We will start with an expression:

alert(foo()); // returns Uncaught TypeError: foo is not a function
var foo = function() { return bar; }

The function was called before it was loaded and when a function expression is created it need to be initialized before it can be called.

Here is the declaration, notice the difference:

alert(foo()); // returns 'bar'. Declarations are loaded before any code can run.
function foo() { return 'bar'; }

Good coding practice is to import or initialize functions prior to being called anyway, but those are the differences: storing values in variables and hoisting distinctions.

Functions

As mentioned above, we talked about the various ways to write functions in the previous part, so I will list those again here to give you an example of the syntax.

function funName() {}// function named funName. to initiate we use funName(). Can take in arguments.(function() {} ())// anon function automatically initated after the {} with the (). Can take in arguments.const anon = function() {}//anon function assigned to the constant variable anon. Can take in arguments. initiated by anon()
//ES6 Syntax:
const anon = () => {}
// naming and anon function(() => {} )// anon funciton. You will see me use this often in the future.

Let’s take the function declaration syntax and create an example:

function text() {
console.log('Hello World')
}text() // returns and logs 'Hello World'

Parameters & Arguments

You see that we declare the function and inside the block (curly brackets) we add our statements, or do something and return some value. What if we wanted to change the string inside the console log? Well, we can do this one of two ways. The inefficient way is to create one function for each string of text you wish to use, but that isn't dynamic with the users’ input. So, to workout around that problem, we can start to use parameters and arguments.

Let's take the previous function and use that as an example:

function hello(text) {
console.log('text')
}hello('Hello World') // returns and logs 'Hello World'

Now we can break down what happening here. Also, parameters and arguments are essentially the same things so you might hear others use them interchangeably. Don't freak out, they both mean & serve the same purpose.

// text is a parameter that takes the arguements from the function // being called. text is essentially a variable that stores the    // arguement. function hello(text) { 
console.log(text)
}// In this instance our argument is 'hello world' and that is stored // as the text parameter as a variable that can be used within the // function. hello('Hello World') // returns and logs 'Hello World'

Now, function do not need parameters or arguments, and the parameters can be named anything from ‘t’ to ‘zebra’ instead of ‘text’. All it does is act as the placeholder that stores the argument value to be used within the function. I just use text because it makes sense to me and others who view the code to know what that parameter represents and should be as an argument.

Functions can have multiple arguments too. Check this out:

function add(a,b) {
return a + b
}hello(5,8) // returns 13

You can have multiple parameters and even take objects or other functions as arguments. We are going to cover functions or callbacks as arguments below, but here is an example of passing objects as an argument.

function newFunc(number,obj,text) {
alert(number);
alert(obj.foo);
alert(obj.bar);
alert(text);
}

newFunc(5, {foo: "This", bar: "works!"}, 'testing Text');

We will explore the object literal later but I just wanted to show you that object as a whole is passed in as a literal and we navigate the object with dot notation to get the specific value of the key pair. The other two parameters are being accepted like they were normally in the previous examples.

The caveat to parameters and arguments is that the arguments when the function is called need to respect the order of the parameters. In other words, we can switch the order of our arguments because the function will assume the incoming arguments are aligning with the set parameters. Heres an example.

function newFunc(number,obj,text) {
alert(number);
alert(obj.foo);
alert(obj.bar);
alert(text);
}

newFunc({foo: "This", bar: "works!"}, 5, 'testing Text');

We placed the object first where the number should be and we would get an error. there is no obj.foo because instead of placing an argument in that parameter we placed a number. So argument placement matters and needs to respect the order of the functions set parameters.

Fat Arrow Functions are the new ES6 syntax for js. You will be seeing this more often and it looks all-around cleaner IMO.

//ES6 Syntax Function Expression: 
const anon = () => {}
//ES6 Syntax anon Function:
(() => {} )

We will explore the differences of es6 functions with the this keyword soon. Keeping with params and arguments, however, I'll show you some examples of single or multiple params using fat arrows.

If we are using no params we need the parenthesis.

const anon = () => { console.log('Hello World') }

If we are returning a single line of code then we can reduce it to this.

const anon = () => console.log('Hello World')

If we are returning a single line of code with a single param we can remove the parenthesis.

const anon = text => console.log(text)

look how clean!!!!!

If we are returning a single line of code with multiple params we need to use the parenthesis.

const anon = (a, b) => console.log(a,b)

We talked about the return key value in the previous part of this section. However, I wanted to talk about return multiple lines of values.

const anon = (a, b) => {
// do somethng
return (
// multiple lines of values
)
}

I just quickly wanted to highlight this use case of return before we moved on because we will be seeing this version of return more often in the subsequent sections.

Nested Statement Scope

We had briefly introduced the concept of scope in previous parts of this section, particularly with the declaration. There are three types of scope we should get acquainted with.

  • Global: upon writing code, anything written initially is inside the global scope automatically. if it is in the global scope it is accessible through the code.
  • Local: this is referencing blocks or {} . When you create if ,while , etc, or functions you are creating a new block thus a new local scope.
  • Lexical: Similar to the local scope, the lexical scope involves blocks within blocks ie. functions in functions for example.

You cannot access local variables globally the same you can with global variables, hence the keyword global.

Here is an example of a global scope being used locally and globally:

//GLOBAL SCOPE
var hero = 'Deku';
const heroName = () => {
// LOCAL SCOPE
console.log(hero); // Deku
}
// GLOBAL SCOPE
console.log(hero); // Jerry

Here is an example of a local scope being used locally and globally:

const heroName = () => {
// LOCAL SCOPE
var hero = 'Deku';
console.log(hero); // Deku
}
// GLOBAL SCOPE
console.log(hero); // Uncaught ReferenceError: hero is not defined

You notice since the hero variable is declared inside the local scope we cannot access it outside of that scope, but we can access global variables inside local and lexical scopes. Here is the same concept but with lexical scope.

// GLOBAL SCOPE
var heroTwo = 'Bakugo';
const heroName = () => {
// SCOPE 1
var heroOne = 'Deku';
const heroNameTwo = () => {
// SCOPE 2
console.log(heroOne); // Deku
console.log(heroTwo); // Bakugo
}
}

Back to var ,let, and const . let and const are constrained by the local or lexical scope. Whereas var is is function scoped.

// GLOBAL SCOPE
var heroTwo = 'Bakugo';
const heroName = () => { // SCOPE 1
var heroOne = 'Deku';
{ // SCOPE 2
var heroOne = 'Bakugo';
let heroThee = 'All Might';
const heroFour = 'Endevour';
} console.log(heroOne); // 'Deku' within the same scope
console.log(heroTwo); // 'Bakugo' Function scoped
console.log(heroThree); // Error: not accesable
console.log(heroFour); // Error: not accesable

}

We will explore this concept in greater detail later in OOPs. Particularly reassigning variables from various scopes.

Call Back Fn

We briefly covered this above, discussing taking in functions as arguments within the parameters of a function. Call back functions are a great way to move around objects and values across scopes and, in react, components.

Here is how they work:

function foo(x) {
alert(x);
}
function bar(func) {
func("Hello World!");
}

//alerts "Hello World!"
bar(foo);

We created the bar functions which takes a function as an argument. We created the foo function which is passed as an argument in the bar function.

A more common was to view this is by using anonymous functions like so:

function foo(x) {
alert(x);
}
function bar(func) {
func();
}

//alerts "Hello World!" (from within bar AFTER being passed)
bar( () => foo("Hello World!") );

the same concept as above however we are passing hello world as an argument within the function foo that's an argument for the function bar. Argument-ception, I know.

That's it for now, there is a more advanced way to execute callbacks using the mysterious this keyword once again. I’ll drop a teaser example but we will continue the discussion and break down in greater detail later.

function funcTwo(power1, power2) {
alert("My superpowers are " + power1 + " and " + power2 );
}
function funcOne(yourCallbackFunc, args) {
//do stuff
//...
//execute callback when finished
yourCallbackFunc.apply(this, args);
}

//alerts "My superpowers are super speed and super strength"
myFunc(funcTwo, ["super speed", "super strength"]);

Once again the order of arguments relative to its parameters matters here.

More info on callbacks here.

Methods

Lastly, we have methods. Methods are essentially functioned nested within a function. So the only real difference is where they are located, how they are defined, and how they are used.

This is something we are going to cover next in OOPs but for now, I wanted to introduce you to the conception of methods. to call methods you need to use the do notation. Before we create our own methods lets see how to use one first.

var message = "Hello world!"; var x = message.toUpperCase();

Remember, strings are not objects BUT they are passed through a parent object that has methods inherent by the child value of the string. We can call those methods from the parent object with the dot notation. The message . is the string and the .toUpperCase() is the method inherited by the parent object being applied to the string.

We are going to talk a lot more about methods in the quick part coming up next and in greater detail in classes and OOPs following the built-in objects.

Wrap Up

Functions can be declarations or expressions. Declaration are loaded before the code runs whereas function expressions will give an error if they are called prior to being defined.

Functions take in arguments that align with the set parameters. The order of arguments needs to match the order of parameters and the arguments can be values, objects, and even other functions.

The functions set inside the arguments are called callback functions. These are useful when communicating values across multiple scopes.

There are three scopes: global, local, and lexical. Global in web dev is the window object. local scopes are found within the block or {} and lexical scopes are block scopes in blocks, usually functions in functions or another form of control flow.

  • var: function scoped undefined when accessing a variable before it’s declared
  • let: block-scoped ReferenceError when accessing a variable before it’s declared
  • const: block-scoped ReferenceError when accessing a variable before it’s declared can’t be reassigned

Methods are functions within functions. They can be called within the function scope or outside the function scope using dot notation.

Thanks for reading! If you enjoyed this article, make sure to applaud us down below! Would mean a lot to me and it helps other people see the story.

Connect with me:

Instagram | YouTube

--

--

Angel Mondragon

Take advantage of trends, Artificial Intelligence developer, Blockchain Enthusiast, TA Trader. Curious mind and infamous communicator.