Bootcamp Notes – Day 12 (Mon) – Bootstrap: JavaScript Advanced

Bootstrap: JavaScript Advanced

Functions Declarations

Functions in JavaScript are pieces of code that you can write once then use over and over again. There are multiple ways to create functions in JavaScript; function declaration is the oldest way. The first part of the syntax is similar to a variable declaration: the function keyword, then a unique function name you use to call the function later.

Example 1:

function sayHello() {
        console.log(“Hello World”);
}

sayHello();   <– This calls the function. Basically starts the function

Now lets try passing data into the function. You can pass either literal values or variables into a function. Whatever you pass in, literals or variables, those are called the arguments. The function catches those arguments and put them into variable names that we define inside the parameter list separated by commas.

Example 2:

function sayHello(userName) {     <— userName the parameter.
     console.log(“Hello ” + userName);
}

sayHello(“Jane”);   <—The argument Jane is passed, which is a string literal. The function takes that and creates a local variable userName inside the function. userName is created  when function is called and then deleted when function is finished. The variable userName is a function scope variable that can only be used inside a function. We don’t have to declare with var or let or const. The variable name only as to be unique inside the function. It has local scope. If you try to accces userName from outside the function it does not exist.

Example 3:

function sayHello(userName) {
       console.log(“Hello ” + userName);
}

sayHello(“Jane”);

function sayGoodbye(userName) {
      console.log(“Hello ” + userName);
}

sayGoodbye(“Simon”);
console.log(“username is “, userName);   <–This would not work. It does not exist, if you ran this code.

 

Now we will look at Multiple Parameters.

Example 4:

function getPizzaCost(size, nToppings) {
    let cost = 10; // base cost for a small pizza
    if (size === ‘medium’) { cost += 4; }
   else if (size === ‘large’) { cost += 8; }
   cost += nToppings;
   console.log(‘The cost of this pizza is: ‘, cost);
}

getPizzaCost(‘medium’, 3);

 

Example 5:

function getPizzaCost(size, nToppings) {    <—The variables in the function call don’t have to match. It matters the order in which you pass them in.
     let cost = 10; // base cost for a small pizza
    if (size === ‘medium’) { cost += 4; }
    else if (size === ‘large’) { cost += 8; }
   cost += nToppings;
   console.log(‘The cost of this pizza is: ‘, cost);
}

let pizzaSize = “large”;
let numToppings = 2;
getPizzaCost(pizzaSize, numToppings); <—The variables in the function call don’t have to match. It matters the order in which you pass them in.

 

Example 6: – The Return statement

A function returns a value. That value is set by you the coder. If you don’t set anything to be returned then it will return undefined. You can use a return statement on it’s own to stop execution of a function similar to a break in a for or while loop that will immediately stop the function and return back to wherever you call the function from, so any code after the return will not execute.

  • A function will always return a value.
  • If there is no value explicitly specified by a return statement, the function will return undefined as its value.
  • A function will always exit wherever it encounters the return statement. So the return statement is similar to a break statement in this way.

function getPizzaCost(size, nToppings) {
let cost = 10; // base cost for a small pizza
if (size === ‘medium’) {
    cost += 4;
}
else if (size === ‘large’) {
     cost += 8;
}
cost += nToppings;
console.log(‘The cost of this pizza is: ‘, cost);
return cost;
}

let pizzaSize = “medium”;
let numToppings = 2;
let pcost = getPizzaCost(pizzaSize, numToppings);
console.log(“cost: ” + pcost);

 

Function hoisting

Function declarations are hoisted, which means that the JavaScript engine before it even starts to execute any of the code will scan the whole code for any function declarations. If it finds any, it will host that function to the top of it’s scope before the code is executed. What that means is you can write a function declaration and then call it from anywhere even before the function declaration in the code.

Example 7:  This block of code is now coming first. So it will run the same.

let pizzaSize = “medium”;
let numToppings = 2;
let pcost = getPizzaCost(pizzaSize, numToppings);
console.log(“cost: ” + pcost);

function getPizzaCost(size, nToppings) {
let cost = 10; // base cost for a small pizza
if (size === ‘medium’) {
    cost += 4;
}
else if (size === ‘large’) {
     cost += 8;
}
cost += nToppings;
console.log(‘The cost of this pizza is: ‘, cost);
return cost;
}


Events

