I missed the last class :(


2023/09/21 - 10:14

const


- you can change the properties of the object but you can't re-initialize it, meaning you can't add new attributes

If you use a var you can define new properties of the object without error
you can use delete keyowrd to delete properties of objects

Functions in JS


- why use functions?
→ readability
→ modularity
→ reusability
- defining a function uses the ‘function’ keyword

Anonymous functions


function with no name, typically stored in a variable for reference
var var1 = 5
var var2 = 6
var var3 = function (a,b){
    //function stuff
}
console.log(var3(var1,var2));


Immediately Invoked Function Expressions


const area = (function () {
    //function stuff
    return something;
})();

//referencing area will invoke the function
console.log(area);


with parameters:
var var1 = 1
var var2 = 2
var var3 = function(a,b){
    var ans = a + b
    return ans
}(var1,var2);

console.log(var3);


Nested Functions


function outer(a){
    function inner(b){
        //do something
        return;
    }
    inner(a);
    return;
}

outer(1);


Arrow Functions



var func = (args) => <expression>

//or

var func = (args) => {
    //expression
}

var func = () => {expression}



var func1 = a => ({'1':a}); //encapsulate object in parenthesis to return it
var func2 = a => {return {'1' : a}}; //return statement does the job



Function as an Argument


- functions that take others as a parameter, or return functions, are higher order functions
- the functions that get passed are callback functions
function printHello(){
    console.log("hello");
}
function foo(func){
    // do something
    func();

}
foo(printHello);

- can also do this with anonymous functions and arrow functions

function foo(func){
    // do something
    func();

}
foo(()=> console.log("Hello"));



Returning Regular Functions


function foo(){
    function bar(){
    
    }
    return bar;
}

var newfunc = foo();
newfunc(); //will execute bar()

again this works for anonymous and arrow functions










Index