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++) {
    console.log(array[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) {
    console.log("None");
} else {
    console.log("Some");
}

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":
        console.log("R");
        break;
    case "Orange":
        console.log("O");
        break;
    case "Yellow":
        console.log("Y");
        break;
    case "Green":
        console.log("G");
        break;
    case "Blue":
        console.log("B");
        break;
    case "Indigo":
        console.log("I");
        break;
    case "Violet":
        console.log("V");
        break;
    default:
        console.error("Not a color!");
        break;
}

Functions

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;
}

Arrays

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;
}

Operators

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";

Objects

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); }
}

Timers

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;
}

Cookies

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

Domain=http://www.example.com
Path=cookie_folder
Expires=Thu, 31 Oct 2021 07:28:00 GMT

JSON Examples

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

JSON.parse()

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);

JSON.stringify()

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
    }
}

Conclusion

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