본문 바로가기
Udemy - The web developer camp

JavaScript function level up

by Hanachoi 2022. 10. 13.

#Scope

  •  Scope refer to variable 'visibilty', basically the location where a variable is defined dictates where we have access to that variable. 
function collectEgg(){
	let totalEggs=6;
    console.log(totalEggs)
}

collectEggs(); // 6
  • If you run this function, totalEggs number is printed on console. But if you move console.log(totalEggs) to outside function, this code makes just an error. What if you run this function first and then console.log(totalEggs)? It is also not working.
  • What we see here or we are running up against functions, scope, variables we define inside of function where we actullay use the keyword and we define that value and that variable in the function, they are scoped to that function. 그 함수로 범위가 한정되기 때문에 totalEggs로 함수 밖에서 접근이 불가능해진다.  It is like a little bubble. This function between those braces is its onw little world with a glass dome around. totalEggs only live in the function.
  • If you really want to access this variable, you can do like this. You make a variable outside of the function and you can update this variable without let keyword inside of function.  You can run totalEggs first, and then run this function.
let totalEggs = 0;
functiom collectEggs(){
	totalEggs = 6;
}
console.log(totalEggs);
collectEggs();
console.log(totalEggs);
  • This is not super common way. This is called global variable. 
  • Function scope means when you declare any variable inside of function, it is just working in function not ouside of functio. The variable inside function is scoped to the function. 
function helpMe(){
	let msg = 'I am on fire!';
    msg; // 'I am on fire!'
}

msg;//Not defined !

 

 

  • If there's variable defined as the same name in a function and is scoped in this function, then this variable refer to the varivale inside of function instead of outside one. If there is no variable in function, it is going to find the same name of variable outside of funtion. 
let bird = 'Scarlet Macaw';
function birdWatch(){
	let bird = 'Great Blue Heron';
    console.log(bird);
}

birdwatch() //  'Great Blue Heron' 함수안에 선언된 같은 이름의 변수부터 찾아서 참조하게 됨.
//만약에 함수안에 bird라는 변수가없다면 가장 가까운 곳에서 bird라는 이름의 변수를 찾아서 참조하게된다.
  • above this example, bird is scoped to birdWatch function. 

 

# Block Scope

  • Block refers to basically any time you see curly braces except for function.  A block includes things like conditionals most commonly but also loops.
let radius = 8;
if(radius >0){
	const PI = 3.14159
    let msg = 'HIII!!'
}

console.log(radius) //8
console.log(msg) // it is not defined.
for(let i = 0; i < 5 ; i++){
	let msg = 'dfsfdf ' ;
}

msg // not defined;
  • you have no access that variable inside of conditonal and loop. If you write console.log(msg) inside of loop, it will work. 
  • If you use var keyword instead of let or const, variables are scoped to functions, but they are not scoped to block. What's more is that if you put let i = 0 in conditonal parentheses, you can also access i number as well. If this is declard with let or const, you only can access these in the block. 

 

# Lexical scope

  • An inner function nested inside of some parent function has access to the scope or to the variable defined in the scope of that outer function. 
  • 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', 'Black Panther', 'Batwoman']
	function cryForHelp(){
    	for(hero of heroes){
        	console.log(`PLEASE HEL ME US ${hero.toUpperCase()}`)
        }
    }
    cryForHelp(); //함수를 한번 실행시키지 않으면 다른 함수안에 들어있는 cryForHelp()가 실행되지 않기때문에 한번 실행해주는 것 
}
  • Nested or inner function has accss  to the same stuff as the parent function or grandparent however leves up. 

 

 

# Function Expressions

  • It is a new way of defining functions. If you don't have identifier which is a name of function, there will be syntax error.  But if you put this function into a variable, you don't need a indetifier.
  • Technically, this function has no name. It is just an object of this variable. 
const add = function (x,y){
	return x + y;
}
  • It is just another syntax for defining a function, saving it in variable. But the second reason is that it actually demonstrates something that is going to come up a lot in this course , which is functions are values in JS. We can jsut store and pass like other variables. 

 

#Higher order functions

  • It is fancy way to talk about a fuction works for another function. Functions that operate on/ with other functions. They can accept other functions as arguements 
function callTwice(func){
	func();
    func();
}

function rollDice(){
	const roll = Math.floor(Math.random() * 6) + 1
    console.log(roll);
}

callTwice(rollDice);
function callTenTimes(f){
	for(let i =0; i <10; i++){
    	 f() // just exacute whatever function in it. 
    }
}

callTenTiems(rollDice); // 10 numbers will show

 

# Return function. 

  • Higher order functions also can return a function. The point here is to illustrate taht functions are just regular old values and we can pass them around whether that means returning them or passing them as arguement.
