JavaScript/Helpful hints



Predefined functions

edit

All over the Wikibook, code examples are given. Usually, they show their results somewhere in the browser. This is done via methods that are aligned with Web API interfaces and implemented in browsers.

alert()

edit

The function alert() creates a modal window showing the given text.

let x = 5;
window.alert("The value of 'x' is: " + x); // explicit notation
alert("The value of 'x' is: " + x);        // short notation

log()

edit

The function log() writes the message to the console of the browser. The console is a window of the browser that is normally not opened. In most browsers, you can open the console via the function key F12.

let x = 5;
console.log("The value of 'x' is: " + x); // explicit notation
                                          // no short notation

print()

edit

The function print() opens the print dialog to print the current document.

window.print(); // explicit notation
print();        // short notation

prompt()

edit

The function prompt() opens a modal window and reads the user input.

let person = window.prompt("What's your name?"); // explicit notation
person = prompt("What's your name?");            // short notation
alert(person);

write()

edit

The use of document.write() is strongly discouraged.

Coding style

edit

Our code examples mostly contain the line "use strict"; before any other statement. This advises the compiler to perform additional lexical checks. He especially detects the use of variable names which are not been declared before they receive a value.

"use strict";
let happyHour = true;
hapyHour = false; //  ReferenceError: assignment to undeclared variable hapyHour

Without the "use strict"; statement the compiler would generate a second variable with the misspelled name instead of generating an error message.

Faulty visualization in some code examples

edit

Due to a minor fault in the Wikibook template quiz, you will see } // instead of } in some examples. The two slashes at the end are only shown to overcome this problem; they are not necessary.

// the two slashes in the last line are not necessary
if (x == 5) {
  ...
} //