본문 바로가기
TIL: Today I Learned

[TIL] 20201204 Leveling Up Our Functions

by 김알리 2020. 12. 5.

Scope

  • Variable 'visibility'
  • Impact of the variable
  • The location where a variable is defined dictates where we have access to that variable

 

 

Function Scope

  • Defined inside of a function
  • Visible only inside of the function

 

 

Block Scope

  • Defined inside of a block (i.e. conditionals, loops...)
  • Visible only inside of the block
  • If var is used to make variables, they are visible outside of the block, which is precisely why let and const are used nowadays.

 

 

Lexical Scope

  • Nested functions have access to variables in their parent functions.

 

 

Function Expressions

  • Creating functions with variables
  • Syntax
const functionName = function() { 
    //code
}

 

 

 

Higher Order Functions

  • Functions that operate on/with other functions
  • Other functions can be accepted as arguments
  • Can return a function
  • Example
function fun1(fun) {
    fun();
    fun();
}

function fun2() {
	//code
}

fun1(fun2); //execute fun2 twice

 

 

 

Returning Functions

  • Functions can be returned in other functions
  • We can make a factory function that makes functions.
  • Example
function makeBetweenFunc(min, max) {
    return function (num) {
    	return num >= min && num <= max;
    }
}

//returns a function that checks if a number is between min and max

 

 

 

Methods

  • Functions that are properties of Objects
  • Syntax
const obj = {
    func: function() {
   	//code
    }
}
  • Shorthand Syntax
const obj = {
    func() {
    	//code
    }
}

 

 

 

this in Methods

  • Used to access other properties on the same object.
  • Example
const person = {
    first: 'Jiwan',
    last: 'Kim',
    fullName() {
    	return `&{this.first} ${this.last}`;
    }
}
  • The value of this depends on the invocation contet of the function it is used in.
    • this refers to the object in front of the dot.
    • For example, for person.fullName, this means 'person'
    • By default, this refers to window object.

 

 

Try/Catch

  • Syntax
try {
	//error-prone code
} catch {
	//code that runs when there's an error
}
  • How to print out the error
catch(e){
    console.log(e);
}

 

 

 

 

 

* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.