Skip to content

Instantly share code, notes, and snippets.

@jonaskahn
Last active March 6, 2023 15:42
Show Gist options
  • Save jonaskahn/42ec372d8e8d25a4017c920a39b2be02 to your computer and use it in GitHub Desktop.
Save jonaskahn/42ec372d8e8d25a4017c920a39b2be02 to your computer and use it in GitHub Desktop.

Function declare

function showMessage(from, text) { // parameters: from, text
  alert(from + ': ' + text);
}

showMessage('Ann', 'Hello!'); // Ann: Hello! (*)
showMessage('Ann', "What's up?"); // Ann: What's up? (**)

Parameters

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
  • Javascript pass by reference and value

Default values

function showMessage(from, text = "no text given") {
  alert( from + ": " + text );
}

showMessage("Ann");
showMessage("Ann", null);
showMessage("Ann", undefined);

Returning a value

function sum(a, b) {
  return a + b;
}

let result = sum(1, 2);
alert( result ); // 3

Function naming:

  • A name should clearly describe what the function does. When we see a function call in the code, a good name instantly gives us an understanding what it does and returns.
  • A function is an action, so function names are usually verbal.
  • There exist many well-known function prefixes like create…, show…, get…, check… and so on. Use them to hint what a function does.

function callable(a, f) {
    if (a == null) { 
        f()
    }
}

callable(null, function () { 
    alert("yahoooo")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment