Skip to content

Javascript

Javascript is a scripting language designed to manipulate the DOM of a web page. Over time through projects such as node.js, Javascript has been redefined to become more of a fully-fledged programming language. Through tools such as Electron, desktop applications can be written using Javascript. There also exists a number of languages which are designed to compile to Javascript, such as the type-safe TypeScript, Coffeescript, or Kotlin. Despite its rather suggestive name, it has nothing to do with the programming language Java.

Example

The following is an implementation of the Caesar Cipher in Javascript.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var caesar = {};

var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

caesar.cipher = function(input, shift) {
    var result = '';

    for (var i = 0; i < input.length; i++) {
        var isUpperCase = input[i] === input[i].toUpperCase();
        if (contains(alphabet, input[i].toUpperCase())) {
            var position = alphabet.indexOf(input[i].toUpperCase()) + Math.floor(shift);
            if (position > 25) {
                position -= 26;
            }
            if (isUpperCase) {
                result = result.concat(alphabet[position]);
            } else {
                result = result.concat(alphabet[position].toLowerCase());
            }
        } else {
            result = result.concat(input[i]);
        }
    }

    return result;
}

caesar.decipher = function(input, shift) {
    return caesar.cipher(input, 26 - shift);
}

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Mozilla Public License 2.0.