JavaScript


This draft deletes the entire topic.

Examples

  • 238

    Almost all web browsers and JavaScript environments support writing messages to a console using a suite of logging methods. The most common of these is the console.log() method.


    Getting Started

    Open up the JavaScript Console in your browser, type the following, and press Enter:

    console.log("Hello, World!");

    Console Log Output in Google Chrome

    In the example above, the console.log() function prints Hello, World! to the console, along with a new line, and returns undefined (shown above in the console output window), because it has no explicit return value.

    The console.log() function is predominantly used for debugging purposes.


    Logging variables

    console.log() can be used to log variables of any kind, not only strings. Just pass the variable that you want to be displayed in the console, for example:

    var foo = "bar";
    console.log(foo);
    

    Will log in the console...

    console.log() can be used with variables

    If you want to log two or more values, simply separate them with commas:

    console.log("thisVar:", thisVar, "and that", thatVar);


    Logging Objects

    Below depicts the result of logging an object, which can be useful, for example, to log JSON responses received from an API call:

    console.log({'Email': '', 'Groups': {}, 'Id': 33, 'IsHiddenInUI': false, 'IsSiteAdmin': false, 'LoginName': 'i:0#.w|virtualdomain\\user2', 'PrincipalType': 1, 'Title': 'user2'});

    Will log in the console...

    Logging an object


    Logging Functions

    The console can also be used to show the return value of a function. In the example below, isNaN() will be executed and the value returned by this function will be shown in the console;

    Logging a result of a function

    console.log also has the ability to display function definitions by passing a non invoked instance of the function.

    var func = function(){console.log("hello from func");}
    console.log(func.toString());

    Will log to the console...

    Logging a non invoked function


    End Note

    For more information on the capabilities of the console, see the Console topic.

  • 70

    DOM stands for Document Object Model. It is an object-oriented approximation of structured documents like XML and HTML.

    Setting the textContent property of an Element is one way to output text on a web page.

    document.getElementById("paragraph").textContent = "Hello, World";
    
    Associated HTML:
    <p id="paragraph"></p>
    

    This will set the text content of the element that has the id paragraph to "Hello, World".

    View Demo

    Or, if you haven't yet defined the HTML element in your HTML page, you can create a new HTML element programmatically. In this example we are creating a new <p></p>:

    const element = document.createElement('p');
    element.textContent = "Hello, World";
    document.body.appendChild(element); //add the newly created element to the DOM
    

    If you're trying to manipulate elements (the DOM) using JavaScript, the JavaScript code must be run after the relevant element has been created in the document. This often means putting the JavaScript <script> tags after all of your other <body> content, or using event such as onload or jQuery's $(document).ready() to delay your code until after the page has loaded to execute the code once the document is ready.

  • 37

    The alert method displays a visual alert box on screen. The alert method parameter is displayed to the user in plain text.

    Syntax

    window.alert(message);
    

    or

    alert(message);
    

    Examples

    alert('hello, world');
    

    In Chrome, you would get a pop-up like this: alert result

    Notes

    The alert method is technically a property of window object, but since all window properties are automatically global variables, we can use alert as a global variable instead of as a property of window - meaning you can directly use alert() instead of window.alert().

    Unlike using console.log, alert acts as a modal prompt meaning that the code calling alert will pause until the prompt is answered. Traditionally this means that no other JavaScript code will execute until the alert is dismissed:

    alert('Pause!');
    console.log('Alert was dismissed');
    

    However the specification actually allows other event-triggered code to continue to execute even though a modal dialog is still being shown. In such implementations, it is possible for other code to run while the modal dialog is being shown.

    More information about usage of the alert method can be found in the modals prompts topic.

    The use of alerts is usually discouraged in favour of other methods that do not block users from interacting with the page - in order to create a better user experience. Nevertheless, it can be useful for debugging.

  • 14

    An easy way to get an input from a user is by using the prompt() method.

    Syntax

    prompt(text, [default])
    

    or

    window.prompt(text, [default])
    
    • text: The text displayed in the prompt box [Required]
    • default: A default value for the input field [Optional]

    Examples

    var age = prompt("How old are you?")
    console.log(age); // Prints the value inserted by the user
    

    Prompt box

    If the user clicks OK button, the input value is returned. Otherwise, the method returns null.

    Note: While the prompt box is displayed, the user is prevented from accessing other parts of the page.

  • 6

    Using canvas elements

    HTML provides the canvas element for building raster-based images.

    First build a canvas for holding image pixel information.

    var canvas = document.createElement('canvas');
    canvas.width = 500;
    canvas.height = 250;
    

    Then select a context for the canvas, in this case two-dimensional:

    var ctx = canvas.getContext('2d');
    

    Then set properties related to the text:

    ctx.font = '30px Cursive';
    ctx.fillText("Hello world!", 50, 50);
    

    Then insert the canvas element into the page to take effect:

    document.body.appendChild(canvas);
    

    Using SVG

    SVG is for building scalable vector-based graphics and can be used within HTML.

    First create an SVG element container with dimensions:

    var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.width = 500;
    svg.height = 50;
    

    Then build a text element with the desired positioning and font characteristics:

    var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
    text.setAttribute('x', '0');
    text.setAttribute('y', '50');
    text.style.fontFamily = 'Times New Roman';
    text.style.fontSize = '50';
    

    Then add the actual text to display to the textelement:

    text.textContent = 'Hello world!';
    

    Finally add the text element to our svg container and add the svg container element to the HTML document:

    svg.appendChild(text);
    document.body.appendChild(svg);
    

    Image file

    If you already have an image file containing the desired text and have it placed on a server, you can add the URL of the image and then add the image to the document as follows:

    var img = new Image();
    img.src = 'https://i.ytimg.com/vi/zecueq-mo4M/maxresdefault.jpg';
    document.body.appendChild(img);
    
  • 3

    Description

    The Window.confirm() method displays a modal dialog with an optional message and two buttons, OK and Cancel.

    Syntax

    result = window.confirm(message);
    
    • message is the optional string to be displayed in the dialog.
    • result is a boolean value indicating whether OK or Cancel was selected (true means OK).

    Examples

    Example 1

    For example, window.confirm can be used to ask for user confirmation before doing a dangerous operation like deleting something in a Control Panel.

    if(confirm("Are you sure you want to delete this?")) {
        deleteItem(itemId);
    }
    

    The Confirmation Dialog is very simple: Message, OK, Cancel

    Example 2

    You can store the the user's interaction result in a variable for later use, as well:

    var deleteConfirm = confirm("Are you sure you want to delete this?");
    

    Notes

    • The argument is optional and not required by the specification.

    • Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window). And regardless, there are very good reasons to avoid using dialog boxes for confirmation.

Please consider making a request to improve this example.

Remarks

JavaScript (not to be confused with Java) is a dynamic, weakly-typed language used for client-side as well as server-side scripting.

JavaScript is a case-sensitive language. This means the language considers capital letters to be different from their lowercase counterparts. Keywords in JavaScript are all lowercase.

JavaScript is a commonly referenced implementation of ECMAScript standard.

Topics in this tag often refer to the use of JavaScript within the browser, unless otherwise stated. JavaScript files alone can't be run directly by the browser; it's necessary to embed them in an HTML document. If you have some JavaScript code you'd like to try, you can embed it in some placeholder content like this, and save the result as example.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test page</title>
  </head>
  <body>
    Inline script (option 1):
    <script>
      // YOUR CODE HERE
    </script>
    External script (option 2):
    <script src="your-code-file.js"></script>
  </body>
</html>

Versions

VersionRelease Date
11997-06-01
21998-06-01
31998-12-01
E4X2004-06-01
52009-12-01
5.12011-06-01
62015-06-01
72016-06-14
82017-07-01
Still have a question about Getting started with JavaScript? Ask Question

Topic Outline