Events are occurrences in the system (in our case, the DOM/browser) that we are able to know about and respond to in the code. For the DOM/browser, this includes events such as mouse clicks, window resizes, key presses, and much more. For a list of possible events, see this page on MDN.

In order to respond to an event happening we have to register an event handler to it. Typically that’s a function that does something in response to that event. There is a few way to do this. We can use what’s called an onEvent handler (older way) or use addEventListener (newer way).

Onevent Handlers (The older way)

There are two variations to onevent handlers. The first is the inline method.

<span onmouseover="console.log('over')">DEMO</span> or
<span onmouseover="makeBlue()" onmouseout="makeYellow()">Test</span>

You can consider these two above, the inline onevent handler, as like an inline CSS style. It works, but it can make your code difficult to maintain, and you should refrain from using them in production code. You can see them in action here at Codepen!

The  other variation of the onevent  handler is created entirely through JavaScript. You can see them in action here at Codepen!

document.querySelector('span').onmouseover = makeBlue;
document.querySelector('span').onmouseout = makeYellow;

Here, above have used a JavaScript method called querySelector to find the first span element in the page, and you’ve attached two properties to that element: onmouseover and onmouseout. It is not required to use the querySelector() method to get the span element. There are other ways to select for elements/DOM nodes, such as with document.getElementById() or document.getElementsByTagName(). The querySelector() method is a powerful and flexible way to select nodes within a document or element, however. Notice that unlike when you used the inline onevent handler, you do not include the parentheses after the function name, only the name of the function.

Now in this example we are now using variables!

 

addEventListners (The newer way)

Event listeners are the more modern way of reacting to events, and more recommended. You can add an event listener to any Dom node. The main advantage of event listeners is that you can attach more than one for the same event to the same node. You can’t do that with the onEvent handlers. You can attach multiple onEvent handlers to the same node, but they all have to be for different events. And you may at times need to register multiple event handlers to the same event and we can do that with event listeners!

  • The main advantage of event listeners is that it is possible to add more than one event listener to an element for the same event.
  • With the onevent handlers, it is only possible to attach a single event handler per event type per element.

Here is an example of working code on codepen!

<span>Demo</span>  (HTML)

(JAVASCRIPT)

const el = document.querySelector(‘span’);
el.addEventListener(‘mouseover’, makeBlue);
el.addEventListener(‘mouseover’, makeTextWhite);
el.addEventListener(‘mouseout’, makeYellow);
el.addEventListener(‘mouseout’, makeTextBlack);
el.removeEventListener(‘mouseout’, makeTextBlack);

function makeBlue() {
el.style.background = “blue”;
}

function makeYellow() {
el.style.background = “yellow”;
}

function makeTextWhite() {
el.style.color = “white”;
}

function makeTextBlack() {
el.style.color = “black”;
}


Function Expressions

Function expressions are a way to write functions inline in expressions. This can be useful for various reasons, including being able to use a function as an argument for another function (which is known as a callback function). The function expression was added to JavaScript after function declarations. There are actually two variants of the function expression: the anonymous function expression, and the named function expression.

anonymous function expression

const adder = function(a,b) {
    return a+b;
}

Codepen example here:

named function expression

const adder = function someName(a,b) {
   return a+b;
}

Most function expressions you run into will be anonymous. One more thing to know about function expressions is that they are not hoisted as function declarations are. They are not valid to use until you have reached them in the code. This can be useful for limiting the scope of a function.


Arrow Functions

Arrow functions are a new introduction to JavaScript in ES6 (ES2015). Arrow functions will be used very frequently in React (and other modern libraries), so it is crucial that you learn to understand and write them. Arrow functions are a more compact version of function expressions and are frequently used as callback functions (functions that are passed into other functions as arguments). You will learn more about using arrow functions as callback functions later. Aside from being more compact, the other crucial difference with arrow functions is that they do not have their own this keyword binding. We will not delve into the meaning of this at the moment, but you will learn more later.

Example of an Arrow function:

const adder = (a,b) => a + b;
console.log(adder(2,3)); Compared to a function expression:
const adder2 = function(a,b) {
    return a + b;
}

Did you catch that? The first line above was the entirety of the arrow function. That’s how concise it is. Arrow functions are a handy and quick way to write functions, and you’ll see how useful they are in the first week of your next course, React, when you will learn about array iteration methods.

 

 


Additional Resources:

You May Also Like