Javascript Tutorial 05 Variables

A variable declared without a value will have the value undefined.

The variable carName will have the value undefined after the execution of this statement:

var carName;

If you re-declare a JavaScript variable, it will not lose its value.

The variable carName will still have the value “Volvo” after the execution of these statements:

var carName = "Volvo";
var carName;

Javascript Tutorial 04 Statements

On the web, you might see examples without semicolons. Ending statements with semicolon is not required, but highly recommended.

For best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it, is after an operator:

document.getElementById("demo").innerHTML =
"Hello Dolly!";

You can also break up a code line within a text string with a single backslash:

document.getElementById("demo").innerHTML ="Hello \
Dolly!";

The \ method is not the preferred method. It might not have universal support. Some browsers do not allow spaces behind the \ character.

A safer way to break up a string, is to use string addition:

document.getElementById("demo").innerHTML ="Hello" +
"Dolly!";

Javascript Tutorial 03 Output

JavaScript can “display” data in different ways:

  1. Writing into an HTML element, using innerHTML.

    Changing the innerHTML property of an HTML element is a common way to display data in HTML.

  2. Writing into the HTML output using document.write().
    • Using document.write() after an HTML document is fully loaded, will delete all existing HTML.

      The document.write() method should only be used for testing.

  3. Writing into an alert box, using window.alert().
  4. Writing into the browser console, using console.log().
    • For debugging purposes, you can use the console.log() method to display data.