3 Functions and Conditional Statements
3 Functions and Conditional Statements
Note: Declared functions are not executed immediately. They are "saved
for later use", and will be executed later, when they are invoked (called
upon).
Call/invoking a function in JavaScript using the call() method
The code inside a function is not executed when the function is
defined. The code inside any JavaScript function will execute
only when "something" invokes it.
It is common to use the term "call a function", "invoke a
function", "start a function, "start a function, all to mean execute
the function.
See below how we can call/invoke the above example function:
myFunctionName(11, 10); // returns 21 because
of 11 + 10
Function expressions: Syntax for defining function with declaration
};
After a function expression has been stored in a variable, the variable can
be used as a function. Functions stored in variables are anonymous or do
not need function names. They are always invoked (called) using the
variable name
You can call/invoke function x above like this:
x (9, 11) // this will return 20, because of 9 + 11
3.3 Functions with arguments
console.log (a);
In the above example, “a” is the input/parameter that we gave for the
function called, myFunction
JavaScript function definitions do not specify data types for parameters.
Note: Functions can be declared wihtout parametes as well
o function mySecondFunction () {
Function arguments: Arguments are the actual value of the parameter passed to
and received by the function. Arguments are values we supply when we
call/use/invoke a function.
Example: When we invoke the myFunction function above, we will need
to pass an argument like this
o myFunction (“Hello world”)// prints Hello world
Note 1: JavaScript doesn’t check the number of parameters you define
and the number of arguments you pass. This means, JavaScript functions
can be called with any number of arguments, regardless of the number of
parameters we named when defining the function originally.
o For example, let’s say you create a function with ONLY two
parameters. You can call this function and pass in 10 arguments.
JavaScript will not care. It will happily invoke the function,
create and assign variables for all parameters and execute the
function. Not a single error thrown.
Note 2: What if you pass fewer arguments than there are parameters?
Those arguments you omit will be set to undefined. Example:
Note 3: The points under note 1 and note 2 above is simple, when you
invoke a function, make sure to pass all required arguments. Remember
that JavaScript will not warn you when you miss some arguments or pass
more arguments than is necessary.
How do function parameter and function argument work in JavaScript?
When you pass arguments to a function:
o JavaScript will create new variables using names of the
parameters
o JavaScript then give these variables initial values using the
argument values you passed when you called the function.
o These variables will be local to the function. They will exist only
inside it (you will not be able to access any of these variables
from the outside)
o These variables will exist only during the function call. Once the
function call is finished, these variables will be lost.
o Example: function adder (x, y) {
console.log (x + y)
In real world, we don't usually want the results to be displayed in a console window. So,
what happens is, our function returns the calculated value to who ever wanted the result.
Some functions don't return a significant value, but others do. It's important to understand
what their values are, how to use them in your code, and how to make functions return
useful values.
Return values: These are values that a function returns when it has completed.
Syntax for functions that return value: A return statement is used in a function body
using the key word “return”. See syntax below:
return value;
var c;
c = a + b;
return c;
numberOne = 4;
numberTwo = 5;
Note: The return statement stops the execution of a function and returns
a value from that function. Let’s see that in example:
function printDog() {
console.log(“dog'”);
return;
console.log(“cat”);
Scope: Scope in JavaScript is a rule that manages the availability of variables. In short,
scope determines which part of your code can see/use or access your variables.
Lexical scoping:
Just like many modern programming languages, JavaScript also follows the
lexical scoping of variables. Lexical scoping is the way by which we set scope of
a variable so that it may only be called (referenced) from within the block of code
in which it is defined. This means that functions are executed using variables that
were named when a function is declared, not using variables named when the
function is called/invoked.
In short, any function, no matter the place where being executed, can access the
variables of its lexical scope
The different forms of variable scoping in JavaScript
Function scope:
Each JavaScript function creates a new scope. Variables declared within
a JavaScript function become LOCAL to the function, meaning variables
within a function are only recognized in that function. That is why
function parameters are always local to that function.
Variables declared with var, let and const are quite similar when declared
inside a function.
function myCar () {
function myFirstName() {
firstName = "Alem";
myFunction();
Block scope: JavaScript introduced block level scope after 2015 (ES6). In ES6,
const and let keywords allow JavaScript developers to declare variables in the
block { } scope, which means those variables exist only within the corresponding
block. In block scope, variables defined in a block of code are only accessible
within that same block.
Variables declared with var: variables declared with var inside a block
{ } can NOT have block scope, meaning, they can be accessed from
outside the block.
Variables declared with let & const: These variables create block
scope variable. This is how most other programing languages scope
variables). It is recommended to use let instead of var. let prevents
mistakes of trying to redeclare an already declared variable
Variables declared with const: const is like let but the value remains
constant always and you cannot reassign the value. const variables need
to be declared using an initializer, or it will generate an error
if (true) {
Arrow:
o Arrow function with ONLY one statement and ONLY one return value: In this case,
you can remove the brackets as well as the return keyword:
const hello = () => "Hello World!";
o Arrow Function with Parameters: Look at the function below that has one parameter
called val
const hello = (val) => "Hello " + val;
In fact, if you have only one parameter, you can skip the parentheses as well:
const hello = val => "Hello " + val;
3.7 Understanding statements: conditional statements
var a = 82;
(a <= 55)
The Decision: Once the evaluation is done, we go to the value of our decision,
This is always a True or False value. Example:
var a = 32;
(a <= 55)
Decision: True
The Statement: This step will determine what to do when conditions are fulfilled
or not fulfilled. Example:
console.log("You failed");
3.8 if statements
Definition: An “if” statement is a programming conditional statement that we use to
specify a block
Syntax: We start by using the key word "if", put the conditions within a bracket. Note
that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Syntax 1:
if (condition) {
Example:
console.log("You failed");
Syntax 2 (alternative syntax): If the statement is only a single line, you can
leave out the containing curly braces
Example:
Example:
var score = 82;
if (score >= pass) {
console.log("Hey you passed");
}else{
console.log("You failed");
// code is executed
// code is executed
} else {
// code is executed
}
Example: Let’s instruct Chu’lo the computer
If (checkIfFolderExists('Abebe')) {
}else{ createFolder('Abebe'
);
Definition: instead of using this long if else statement, you might choose to go with an
easier to read switch statement. The switch statement starts with a variable called the
switch value. Each case in “switch statement” indicates the possible value and if there is a
match when comparing the input value with values of a case, the code associated with the
match will run.
Syntax:
switch(expression) {
case x:
// the code you want to be executed if expression matches value of the case
break;
case y:
// the code you want to be executed if expression matches value of the case
break;
default:
// the code you want to be executed if expression matches value of the case
}
switch (timeOfDay) {
case "morning":
break;
case "afternoon":
break;
case "evening":
break;
default:
break;
console.log(greetings); //
This prints in the console "Good afternoon" after comparing the expression value
in the switch statement (value of timeOfDay) with each case. We see that there is
a match when the case is “afternoon”. Therefore, the code in that associated with
the matching case has executed.
What does the keyword “break” do in “switch statements”?
When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution inside the switch block. Note: It is not necessary to
break the last case in a switch block. The block breaks (ends) there anyway.
What does the keyword “default” do in “switch statements”?
Default clause in switch statement works as the same as else clause in if
else block. The “default” keyword specifies the code to run if there is no
match between the condition and the expression.
The default statement doesn't have to come at the end. It may appear
anywhere in the body of the switch statement.
If no default label is found, the program continues to the statement(s)
after the switch. If default is not the last case in the switch block,
remember to end the default case with a break.
Example:
let x = 4;
switch (x) {
case 0:
console.log("Off");
break;
case 1:
console.log("On");
break;
switch(score){
break;
default:
console.log("Score is 70 or lower");
Example 2 (if you want to evaluate an imprecise value using the switch
statement, you need to create a workaround by evaluating a true expression)
switch(true){
break;
default:
console.log("Score is 70 or lower");
}