Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Writing reusable code with functions
- function ourReusableFunctionName() { //may pass info to (). Function is also being defined as ourReusableFunctionName
- console.log("Hi, World"); //Info inside this curly bracket is run when the function is called
- }
- ourReusableFunctionName(); //function is being called here
- /*Passing values to functions with arguments
- Parameters are variables that act as placeholders for values that are to be input to a function
- when it's called.*/
- function ourFunctionwithArgs(a, b) {
- console.log(a - b);
- }
- ourFunctionwithArgs(10, 5) //when this function is called, data (10, 5) is passed into the function
- /*Global scope and functions
- Scope refers to the visibility of variables. These variables are defined/anywhere outside of a
- function block have global scope.
- Global scope refers to them being seen anywhere in JS code.*/
- var myGlobal = 10; //this is a global scope, outside a function
- function fun1() {
- oopsGlobal = 5; /*this is a GLOBAL Function in a function for NOT having var.
- Var oopsGlobal = 5, This is scoped WITHIN function, aka LOCAL scope*/
- }
- function fun2() {
- var output = "";
- if (typeof myGlobal != undefined ) {
- output += "myGlobal: " + myGlobal;
- }
- if (typeof oopsGlobal != undefined) {
- output += " oopsGlobal: " + oopsGlobal //undefined would show if it was var oopsGlobal
- }
- console.log(output);
- }
- fun1();
- fun2();
- //Local scope and functions
- function theLocalScope() { /*variables declared within a function/function parameters have LOCAL scope.
- meaning that they are visible within the function.*/
- var myVar = 20 //this variable is declared within the function, hence only visible there.
- console.log(myVar);
- }
- theLocalScope();
- /*console.log(myVar); This doesn't work since it tried to access myVar outside the function*/
- //Global vs. Local Scope in Functions
- //It's possible to both have GLOBAL and LOCAL variables with the same name.
- //The LOCAL variable takes precedence over the global variable
- var outerWear = "T-shirt";
- function myOutfit() {
- var outerWear = "Sweater" //This would appear instead of T-shirt.
- return outerWear;
- }
- console.log(myOutfit());
- console.log(outerWear) //T-shirt appears here, since it's logging GLOBAL variable.
- //Returing values from a Function with Return
- function minusSeven(num) {
- return num -7; //This gives back the result from 10-7
- }
- console.log(minusSeven(10))
- //Understanding Undefined Value Returned from a function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement