JS statements
by AlexMM
JavaScript
// If
var name = 'Alex';
if (name === 'Alex') {
console.log('success');
} else if (name === 'Pepe') {
console.log('fail');
} else {
console.log('fail: no case found');
}
// For
var array = ['Alex', 'Pepe', 'Carlos'];
var i;
for (i = 0; i < array.length; i++) {
console.log(array[i]);
}
// Exceptions
try {
// Exception: there are some extra 'd's
//adddlert("Welcome guest!");
// How to throw an exception. It allows String, Number, Boolean or Object
// and what is thrown is what is caught in the "exception" parameter.
//throw "Too big"; // Throws a text
//throw 500; // Throws a number
//throw {firstName: "Alex", secondName: "Moros"}; // Throws an object
throw new Error('Some error happened!');
//throw new SyntaxError('Some error happened!');
//throw new DOMException('DOM exception!!!');
} catch (exception) {
if (exception instanceof SyntaxError) {
console.log('SyntaxError with name "' + exception.name + '" and message "' + exception.message + '"');
} else if (exception instanceof Error) {
console.log('Error with name "' + exception.name + '" and message "' + exception.message + '"');
} else {
console.log('Exception caught with following message: ' + exception);
}
} finally {
console.log('End of try-catch (allways executes)');
}