Skip to content

Instantly share code, notes, and snippets.

@58bits
Created October 6, 2015 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 58bits/507abc0034f561e24811 to your computer and use it in GitHub Desktop.
Save 58bits/507abc0034f561e24811 to your computer and use it in GitHub Desktop.
importPackage(java.io);
importPackage(java.lang);
System.out.println("JavaScript!");
// create some variables to use
// TERM: assignment
var a = 1;
var b = 2;
var c = 3;
var d = 4;
var e = 5;
// total the numbers
// TERM: operation, operators
var total = a + b + c + d + e;
// variable to indicate if we should System.out.println the total
var should_print_total = true;
// output the total (if the variable is set)
// TERM: concatenation, conditional, boolean, coercion, control flow
if(should_print_total) {
System.out.println("The total is " + total.toString() + "\n");
}
// output the total if it is equal to
if (total === 15) {
System.out.println("The total was 15 just like we wanted\n");
}
// create a list of numbers
// TERM: list, array
var list = [a, b, c, d, e];
// how many numbers do we have?
// TERM: method, interpolation
var count = list.length;
System.out.println("There are " + count + " numbers in the list");
// output each number
// TERM: iteration, interpolation
list.forEach(function(value, index, array) {
System.out.println("The number " + value + " is at index " + index + " in the list");
});
// are the numbers even or odd?
// TERM: iteration, branching logic (with else), (danger: scope of i is global)
for (var i=0; i < list.length; i++) {
if (list[i] % 2 == 0) {
System.out.println(list[i] + " is even");
} else {
System.out.println(list[i] + " is odd");
}
}
// is there a quicker way to get the total? in this language?
// TERM: reduce, method, interpolation
total = list.reduce(function(a, b) {
return a + b;
});
System.out.println("The total is " + total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment