javascript - javascript code - javascript example

Javascript Examples: An Overview of Udacity’s Javascript Code

Javascript is one of Udacity’s most useful language resources when you want to learn about web development. Our Javascript hub contains many examples of Javascript code, but it might seem overwhelming to keep track of it all if you’re just starting out. That’s where this article comes in: a one-stop repository of Javascript examples.

Use this article to get a general idea of how Javascript works and to become familiar with its syntax. It also includes examples of JSON, a data exchange language modeled on some characteristics of Javascript. Every Javascript example contains a link back to a Udacity article that explains more about that Javascript code.

You can test these examples, and any example in Udacity’s Javascript articles, at Play Code.

Javascript Examples

All these Javascript examples are purposely kept simple; please see the linked articles for more detailed information.

For Loops

Javascript for loops examine every element in a collection of data. This Javascript code example prints out every element from a collection in order.

let array = "["a", "b", "c", 1, 2, 3];
for (let i = 0; i <= array.length; i++) {

If Else Statements

Javascript if else statements create branching logical flows through the program when a particular condition has been met. This Javascript code example prints out different strings depending on a number’s value.

if (x == 0) {
} else {

Switch Statements

Javascript switch statements determine whether an expression evaluates to one of many fixed values, then execute instructions based on that value. This Javascript code example simplifies color names to “ROYGBIV” notation.

let x = "Violet";
switch(x) {
    case "Red":
    case "Orange":
    case "Yellow":
    case "Green":
    case "Blue":
    case "Indigo":
    case "Violet":
        console.error("Not a color!");


Javascript functions create reusable blocks of code with specific names to prevent code duplication. This Javascript code example shows a simple function that converts temperatures in Fahrenheit to temperatures in Celsius.

function fToC(fahrenheit) {
    return (fahrenheit - 32) * 5 / 9;


Javascript arrays hold multiple valid Javascript variables in a single group. This Javascript code example shows an array that contains strings and numbers.

let arrayExample = ["yes", 1, "no", 2];

Array Methods

Javascript array methods provide complex functionality that manipulates array contents. There are many different array methods; please see the linked article for details. This Javascript code example shows the toString() method which converts an array to a string representation.

let arrayEx = ["A", "B", "C", 1, 2, 3];
let arrayExString = arrayEx.toString();  // A,B,C,1,2,3

Output and Printing

Javascript output and printing happens when output is sent to a browser’s developer console or when Javascript changes the contents of a web page dynamically. This Javascript code example shows messages, warnings, and errors being printed to the developer console.

let object = {"a": 1, "b": 2};
console.log("message: " + object);

let alert = "Potential problem!";
console.warn("warning: " + warning);

let errorCode = 2;
console.error("error: " + errorCode);

Try Catch Statements

Javascript try catch statements manage runtime errors in a Javascript program. This Javascript code example shows a try catch statement that prevents an error from stopping a program.

let x = 0;
try {
    x = Number.parseInt("CantParseThis");
} catch (err) {
    x = 0;


Javascript operators evaluate the ways variables and expressions are related to each other. This Javascript code example demonstrates the “greater than” and “less than or equal to” operators.

x > 8
x <= 10

Document Object Model (DOM)

The Document Object Model (DOM) describes how Javascript interacts with the underlying HTML and CSS of a web page. This Javascript code example shows how to use the document to dynamically set a doctype.

document.doctype = "doctype html";


Javascript objects contain properties and methods in a reusable container that allows developers to implement complex functionality with minimal code. This Javascript example illustrates an object containing a property and a method.

let example1 = {
    color: "purple",
    smile: function() { console.log("Hi " + color); }


Javascript timers, also known as wait functions, give developers the ability to purposely pause code execution for a specified amount of time. This Javascript code example shows a function being run after a delay of 2000 milliseconds (2 seconds).

function delayedFunction(a, b) { // after delay, a personalized "Hi"
    console.log("Hi " + a + " " + b + "!");
// Run delayedFunction() after a 2000 millisecond (2 second) delay
let timer = setTimeout(delayedFunction, 2000, "John", "Doe");

Random Numbers

Javascript random numbers are not truly random because computers rely on cause and effect to make computations, so they instead are “pseudo-random,” relying on internal calculations. This Javascript code example shows how to create a simple random number between 2 and 10.

// Generate a random number between 2 and 10, including both 2 and 10
function generateRandomIntegerInRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;

let num = generateRandomIntegerInRange(2, 10);

While Loops

Javascript while loops execute until their end condition becomes false, at which point code continues outside the loop. This Javascript code example shows a while loop that executes until the value of “X” is 1 or less.

let x = 10;
while (x > 1) {
    x = x - 1;


Javascript cookies are small text files stored on web servers that give the user a personalized experience when they visit a website. This Javascript code example shows a cookie on “” that expires on Halloween.

Expires=Thu, 31 Oct 2021 07:28:00 GMT

Date Formats

Javascript date formats may vary somewhat as the developer pleases, but Javascript uses ISO date formats internally, so developers should use that format if possible. This Javascript code example shows a selection of Javascript date and datetime ISO formats.

let completeDate = new Date("2021-01-01");
let yearMonth = new Date("2021-01");
let yearOnly = new Date("2021");
let dateTimeUTC = new Date("2021-01-01T12:00:00Z");
let dateTimeEST = new Date("2021-01-01T12:00:00-04:00");


The Javascript Window.location object lets developers manage browser addresses and obtain information about their properties. This Javascript code example prints out an initial page address,, then navigates to the Udacity home page using window.location.href.

window.location.href = "";


Javascript comments provide a way to explain what is happening within code using plain language. This Javascript code example shows a comment that spans multiple lines.

This is a multiline comment
that can span as many lines
as you have the patience to
compose for your future self.

Data Types

Javascript data types are the distinct kinds of information that Javascript supports: nine as of 2020. This Javascript code example shows the string, number, and BigInt data types.

let exampleString = "1";  // the text string "1"
let exampleNumber = 1;    // the number 1
let exampleBigInt = 1n;   // the BigInt 1

Popup Windows

Javascript popup windows let the user know that something needs their attention on a web page, but it’s important not to overuse them. This Javascript code example shows the two different ways to create the most common type of popup window: an alert box.

window.alert("This is an alert.");
alert("This is an alert too!");


Javascript booleans are true or false values used to control logical decisions in program flow. This Javascript code example shows the preferred way to create boolean variables.

let trueVal = true;
let falseVal = false;

The Script Tag

The script tag is the correct way to add Javascript to HTML, either as short snippets or as links to larger code pieces. This Javascript code example shows Javascript as a snippet inside a script tag and as a longer piece linked through the script tag.

document.write("This is a snippet!");
<script src=""></script>

Break and Continue Statements

The Javascript break and continue statements halt execution of Javascript loops and control structures before they would normally complete. This Javascript code example demonstrates a loop that uses the Javascript break and continue statements together.

for (let i = 1; i <= 5; i++) {
    if (i % 4 == 0) { continue; }
    if (i >= 4) { break; }


Javascript variables are containers for data values. This example shows the three valid ways to define variables in JavaScript.

var myVar1;
let myVar2;
const myVar3 = 1;

String Methods

Javascript string methods perform complex manipulations of JavaScript strings like substring creation. This JavaScript code example shows the most recently added string methods that pad the beginning and end of strings.

let exampleA = "1";
let exampleB = exampleA.padStart(4,"a");  // "aaa4"
let exampleC = exampleB.padEnd(5, "b");   // "5bbbb"

Javascript CSS

Manipulating CSS with JavaScript is useful for changing the styling of dynamic components. This JavaScript code example demonstrates JavaScript changing CSS to make part of a web page visible or invisible on a button click.

let button = document.createElement('button');

button.addEventListener('click', event => {
    let myDiv = document.getElementById("myDiv");
    if ( === "none") {
        document.getElementById("myDiv").style.display = "block";
    } else {
        document.getElementById("myDiv").style.display = "none";

JSON Examples

All these JSON examples are purposely kept simple; please see the linked articles for more detailed information.


The JSON.parse() function converts JSON objects into Javascript objects. This Javascript code example converts a simple JSON object with two key-value pairs into a Javascript object.

let json = '{"a": 1, "b", 2}';<
let object = JSON.parse(json);


The JSON.stringify() function converts Javascript objects into JSON objects. This Javascript code converts a simple JSON string into a Javascript object containing three key-value pairs.

let object = {"a": 1, "b", 2, "c", 3};
let json = JSON.stringify(object);

JSON Arrays

JSON arrays are simpler than Javascript arrays because they are static and can hold fewer data types. This Javascript code example shows a simple JSON array with 2 dimensions.

    ["A", "B", "C", "D"],
    ["E", "F", "G", "H"],
    ["I", "J", "K", "L"]

JSON Objects

JSON objects are simpler than Javascript objects because they are static and can hold fewer data types. This Javascript code example shows a JSON object with a nested object inside.

    "A": "B",
    "C": "D",
    "E": {
        "AA": 1,
        "AB": 2


Javascript examples can help you get a handle on new Javascript concepts without needing to read through technical information first. They’re a great springboard to dive deeper into Javascript code studies.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript code and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni