JavaScript

From HaFrWiki42
Jump to navigation Jump to search

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

Documentation

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

See for a description on how to cope with JavaScript Cookies

FAQ

My personal list of FAQ's.

Javascript function Name

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

  • Use: arguments.callee.name
  • Example (code snippet):
var logFormatLBW  = '[%-25.25s] - %-15s %s';

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

Default parameter

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

  • Yes, see example.
/**
Does something foo...
@param string optionalParameter [Optional] option for .... [default: ""]
*/
function foo( optionalParameter ) {
   var option = typeof optionalParameter !== 'undefined' ? optionalParameter : "";
}

Check existence of variable

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

  • Yes, see example
if ( somecondition) {
    var newObject = { name: "myname", ... };
}

if ( typeof newObject !== 'undefined') {
   newObject.method();
}

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

Redirector

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

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
function findItem() {
    var item;
    while(item_not_found) {
        // search
    }
    return item;
}

var item = findItem();

// Do something with item
doSomethingElse();

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.

findItem(function(item) {
    // Do something with item
});
doSomethingElse();

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

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
// 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);
        }
    });
}

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

// 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);
}

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


Promises or Futures

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

with asyn/await

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

with then()

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

Clones and Deep copies

Since Javascript parses objects by reference to a function, changes made inside the function are kept!
Therefore make a deep copy of the object before offering the object to the function.
In fact make a deep copy and use that as function parameter.

The JSON.stringify() method takes in an object and creates a JSON string from it.
The JSON.parse() method parses a string and returns a JavaScript object.
We can combine both of these methods to create a copy of an object in the following way:

const user = {
    name: "Kingsley",
    age: 28,
    job: "Web Developer"
}
let clone = JSON.parse(JSON.stringify(user))
console.log(user)
console.log(clone)
/* 
{ 
age: 28, 
job: "Web Developer", 
name: "Kingsley" 
} 
{ 
age: 28, 
job: "Web Developer", 
name: "Kingsley" 
} 
*/

When the copy object is mutated, the original object stays the same:

clone.age = 32
console.log(user)
console.log(clone)
/* 
{ 
age: 28, 
job: "Web Developer", 
name: "Kingsley" 
} 
{ 
age: 32, 
job: "Web Developer", 
name: "Kingsley" 
} 
*/
  • TutPlus, Best way to deep copy an object in Javascript.

JS-Debugging

There are different ways to debug javascript.

  • raygun, Javascript debugging tips. The 16 JavaScript debugging tips you probably didn’t know.

See also

JavaScript W3S

  • W3Schools, JavaScript and HTML DOM Reference.

Reference

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.