function makeMysteryFunc(){
	const rand = Math.random();
    if(rand > 0.5){
    	return function() {
        	console.log('congrats, I am a good function!')
            console.log('you win a million dollors!')
        }else{
        	return function(){
            	alert('You have been infected by a computer virus')
                alery('Stop trying to close this window!')
            }
        }
    }
}
function isBetween(num){
	return num>=50 && num<=100
}// boolean true or false
function makeBetweenFunc(min,max){
	return function(num){
    	return num >=min && num <= max;
    }
}

makeBetweenFunc(100,200)// It will return me a function
  • 100 is the same value as min and 200 is the same value as max which is they are scoped of this function, basically whatever they were at the time, we returned this function. 
  • we can save it a variable 
const isChild = makeBetweenFunc(0,18)

//function returns num>=min && num<=max ; is true or false.

isChild(40) // false
isChild(17) // true

const isSenior = makeBetweenFunc(65,120)

isSenior(40); // false

 

#Methods

  • Methods is simply that we can add functions as properties on objects. Such as .toUpperCase() / indexOf(), it is all methods and when we use methods, we put dot before the name of methods.'
  • Every Method is a function, but not  every function is a method, so we can actually add some method on object. We can add function as a property and value. 
const math = {
	multiply : function (x,y){
    	return x*y;
    },
    divide : function(x,y){
    	return x/y;
    },
    squre : function (x){
    	return x*x;
    }
};
const myMath = {
	PI : 3.14159,
    squre : function (num){
    	return num * num;
    },
    cube : function(num){
    	return num **3
    }
}
  • When you execute this function, you need to access with .(dot) method. myMath.squre(2) // 4 
  • There is new way to add some properties like function in js. 
  • You don't need to write down function keyword. Just put name of function right away, but still you need to put comma
const myMath = {
	PI : 3.14159,
    squre(num){
    	retrun num*num;
    },
    cube(num){
    	return num**3;
    }
}

 

 

# This keyword

  • We use 'this' keyword to access other properties on the same object.
  • Let's say you have a function of several properties and you want to access 'name' of cat object. If you just write down name itself, this function won't work. When you access it with this keyword, It is going to be working
const cat = {
	name : 'Blue steele',
    color : 'grey',
   	breed : 'scottish fold',
    meow(){
    	console.log(`${this.name} says MEOWWWWW`);
    }
}
  • But the value of this depends on the invocation context of the function it is used in. It depends on actually how we call the function. 
cat.meow() // Blue steele says MEOWWWW

const meow2() = cat.moew;// says MEOWWWW
// meow2 and a function above is the same one but meow2 didnt get the name
  • The reason why meow2 didn't get the same result is that they invoked in a different way. when you call cat.meow, it refer to the object called cat. However meow2 is in Window object. 
  • Window object is built in object in JS. It is a huge object in js and it has some properties like alert. WIndow is the top of object in js. 
  • In case of cat.meow, meow is a function and it has a .(dot) and object called cat in the left side. meow2 also has an object which is window that is invisible. It is a defalut value of this keyword.

 

# Try / Catch

  • It is not related with function directly. These keywords go together. They have to do with errors or exceptions in JS specifically. They have to do with catching errrors and preventing then from breaking or stipping the execution of our code. 
hello.toUpperCase() // uncaught referenceError ;
  • If you run this code, you will get an error because hello is not defined. you need to focus on 'uncaught Error'. If you anticipate you might have any error, we can wrap it with TRY block. But it won't work because you missed CATCH block. 
  • Catch block will execute when try block does not work. 
try {
	hello.toUpperCase();
}catch{
	console.log("ERROR!!")
}
  • If there is any errors in your code, the next code line is not working and just send an error message. But if you use this try / catch block, you can run the next code without error.
function yell(msg){
	console.log(msg.toUpperCase().repeat(3));
}//

yell("HELLO") // HELLOHELLOHELLO
yell(1234) // error!
  • On this example, this function is not working if you put number not string, and you can use try/catch here. At least that's one strategy that I can use to handle the situation where message is not a string. You can just straight up check if this message is a string or not, but this is a different approach. 
  • You can just wrap up this whole thing with try and catch. 
function yell(msg){
	try{
    	console.log(msg.toUpperCase().repeat(3));
    }catch(e){
        console.log("Please pass a string next time!")
	}
}

yell(1234);  // Please pass a string next time!

 

'Udemy - The web developer camp' 카테고리의 다른 글

JavaScript new syntax  (0) 2022.11.12
JavaScript Callback and Array Methods  (0) 2022.10.25
JavaScript Function  (0) 2022.09.28
JavaScript Loop  (0) 2022.09.13
JavaScript Object Literals  (0) 2022.09.09

댓글