I was doing a course on Udemy to learn JavaScript by making a pong game but when I came across this part I was really confused. What do the parameters do? Are they variables? If they are variables can they be accessed out of the function? I just don't understand! Please explain it to me! :(
I don't even understand what he's trying to do!
I think he was trying to draw or fill it in or something.
this is the code:
function colorCircle(centerX, centerY, radius, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2, true);
}
A variable is simply a named value. Instead of hard-coding values everywhere:
100 /* speed of my canary */ + 10 /* current speed bonus */
we can "name" our values and pass them around (and even change them as we need to without re-writing the rest of our program):
var speedOfMyCanary = 100;
var speedBonus = 10;
speedOfMyCanary + speedBonus // still 110;
A function parameter is simply a variable scoped to a function:
function doWork(a, b, c) {
// Do work here later with a, b, and c.
}
is the same (conceptually) as:
var a, b, c;
function doWork() {
// Do work here later with a and b and c
}
// Call do work now
doWork();
delete a;
delete b;
delete c;
if we could carry around the var a, b, c
and delete a, b, c
with our doWork
without copy-pasting it.
That is to say, when we call:
doWork(1, 2, 3);
It is (again, conceptually) the same as:
var a = 1, b = 2, c = 3;
function doWork() {
// Do work here later with a and b and c
}
doWork();
delete a;
delete b;
delete c;
Function parameters get us a few extra benefits:
First, the parameters a
, b
, and c
are not accessible to code outside our function:
function doWork(a, b, c) {
// a, b, and c are all accessible here
return a + b + c;
}
// But we can't access those values out here
// if we try we'll get:
a // ReferenceError - `a` is not defined
The bonus benefit is that our callers don't have to worry about what we call our inputs internally - if we change the names from a
, b
, and c
to x
, y
, and z
our calling code remains unchanged:
function doWork(x, y, z) {}
doWork(1, 2, 3) // STILL WORKS :-)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments