name.function name(parameter1, parameter2, ... parameterN) {
// body
}
For instance:
function showMessage() {
alert( 'Hello everyone!' );
}
For instance:
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function
For instance:
let userName = 'John';
function showMessage() {
userName = "Bob"; // (1) changed the outer variable
let message = 'Hello, ' + userName;
alert(message);
}
alert( userName ); // John before the function call
showMessage();
alert( userName ); // Bob, the value was modified by the function
For instance:
function showMessage(from, text) {
from = '*' + from + '*'; // make "from" look nicer
alert( from + ': ' + text );
}
let from = "Ann";
showMessage(from, "Hello"); // *Ann*: Hello
// the value of "from" is the same, the function modified a local copy
alert( from ); // Ann
declared with two parameters, then called with two arguments: from and "Hello"".function showCount(count) {
// if count is undefined or null, show "unknown"
alert(count ?? "unknown");
}
showCount(0); // 0
showCount(null); // unknown
showCount(); // unknown
Q. Is "else" required? - Will the function work differently if else is removed?
function checkAge(age) {
if (age > 18) {
return true;
} else {
// ...
return confirm('Did parents allow you?');
}
}
function checkAge(age) {
if (age > 18) {
return true;
}
// ...
return confirm('Did parents allow you?');
}
Q. Rewrite the function using '?' or '||'
function checkAge(age) {
if (age > 18) {
return true;
} else {
return confirm('Did parents allow you?');
}
}
// my soln(1) - using '?'
function checkAge(age) {
(age > 18) ? return true : return confirm('Did parents allow you?');
}
// my soln(1) - using '||'
function checkAge(age) {
(age > 18)
|| return confirm('Did parents allow you?');
}
// Solution in expected format - using '?'
function checkAge(age) {
return (age > 18) ? true : confirm('Did parents allow you?');
}
// Solution in expected format - using '||'
function checkAge(age) {
return (age > 18) || confirm('Did parents allow you?');
}
Q. Function min(a, b)-Write a function min(a,b) which returns the least of two numbers a and b.
For instance:
min(2, 5) == 2
min(3, -1) == -1
min(1, 1) == 1
// my soln
function min(a,b) {
if (a >= b){
return a;
}else{
return b;
}
}
// Solution in expected format
function min(a, b) {
if (a < b) {
return a;
} else {
return b;
}
}
function min(a, b) {
return a < b ? a : b;
}