Introduction Functions
A function takes in inputs, does something with them, and produces an output.
1 // This is what a function looks like: 2 3 var divideByThree = function (number) { 4 var val = number / 3; 5 console.log(val); 6 }; 7 8 // On line 12, we call the function by name 9 // Here, it is called ‘dividebythree‘ 10 // We tell the computer what the number input is (i.e. 6) 11 // The computer then runs the code inside the function! 12 divideByThree(10);
- First we declare a function using
var
, and then give it a name dividByThree. The name should begin with a lowercase letter and the convention is to use lowerCamelCase where each word (except the first) begins with a capital letter. - Then we use the
function
keyword to tell the computer that you are making a function - The code in the parentheses is called a parameter. It‘s a placeholder word that we give a specific value when we call the function. Click "Stuck? Get a hint!" for more.
- Then write your block of reusable code between
{ }
. Every line of code in this block must end with a;
.
Defining Functions
function square(number) { return number * number; }
- the name of the funciton
- A list of arguments to the function, enclosed in parentheses and separated by commas.
- The JavaScript statements that define the function, enclosed in curly brackets,
{ };
Function Expressions
Such a function can be anonymous; it does not have to have a name.
var square = function(number) { return number * number }; var x = square(4) // x gets the value 16
Scope(global vs local)
Variables defined outside a function are accessible anywhere once they have been declared. They are calledglobal variables and their scope is global.
Variables defined inside a function are local variables. They cannot be accessed outside of that function.
时间: 2024-11-14 07:30:48