Technology

Useful, Visually Appealing, and Performance-Optimized JavaScript Examples

Discover practical, visually impressive, and performance-optimized examples of JavaScript usage, including ternary operations, conditional assignments, and tips for fast execution.

Sangrak

JavaScript is rich with unique and useful syntax options.

Visually Appealing Examples

Ternary Operators and Conditional Assignment

var value;

// Method 1
if (n) value = n;
else value = 1;

// Method 2
var value = n ? n : 1;

// Method 3
var value = n || 1;

Conditional Function Calls

// Method 1
if (callback) {
	callback();
}

// Method 2
callback && callback();

Examples with Fast Execution

Using Array Construction and Concatenation Over Arithmetic (+) Operation

var result = 'a' + 'b' + 'c' + 'd';

var result = ['a', 'b', 'c', 'd'].join('');

Iterating Over Arrays More Efficiently

To avoid repeatedly calculating nodes.length:

// Instead of this...
function nodeJam(){
	nodes = document.getElementsByTagName('P');
	
	for (var i = 0; i < nodes.length; i++) {
		nodes[i].innerHTML += 'test';
	}
}

// This is much faster
function nodeJam(){
	nodes = document.getElementsByTagName('P');

	for (var i = 0, len = nodes.length; i < len; i++) {
		nodes[i].innerHTML += 'test';
	}
}

Extracted from Sexy JavaScript Coding Conventions (Firejune).