Simple examples
Variables in JavaScript can be defined using either the var, let or const keywords.
// Declares a function-scoped variable named `x`, and implicitly assigns the
// special value `undefined` to it. Variables without value are automatically
// set to undefined.
var x;
// Variables can be manually set to `undefined` like so
var x2 = undefined;
// Declares a block-scoped variable named `y`, and implicitly sets it to
// `undefined`. The `let` keyword was introduced in ECMAScript 2015.
let y;
// Declares a block-scoped, un-reassign-able variable named `z`, and sets it to
// a string literal. The `const` keyword was also introduced in ECMAScript 2015,
// and must be explicitly assigned to.
// The keyword `const` means constant, hence the variable cannot be reassigned
// as the value is `constant`.
const z = "this value cannot be reassigned!";
// Declares a variable named `myNumber`, and assigns a number literal (the value
// `2`) to it.
let myNumber = 2;
// Reassigns `myNumber`, setting it to a string literal (the value `"foo"`).
// JavaScript is a dynamically-typed language, so this is legal.
myNumber = "foo";
Note the comments in the example above, all of which were preceded with two forward slashes. There is no built-in Input/output functionality in JavaScript; the run-time environment provides that. The ECMAScript specification in edition 5.1 indeed, there are no provisions in this specification for input of external data or output of computed results.
Data Types in JavaScript
These are data types in JavaScript:
- undefined
- null
- boolean
- string
- bigint
- number
- object
Console Object
However, most runtime environments have a console object that can be used to print output. Here is a minimalist Hello World program in JavaScript:
console.log("Hello World!");
Recursive Function
A simple recursive function:
function factorial(n) {
if (n === 0)
return 1; // 0! = 1
return n * factorial(n - 1);
}
factorial(3); // returns 6
Anonymous Function
An anonymous function (or lambda):
function counter() {
let count = 0;
return function() {
return ++count;
};
}
let closure = counter();
closure(); // returns 1
closure(); // returns 2
closure(); // returns 3
This example shows that, in JavaScript, function closures capture their non-local variables by reference.
Arrow Functions
Arrow functions were first introduced in 6th Edition - ECMAScript 2015. They shorten the syntax for writing functions in JavaScript. Arrow functions are anonymous in nature; a variable is needed to refer to them in order to invoke them after their creation.
Example of arrow function:
// Arrow functions let us omit the `function` keyword. Here `long_example`
// points to an anonymous function value.
const long_example = (input1, input2) => {
console.log("Hello, World!");
const output = input1 + input2;
return output;
};
// Arrow functions also let us automatically return the expression to the right
// of the arrow (here `input + 5`), omitting braces and the `return` keyword.
const short_example = (input,input2) => input + input2;
long_example(2, 3); // Prints "Hello, World!" and returns 5.
short_example(2, 5); // Returns 7.
// If an arrow function only has one parameter, the parenthesis can be removed.
const no_parenthesis = input => input + 2;
no_parenthesis(3); // Returns 5.
Objects in JavaScript
In JavaScript, objects are created in the same way as functions; this is known as a function object.
Object example:
function Ball(r) {
this.radius = r; // the radius variable is local to the ball object
this.area = Math.PI * r ** 2;
this.show = function(){ // objects can contain functions
drawCircle(r); // references a circle drawing function
}
}
let myBall = new Ball(5); // creates a new instance of the ball object with radius 5
myBall.radius++; // properties exposed with "this" can be modified from the outside
myBall.show(); // this instance of the ball object has the show function performed on it
Variadic Function
Variadic function demonstration (arguments is a special variable):[63]
function sum() {
let x = 0;
for (let i = 0; i < arguments.length; ++i)
x += arguments[i];
return x;
}
sum(1, 2); // returns 3
sum(1, 2, 3); // returns 6
Immediately Invoked Function Expressions
Immediately-invoked function expressions are often used to create modules; before ECMAScript 2015 there was no built-in module construct in the language. Modules allow gathering properties and methods in a namespace and making some of them private:
let counter = (function() {
let i = 0; // private property
return { // public methods
get: function() {
alert(i);
},
set: function(value) {
i = value;
},
increment: function() {
alert(++i);
}
};
})(); // module
counter.get(); // shows 0
counter.set(6);
counter.increment(); // shows 7
counter.increment(); // shows 8
Exporting and Importing Modules
Exporting and Importing modules in JavaScript.
/* mymodule.js */
// This function remains private, as it is not exported
let sum = (a, b) => {
return a + b;
}
// Export variables
export let name = 'Alice';
export let age = 23;
// Export named functions
export function add(num1, num2){
return num1 + num2;
}
// Export class
export class Multiplication {
constructor(num1, num2) {
this.num1 = num1;
this.num2 = num2;
}
add() {
return sum(this.num1, this.num2);
}
}
Import example:
// Import one property
import { add } from './mymodule.js';
console.log(add(1, 2)); // 3
// Import multiple properties
import { name, age } from './mymodule.js';
console.log(name, age);
//> "Alice", 23
// Import all properties from a module
import * from './module.js'
console.log(name, age);
//> "Alice", 23
console.log(add(1,2));
//> 3
More Advanced Example
This sample code displays various JavaScript features.
/* Finds the lowest common multiple (LCM) of two numbers */
function LCMCalculator(x, y) { // constructor function
let checkInt = function(x) { // inner function
if (x % 1 !== 0)
throw new TypeError(x + "is not an integer"); // var a = mouseX
return x;
};
this.a = checkInt(x)
// semicolons ^^^^ are optional, a newline is enough
this.b = checkInt(y);
}
// The prototype of object instances created by a constructor is
// that constructor's "prototype" property.
LCMCalculator.prototype = { // object literal
constructor: LCMCalculator, // when reassigning a prototype, set the constructor property appropriately
gcd: function() { // method that calculates the greatest common divisor
// Euclidean algorithm:
let a = Math.abs(this.a), b = Math.abs(this.b), t;
if (a < b) {
// swap variables
// t = b; b = a; a = t;
[a, b] = [b, a]; // swap using destructuring assignment (ES6)
}
while (b !== 0) {
t = b;
b = a % b;
a = t;
}
// Only need to calculate GCD once, so "redefine" this method.
// (Actually not redefinition—it's defined on the instance itself,
// so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd.
// Note that this leads to a wrong result if the LCMCalculator object members "a" and/or "b" are altered
afterwards.)
// Also, 'gcd' === "gcd", this['gcd'] === this.gcd
this['gcd'] = function() {
return a;
};
return a;
},
// Object property names can be specified by strings delimited by double (") or single (') quotes.
lcm: function() {
// Variable names do not collide with object properties, e.g., |lcm| is not |this.lcm|.
// not using |this.a*this.b| to avoid FP precision issues
let lcm = this.a / this.gcd() * this.b;
// Only need to calculate lcm once, so "redefine" this method.
this.lcm = function() {
return lcm;
};
return lcm;
},
toString: function() {
return "LCMCalculator: a = " + this.a + ", b = " + this.b;
}
};
// Define generic output function; this implementation only works for Web browsers
function output(x) {
document.body.appendChild(document.createTextNode(x));
document.body.appendChild(document.createElement('br'));
}
// Note: Array's map() and forEach() are defined in JavaScript 1.6.
// They are used here to demonstrate JavaScript's inherent functional nature.
[
[25, 55],
[21, 56],
[22, 58],
[28, 56]
].map(function(pair) { // array literal + mapping function
return new LCMCalculator(pair[0], pair[1]);
}).sort((a, b) => a.lcm() - b.lcm()) // sort with this comparative function; => is a shorthand form of a
function, called "arrow function"
.forEach(printResult);
function printResult(obj) {
output(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());
}
The following output should be displayed in the browser window.
LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56
LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168
LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275
LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638