As demonstrated in the below examples, I used the function
keyword to declare a function that will generate a random integer number within a range, and I also used a const
keyword to declare another function that will convert a string and return an integer. Your brief explanation will be helpful and appreciated.
//Generating a random whole number within a range.
function isBeginner(a1, a2) {
let randomRange = "";
if (a2 >= a1) {
randomRange = Math.floor(Math.random() * (a2 - a1 + 1) + a1);
} else {
randomRange = Math.floor(Math.random() * (a1 - 1 + a2) - a1);
}
return randomRange;
};
console.log(isBeginner(2, 4)); //positive integer expected
console.log(isBeginner(5, 3)); //negative integer expected
//Using ParseInt to generate an Integer
const isBeginner2 = function(lib) {
let crib = "";
// using Switch statement for better descriptions
switch (lib) {
case "Zero before a real number":
crib = parseInt(lib)
break;
case "String":
crib = parseInt(lib);
break;
case "Decimal number":
crib = parseInt(lib);
break;
case "Letter before a number":
crib = parseInt(lib);
break;
case "Number before a letter":
crib = parseInt(lib);
break;
default:
crib = parseInt(lib);
break;
}
return crib;
};
console.log(isBeginner2(005)); // output **5** expected
console.log(isBeginner2("Stay Healthy")); // output **NaN** expected
console.log(isBeginner2(1.5)); // output **1** expected
console.log(isBeginner2("E7")); // output **NaN** expected
console.log(isBeginner2("8S")); // output **8** expected
2
Answers
Function expressions
Function Expressions are created when the execution flow reaches them.
The two syntaxes you show represent a "function declaration" and a "function expression".
Function Declaration:
a function with the
function
keyword. The function declaration musthave a function name.
are standalone constructs and they cannot be nested inside a
functional block.
after the function definition (due to "hoisting").
Function Expression:
the function name (an anonymous function assigned to a variable).
interpreter reaches the line of code.
the function definition (the variable is hoisted, but the actual assigned value is not).
Now whether you use
var
,let
, orconst
in the function expression doesn’t really affect how the function operates, but it does affect the scope of the function, and in the case ofconst
indicates that the variable can’t be reassigned.