Skip to content

Instantly share code, notes, and snippets.

@LGitHub-sprout
Last active January 20, 2023 10:43
Show Gist options
  • Save LGitHub-sprout/3b94f2a10f2d0c48f02833e1cb129f4a to your computer and use it in GitHub Desktop.
Save LGitHub-sprout/3b94f2a10f2d0c48f02833e1cb129f4a to your computer and use it in GitHub Desktop.
JavaScript.info – JS Fundementals; Conditionally declare a function; Callbacks; Function expressions; Function Params, Arrow Funcs
// Wes: Arrow Functions - convert to arrow function
function inchesToCM(inches) {
const cm = inches * 2.54;
return cm; // 17.78
}
// First convert to anon func:
const inchestoCM2 = function (inches) { return +inches * 2.54 };
// Second, convert to arrow func
// variable = (args) => expression;
const inchestoCM3 = inches => inches * 2.54; // implied return
// Wes: Arrow Functions - convert to arrow function
// Repeat but with two params
function addAB(a, b = 666) {
const sum = a + b;
return sum;
}
// Convert to anon function first
// Then convert to arrow function
// define a function called checkAge and pass a param, age
// if age is greater than or equal to 18, return true
// otherwise, return a confirm msg 'Do you have permission from your parents?'
// assign age a prompt msg 'How old are you?' and pass in 18
// write a conditional using checkAge function to send an alert 'Access granted' or 'Access denied' depending on age.
function checkAge(age) {
if (age >= 18) return true;
return false;
}
const age = prompt('Enter your age');
if (checkAge(age)) {
alert('Welcome to the Party!');
} else {
alert('We need a permission slip from your parents to get in.');
}
// Simple function expression: saving function as const variable
const sayHi = function() {
alert('Well... Hello!');
}; // Notice the semi-colon at end of entire stmt
// Can copy functions into variables
function copyMe() {
alert('Help! I\'ve been COPIED Lol');
}
const makinCopies = copyMe;
// Arrow Functions
// https://javascript.info/arrow-functions-basics#summary
// If the response 'confirmation' to question is yes, run yes() else run no()
// Invoke ask using ternary operator and arrow function
function ask(question, yes, no) {
if (confirm(question)) yes();
else no();
}
ask('OK to confirm, otherwise Cancel.',
() => { alert('Thank you for your confirmation.'); },
() => { alert('We\'re sorry you\'ve canceled but hope to have you back soon!'); }
);
let age = prompt("What is your age?", 18);
let welcome; // init the variable outside conditional stmt to change scope
// Conditionally declare a function
if (age < 18) {
welcome = function () {
alert("Sweetie, you\'re not over 18.");
}
} else {
welcome = function () {
alert("Greetings, old timer :)!");
}
}
welcome();
// My solution using ternary operator w/out function expression, function declaration
let age = prompt('Please enter your age', 0);
let welcome = age < 18 ? alert('Sorry, you aren\'t old enough') : alert('Hi! What would you like to drink?');
// https://www.javascripttutorial.net/es6/javascript-default-parameters/
// Test for an undefined parameter value and assign one if none using ternary operator.
function salutation(text) {
text = typeof text === 'undefined' ? 'Dear Krista:' : text;
console.log(text);
}
function salutation('To Whom It May Concern: ');
salutation();
// Can be rewritten using default params:
function shippedMsg(status = 'Your order has been shipped.') {
console.log(status);
}
shippedMsg(); // Uses default which is same as 'undefined'
// argument is used when CALLING the function
shippedMsg('Item is backordered and will be shipped when available.');
shippedMsg(undefined); // undefined uses default param
// Noodling around w function passing function as param
function showMessage(from, text = textFunction()) {
// console.log(from, text); // All Tests
// return message = from + text; // No tests yet.
return `${from}: ${text}`; // A Series Test
}
function textFunction() {
// return 'This is the callback function message.'; // First test
// text = 'This is the callback function message.'; // Second Test
return text = 'This is the callback function message.'; // Third Test
// console.log('This is the callback function message.') //
}
// First test:
// showMessage('Lester: ', whateverVar = 'Text here.'); // Lester:: Text here.
// showMessage('Lester: ', 'Message!'); // Lester: Message!
// showMessage('Lester: ', undefined); // Lester: This is the callback function message.
// Second Test:
// showMessage(undefined, text); // text is not defined Uncaught RefError
showMessage(undefined, text = 'Poop'); // undefined Poop
showMessage('Lester:', text = 'Message of hope.'); // Lester: Message of hope.
showMessage('Lester:', 'Message of hope.'); // Lester: Message of hope.
showMessage('Lester:', undefined); // Lester: undefined
// Third Test:
// showMessage(undefined, text); // text is not defined Uncaught RefError
// showMessage(undefined, text = 'Tom Papa Podcast'); // undefined Tom Papa Podcast
// showMessage(undefined, undefined); // undefined This is the callback function message.
// showMessage(undefined, 'A message'); // undefined This is the callback function message.
// A Series Test:
// console.log(showMessage()) // undefined: This is the callback function message.
console.log(showMessage('Lester', undefined)) // Lester: This is the callback function message.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#function_body
// const wontWork = () => { foo: 'Text string' };
// console.log(wontWork()); // undefined
// Use parentheses around object literal
// const thisWorks = () => ({ foo: 1 }); // returns {foo: 1}
// console.log(thisWorks().foo); // returns number 1
// const thisWorks = () => ({ foo: function () { console.log('boo') } }); // returns 'boo'
// thisWorks().foo(); // returns 'boo'
// const thisWorks = () => ({ foo: function whatevs() { return 'boo' } }); // return {foo: 1}
// console.log(thisWorks().foo()); // returns 'boo'
const anObject = {
i: 10,
b: () => console.log(this.i, this),
c: function whatevs() {
return this.i + 666; // returns '676' when logging object property, see below
// console.log(this.i + 1); // logs 676
},
// c() {
// console.log(this.i, this, 'use addition', this.i + 1);
// },
};
// anObject.b(); // undefined, window object
// console.log(anObject.c()); // 676
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#no_binding_of_arguments
// This seems like a future 'gotcha' for me. Hope I can find it later :/
const args = [1, 2, 3];
const getArgs = () => args[2];
// console.log(getArgs()); // 3
// Can use 'rest parameters' in most cases.
function add(n) {
const f = (...args) => args[0] + n;
return f(10);
}
console.log(add(0));
const birthYear = a => '19' + a;
// console.log('birthYear', birthYear('66')); // birthYear 1966
// console.log((a)); // Reference Error a is not defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment