code

JavaScript Functions

// Write Reusable JavaScript with Functions

function functionName() {
  console.log("Hello World");
}

functionName();

// Passing Values to Functions with Arguments

function testFun(param1, param2) {
  console.log(param1, param2);
}

testFun("Hello", "World");

// Global Scope and Functions

/*
In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.

Variables which are declared without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.
*/

function myTest() {
  var loc = "foo";
  console.log(loc);
}
myTest();
console.log(loc);

// Global vs. Local Scope in Functions

/*
It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.
*/

var someVar = "Hat";
function myFun() {
  var someVar = "Head";
  return someVar;
}

/* The function myFun will return the string Head because the local version of the variable is present. */

// Return a Value from a Function with Return

function plusThree(num) {
  return num + 3;
}
var answer = plusThree(5);

// Understanding Undefined Value returned from a Function

/* A function can include the return statement but it does not have to. In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.*/

var sum = 0;
function addSum(num) {
  sum = sum + num;
}
addSum(3);

/*addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is undefined.*/

// Assignment with a Returned Value

ourSum = sum(5, 12);



Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.