function speak (words) {
console.log(words);
}
var speak = function (words) {
console.log(words);
}
// can be run anytime
speak('hello, world!')
function speak(words) {
console.log(words)
}
// DOES NOT RESULT IN ERROR
// MUST be declared BEFORE
// you run the function
speak('hello, world!')
var speak = function (words) {
console.log(words)
}
// RESULTS IN ERROR:
// TypeError: undefined
// is not a function
function hello () {
console.log("hello there!")
}
hello();
=> hello there!
// Bad idea...
function helloBlanch () {
console.log('hello, Blanch');
}
function helloRose () {
console.log('hello, Rose')
}
function sayHello (name) {
console.log('Hello ' + name);
}
sayHello('Blanch');
=> 'Hello Blanch'
sayHello('Rose');
=> 'Hello Rose
Parameters allow us to write functions that can act on different inputs
// Parameter
function doSomething (parameter) {
// does something
}
// Argument
doSomething(argument)
Parameters refer to variables defined in the function's declaration;
arguments refer to the actual values passed into the function when the function is called. For example:
function sum(x, y, z) {
console.log(x + y + z)
}
sum(1, 2, 3);
=> 6
sum(7, 8, 9);
=> 24
Create a page that displays a random update of two dice every time the user hits the "Roll Dice" button
Sometimes we want to update a variable or even call another function. This requires a return statement.
When we return something, it ends the function's execution and "spits out" what we are returning.
function sum (x, y) {
return x + y;
}
var z = sum(3, 4);
=> 7
function sum (x, y) {
return x + y;
}
function double (z) {
return z * 2;
}
var num = sum(3, 4)
=> 7
var numDbl = double(num);
=> 14
// This can also be written:
var num = double(sum(3,4));
=> 14
return words;
// The following statements
// will not run:
var x = 1;
var y = 2;
console.log(x + y)
}
Scope is the set of variables you have access to.
JavaScript reads from top to bottom. Sometimes, however, we declare variables inside functions (just like arguments), which aren't accessible in other parts of our code.
This is the concept of scope.
Conversely, if a variable is declared inside a function, it is referred to as LOCAL, and has a local scope.
A variable with local scope cannot be referenced outside of that function.
var a = "this is the global scope";
function myFunction() {
var b = "this variable is defined in the local scope";
}
myFunction();
console.log(b);
// Global Scope
var a = "Hello";
// This function is defined in the global scope
function sayHello(name) {
return a + " " + name;
}
sayHello("JavaScript");
=> "Hello JavaScript";
When a function is defined inside another function, it is possible to access variables defined in the parent from the child:
var a = 1;
function getScore () {
var b = 2,
c = 3;
function add() {
return a + b + c;
}
return add();
}
getScore();
=> 6