JavaScript

From HaFrWiki
Jump to: navigation, search

Always I can not find a pleasant and good reference/example of JavaScript code [1], but constant searching helps [2].

Documentation[edit]

Not a beginners guide and note a reference. JavaScript Garden (Bonsai Garden) is a growing collection of documentation about the most quirky parts of the JavaScript programming language. It gives advice to avoid common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert JavaScript programmers may encounter on their endeavours into the depths of the language. [2]

JavaScript Garden does not aim to teach you JavaScript. Former knowledge of the language is strongly recommended in order to understand the topics covered in this guide. In order to learn the basics of the language, please head over to the excellent guide on the Mozilla Developer Network.

Cookies[edit]

See for a description on how to cope with JavaScript Cookies

FAQ[edit]

My personal list of FAQ's.

Javascript function Name[edit]

How to het the function name of the function you are in. [3]

  • Use: arguments.callee.name
  • Example (code snippet):

<syntaxhighlight lang="javascript"> var logFormatLBW = '[%-25.25s] - %-15s %s';

function getTail() {

 ...
 m = arguments.callee.name; 
 console.log(sprintf( logFormatLBW, m, 'callee'  , arguments.callee.name));

</syntaxhighlight>

Default parameter[edit]

Is it possible to have a function with a default parameter?

  • Yes, see example.

<syntaxhighlight lang="javascript"> /** Does something foo... @param string optionalParameter [Optional] option for .... [default: ""]

  • /

function foo( optionalParameter ) {

  var option = typeof optionalParameter !== 'undefined' ? optionalParameter : "";

} </syntaxhighlight>

Check existence of variable[edit]

Can you check on the existence of a variable/object?

  • Yes, see example

<syntaxhighlight lang="javascript"> if ( somecondition) {

   var newObject = { name: "myname", ... };

}

if ( typeof newObject !== 'undefined') {

  newObject.method();

} </syntaxhighlight> The above will check whether foo was actually declared or not; just referencing it would result in a ReferenceError. This is the only thing typeof is actually useful for.

Links[edit]

Redirector[edit]

use the lcation object. An example:

<html>
<title>CodeAve.com (JavaScript: Current Page URL)</title>
<body bgcolor="#FFFFFF">
...
<script language="JavaScript">
<!-- 
  document.write (location.href);
  document.write ("<p><a href='" +location.href + "'>Link To Current Page</a></p>");
// -->
</script>
...
</body>
</html>

Javascript asynchronous[edit]

The asynchronous behaviour of Javascript is well known, but not very good understood by all the developers and users.
Therefore a small explanation with examples to describe the different opportunities and possibilities.

Assuming the following problem:

Synchronous Asynchronous

<syntaxhighlight lang="javascript" line start="1"> function findItem() {

   var item;
   while(item_not_found) {
       // search
   }
   return item;

}

var item = findItem();

// Do something with item doSomethingElse(); </syntaxhighlight> Even though findItem might take a long time to execute, any code coming after var item = findItem(); has to wait until the function returns the result.

<syntaxhighlight lang="javascript" line start="1"> findItem(function(item) {

   // Do something with item

}); doSomethingElse(); </syntaxhighlight> Instead of waiting for the response, the execution continues immediately and the statement after the Ajax call is executed.
To get the response eventually, you provide a function to be called once the response was received, a callback (notice something? call back ?).
Any statement coming after that call is executed before the callback is called.

Callback[edit]

A callback is simply a function passed to another function.
That other function can call the function passed whenever it is ready.
In the context of an asynchronous process, the callback will be called whenever the asynchronous process is done.
Usually, the result is passed to the callback.

Simple callback with Ajax Another example using Ajax

<syntaxhighlight lang="javascript" line start="1"> // Replaces the code 'var result = foo();' foo(function(result) {

   // Code that depends on 'result'

});

// Defines the function "inline" but you can pass any function reference: function myCallback(result) {

   // Code that depends on 'result'

}

foo(myCallback);

function foo(callback) {

   $.ajax({
       // ...
       success: callback
   });

}

// Or as alternative: function foo(callback) {

   $.ajax({
       // ...
       success: function(response) {
           // For example, filter the response
           callback(filtered_response);
       }
   });

} </syntaxhighlight> See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323

<syntaxhighlight lang="javascript" line start="1"> // 1. Call helloCatAsync passing a callback function, // which will be called receiving the result from the async operation helloCatAsync(function(result) {

   // 5. Received the result from the async function,
   //    now do whatever you want with it:
   alert(result);

});

// 2. The "callback" parameter is a reference to the function which // was passed as argument from the helloCatAsync call function helloCatAsync(callback) {

   // 3. Start async operation:
   setTimeout(function() {
       // 4. Finished async operation,
       //    call the callback passing the result as argument
       callback('Nya');
   }, Math.random() * 2000);

} </syntaxhighlight> See https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron


Promises or Futures[edit]

There are 2 versions: - Promises with asyn/await - Promises with then()

with asyn/await[edit]

Defined in EcmaScript 2017+ and available in all major browsers (Chrome 55, Safari 10.1+, so not on the first mark iPads).

with then()[edit]

Defined in EcmaScript 2015+ and available in all major browsers (Chrome 32, Safari 8+, so not on the first mark iPads).

See also[edit]

Reference[edit]

top

  1. JavaScriptKit, Index, Tutorials and Reference. This is a very good start.
  2. 2.0 2.1 Bonsai Garden, Javascript Examples, Best practices and tutorials.
  3. Kangax, Named function expressions demystified.