-Intro to Functions
-Arguments Intro
-Function with Multiple Arguments
-The Return Keyword
-Function Scope
-Block Scope
-Lexical Scope
-Function Expressions
-Higher Order Functions
-Returning Functions
-Defining Methods
-The Keyword 'this'
-Using Try/Catch
Intro to Functions
Functions are reusable procedures.
Functions allow us to write reusable, modular code.
We define a "chunk" of code that we can then execute at a later point. We use them all the time.
syntax
function functionName() {
do something here
}
function singSong() {
console.log("Do");
console.log("RE");
console.log("MI");
}
singSong()
singSong()
singSong()
the out put of the code would be
DO RE MI
Arguments Intro
An argument allows us to write functions that accept inputs.
Code with no inputs
"hello".toUpperCase();
Code with inputs
"hello".indexOf('h');
"hello".indexOf('o');
The main point of arguments is that they allow something to happen within the code to change the outcome by using inputs.
Function with Multiple Arguments
function greet(firstName, lastName) {
console.log(`Hey there, ${firstName}! ${lastName}.`)
}
The code has two parameters defined that is separated by a comma.
greet('Jane','John');
the output would be
Hey there, Jane, John.
The Return Keyword
The return keyword is a built-in methods that returns values when we call them.
function repeat(str, numTimes) {
let result = '';
for (let i = 0; i < numTimes; i++) {
result += str;
}
console.log(result);
}
function add(x, y) {
let sum = x + y;
return sum;
}
Return statement ends functions execution and specifies the value to be returned by that function.
Function Scope
Scope variable "visibility" is the location where a variable is defined dictates where we have access to that variable.
Block Scope
A block includes things like conditionals as well as loops.
let radius = 8;
if (radius > 0) {
const PI = 3.14;
let circ = 2 * PI * radius;
}
console.log(radius);
console.log(msg);
The console.log statements are outside the block level scope, therefore the console.log statements will not run.
The code between the { will run accordingly because they are in the block level scope.
PI and circ are scoped to the block level.
let bird = 'mandarin duck';
function birdWatch() {
let bird = 'golden pheasant';
bird;
}
bird;
bird is scoped to birdWatch function
Lexical Scope
Lexical Scope is when an inner function nested inside of some parent function has access to the scope or to the variables defined in the scope of that outer function.
function bankRobbery() {
const heroes = ['Spiderman', 'Wolverine',]
function cryForHelp() {
for (let hero of heros) {
console.log(`Please help us, ${hero.toUpperCase()}
}
}
cryForHelp();
}
Nested or inner function has access to the same stuff as the parent function or grandparent or how many levels up.
Function Expressions
A function is just a value that can be stored in a variable.
const sqaure = function (num) {
return num * num;
}
sqaure(7);
const add = function (x, y) {
return x + y;
}
Higher Order Functions
Functions that operate on/with other functions.
They can accept other functions as arguments and return a function.
function callTwice(func) {
func();
func();
}
function laugh() {
console.log("Hahahah");
}
callTwice(laugh)
The function called callTwice is going to expect a function to be passed in.
Returning Functions
function makeMysteryFunc() {
const rand = Math.random();
if (rand > 0.5) {
return function () {
console.log("Congratz, I am a good function!")
console.log("You win a million dollars!!")
} else {
return function() {
alert("This is a popup message to annoy you")
}
}
}
}
Returning a function as a value.
Defining Methods
Methods are functions as properties on objects.
const math = {
multiply : function(x ,y) {
return x * y;
},
divide : function(x ,y) {
return x / y;
},
square : function(x) {
return x * x;
},
};
The Keyword 'this'
The keyword 'this' is used to access other properties on the same object.
const person = {
first: 'Robert',
last: 'Herjavec',
fullName() {
return `${this.first} ${this.last}`
}
}
person.fullName(0;
person.last = "Plant";
person.fullName();
Using Try/Catch
Try/Catch is used for errors or exceptions in JavaScript. They have to do with catching errors or preventing them from breaking or stopping the execution of code.
Sometimes it is necessary to anticipate where something might go wrong and plan for that in a way that will keep the code from breaking.
try {
hello.toUpperCase();
} catch {
console.log("Error!!")
}
hello.toUpperCase();
console.log("After");
function yell(msg) {
try {
console.log(msg.toUpperCase().repeat(3));
} catch (e) {
console.log("Please pass a string next time!")
}
}
Top comments (0)