JavaScript/Helpful hints

From Wikibooks, open books for an open world
Jump to navigation Jump to search



Predefined functions[edit | edit source]

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 | edit source]

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 | edit source]

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 | edit source]

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

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

prompt()[edit | edit source]

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 | edit source]

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

Coding style[edit | edit source]

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 | edit source]

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) {
  ...
} //