JavaScript Programming/Functions

From Wikiversity
Jump to navigation Jump to search

This lesson introduces JavaScript functions.

Objectives and Skills[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Complete and debug code that uses built-in Math functions
    • Random; round; abs; floor; ceiling; min; max; pow; sqrt
  • Complete and debug a function that accepts parameters and returns a value
    • Reusable code; local versus global scope, redefine variables, pass parameters, value versus reference, return

Readings[edit | edit source]

  1. Wikibooks: JavaScript/Functions
  2. Wikibooks: JavaScript/Anonymous functions
  3. Mozilla: JavaScript/Functions
  4. JavaScript Functions

Multimedia[edit | edit source]

  1. YouTube: JavaScript Functions
  2. YouTube: JavaScript Tutorial for Beginners - 06 - Functions
  3. YouTube: JavaScript Tutorial for Beginners - 07 - Functions Part 2
  4. YouTube: JavaScript Tutorial for Beginners - 14 - Return statement
  5. YouTube: JavaScript Tutorial for Beginners - 15 - Global and local variables
  6. YouTube: JavaScript Tutorial for Beginners - 16 - Pass by value
  7. YouTube: Passing by reference vs. by value - JavaScript Tutorial
  8. YouTube: Javascript Functions & Parameters
  9. YouTube: Number Methods and Math Objects in JavaScript
  11. YouTube: Functions and Return
  12. How To Create/Use Functions - JavaScript Essentials

Examples[edit | edit source]

Activities[edit | edit source]

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Prompt the user for input and use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a program to prompt the user for hours worked per week and rate per hour and then calculate and display their weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.
  2. Create a program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds. For example, a person 1 year old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths and Metric - US/Imperial Conversion Charts. Create a program that asks the user for a distance in miles, and then calculate and display the distance in yards, feet, and inches, or ask the user for a distance in miles, and then calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet to a yard.[2]
  6. Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as 2 * length * height + 2 * width * height . Calculate the number of gallons as: total area / square feet per gallon . Note: You must round up to the next full gallon. To round up, use the Math.ceil function. Calculate the total cost of the paint as: gallons * price per gallon.[3]

Lesson Summary[edit | edit source]

  • A JavaScript function is a block of code designed to perform a particular task.[4]
  • Indent JavaScript code blocks (functions, conditions, loops, comment blocks, etc.) 2 spaces for each indent level.[5]
  • Functions break down code into reusable blocks of code each of which performs a specific task.[6]
  • Code inside a function is not executed at the time of declaration. A function has to be called upon (invoked) first.[7]
  • JavaScript function expressions can invoke themselves.[8]
  • JavaScript functions do not check the number of arguments received. Missing arguments are set to undefined.[9]
  • JavaScript functions do not check the data type of passed arguments.[9]
  • JavaScript functions can only return one value.[10]
  • A key benefit to using functions is that breaking. program down into smaller, simpler tasks makes it more manageable and maintainable.[11]
  • Functions can be used as values.[12]

Key Terms[edit | edit source]

anonymous function
A function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.[13]
The real value passed to (and received by) the function.[14]
arguments object
An array of the arguments passed in when the function is invoked. The arguments object can be used to access arguments when more arguments are passed to the function than parameters declared by the function definition.[15]
A block of code designed to perform a particular task when the code is invoked. A JavaScript function can be defined using the function keyword.[16]
function call
The declaration of the function by its self doesn't do anything. In order to execute that code, the function must be called using the name given when the function was declared, and parenthesis "()" with parameters if needed.[17]
function expression
A function that can be stored in a variable. After a function expression has been stored in a variable, the variable can be used as a function. Functions stored in variables do not need function names. They are always invoked (called) using the variable name.[18]
global variable
A variable declared outside a function.[19]
The code inside the function will execute when "something" invokes (calls) the function.[20]
local variable
A local variable is a variable which is either a variable declared within the function or is an argument passed to a function.[21]
A name listed in a function definition.[22]
Ends function execution and returns a value in the place the function was invoked.[23]
Refers to the visibility of variables and methods in one part of a program to another part of that program (local and global variables).[24]
The undefined property indicates that a variable has not been assigned a value, or not declared at all. It is a variable in global scope.[25]

See Also[edit | edit source]

References[edit | edit source]

  1. Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. Wikibooks: Programming Fundamentals/Practice: Data and Operators
  3. Wikibooks: Programming Fundamentals/Practice: Data and Operators
  4. W3Schools: JavaScript Functions
  6. MDNː Functions — reusable blocks of code
  7. W3Schoolsː JavaScript Function Invocation
  8. W3Schoolsː JavaScript Function Definitions
  9. 9.0 9.1 W3Schoolsː JavaScript Function Parameters
  10. MDNː Functions — Return Values
  11. "JavaScript/Functions - Wikibooks, open books for an open world". Retrieved 2021-02-01.
  12. Example: "Tryit Editor v3.6". Retrieved 2021-02-01.
  13. Wikibooks: JavaScript/Anonymous functions
  14. "JavaScript Function Parameters". Retrieved 2019-09-05.
  15. "JavaScript Function Parameters". Retrieved 2019-09-05.
  16. "JavaScript Functions". Retrieved 2019-09-05.
  17. W3Schools: JavaScript Functions
  18. Singh, Mandeep (2017-10-11). "Function Declarations vs. Function Expressions". Medium. Retrieved 2020-09-08.
  19. W3Schools: JavaScript Scope
  20. W3Schools: JavaScript Functions
  21. Wikipedia: Local variable
  22. "JavaScript Function Parameters". Retrieved 2019-09-05.
  23. W3Schools: Return
  24. Introduction to Programming/Scope
  25. MDN: Undefined