2015년 8월 30일 일요일

Javascript Block Scope, Falsy Value, Error Handling

Let's see javascript block scope( {...}), False values and throw, Error Handling statements. Learning test is written using Jasmine. Please refer Jasmine usage which I wrote before if you have interest it.

1. Javascript don't have Block Scope before ECMAScript6


it("donot have a block scope prior to ECMAScript6", function() {
var x = 1;
{
var x = 2;
}
expect(x).toBe(2);
});

2. Falsy value

false, undefined, 0, empty string(""), NaN are treated as a false.
it("Falsy value", function() {
var falsyAray = [false, undefined, 0, '', NaN];
for (x of falsyAray) {
expect((x? true:false)).toBe(false);
}
});

3. Throw expression, try - catch - finally

Javascript can throw any expression using "throw" keyword. The throwed expression can be used in catch statement like [line 15], [line 43]. You can see how to use try - catch -finally statements.
it("you may throw any expression, try - catch- finally", function() {
var throwFunc = function() {
throw "error";
}
expect(throwFunc).toThrow();
throwFunc = function() {
throw 42;
}
expect(throwFunc).toThrow();
try {
throwFunc();
} catch (e) {
expect(e).toBe(42);
}
throwFunc = function() {
throw function() {
return "hello";
};
}
expect(throwFunc).toThrow();
function MyException (m) {
this.message = m;
};
MyException.prototype.toString = function () {
return this.m;
};
throwFunc = function() {
throw new MyException("Oops!");
};
expect(throwFunc).toThrow();
try {
throwFunc();
} catch (e) {
expect(e.message).toBe("Oops!");
}
var i = 0;
try {
i++;
expect(i).toBe(1);
throwFunc();
} catch (e) {
i++;
expect(e.message).toBe("Oops!");
expect(i).toBe(2);
} finally {
i++;
expect(i).toBe(3);
}
});

4. Error Object

You can throw Error Object easily.
it("thorw Error", function() {
var throwErrorFunc = function() {
throw (new Error("Oops!"));
}
expect(throwErrorFunc).toThrow();
expect(throwErrorFunc).toThrowError("Oops!");
expect(throwErrorFunc).toThrowError(Error);
expect(throwErrorFunc).toThrowError(Error, "Oops!");
});

5. Reference

- MDN - https://developer.mozilla.org/en/docs/Web/JavaScript
- Jasmine - http://jasmine.github.io/2.3/introduction.html

댓글 없음:

댓글 쓰기