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

Multimedia[edit | edit source]

  1. YouTube: JavaScript Tutorial for Beginners - 06 - Functions
  2. YouTube: JavaScript Tutorial for Beginners - 07 - Functions Part 2
  3. YouTube: JavaScript Tutorial for Beginners - 14 - Return statement
  4. YouTube: JavaScript Tutorial for Beginners - 15 - Global and local variables
  5. YouTube: JavaScript Tutorial for Beginners - 16 - Pass by value
  6. YouTube: JavaScript Pass By Reference
  7. YouTube: Number Methods and Math Objects in JavaScript
  8. YouTube: Javascript Functions & Parameters
  9. YouTube: JavaScript Functions - Practice
  10. YouTube: JavaScript Functions

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]
  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. 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.[3]
  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, add 0.9999 and then convert the resulting value to an integer. Calculate the total cost of the paint as: gallons * price per gallon.[4]

Lesson Summary[edit | edit source]

  • A JavaScript function is a block of code designed to perform a particular task.[5]
  • Indent JavaScript code blocks (functions, conditions, loops, comment blocks, etc.) 2 spaces for each indent level.[6]
  • Functions break down code into reusable blocks of code each of which performs a specific task.[7]
  • Code inside a function is not executed at the time of declaration. A function has to be called upon (invoked) first.[8]
  • JavaScript function expressions can invoke themselves.[9]
  • JavaScript functions do not check the number of arguments received. Missing arguments are set to undefined.[10]
  • JavaScript functions do not check the data type of passed arguments.[10]
  • JavaScript functions can only return one value.[source?]

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.[11]
argument
The real value passed to (and received by) the function.[12]
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.[13]
function
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.[14]
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.[15]
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.[16]
global variable
A variable declared outside a function.[17]
invocation
The code inside the function will execute when "something" invokes (calls) the function.[18]
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.[19]
parameter
A name listed in a function definition.[20]
return
Ends function execution and returns a value in the place the function was invoked.[21]
scope
Refers to the visibility of variables and methods in one part of a program to another part of that program (local and global variables).[22]
undefined
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.[23]

See Also[edit | edit source]

References[edit | edit source]

  1. Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. PythonLearn: Variables, expressions, and statements
  3. Wikibooks: Programming Fundamentals/Practice: Data and Operators
  4. Wikibooks: Programming Fundamentals/Practice: Data and Operators
  5. W3Schools: JavaScript Functions
  6. https://google.github.io/styleguide/jsguide.html
  7. MDNː Functions — reusable blocks of code
  8. W3Schoolsː JavaScript Function Invocation
  9. W3Schoolsː JavaScript Function Definitions
  10. 10.0 10.1 W3Schoolsː JavaScript Function Parameters
  11. Wikibooks: JavaScript/Anonymous functions
  12. "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
  13. "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
  14. "JavaScript Functions". www.w3schools.com. Retrieved 2019-09-05.
  15. W3Schools: JavaScript Functions
  16. Singh, Mandeep (2017-10-11). "Function Declarations vs. Function Expressions". Medium. Retrieved 2020-09-08.
  17. W3Schools: JavaScript Scope
  18. W3Schools: JavaScript Functions
  19. Wikipedia: Local variable
  20. "JavaScript Function Parameters". www.w3schools.com. Retrieved 2019-09-05.
  21. W3Schools: Return
  22. Introduction to Programming/Scope
  23. MDN: Undefined