3.1 if-else statement
The most common operator in JavaScript, just like in Java, is if-else
. It works exactly the same. Example:
var x = 1;
if (x == 1) {
console.log("one");
}
else {
console.log("unknown");
}
if-else
may be nested, and the block else
may be missing. Everything is the same as in Java.
3.2 Loops for, while, for in
The for loop in JavaScript works the same way as in Java. And no wonder, they both copied its behavior from the C ++ language. Generally no differences. JavaScript also has the break
and operators continue
. No surprises. Example:
var s = 0;
for (var i=0; i<10; i++)
s += i;
console.log(s);
There are also cycles while
and do.while
. They work exactly the same as in Java and C++.
From the interesting: there is an analogue of the cycle for each
, called for in
. Here's what it looks like:
var obj = {a: 1, b: 2, c: 3};
for (var key in obj)
console.log( obj[key] );
Unlike the Java language, here the variable key
sequentially takes the values of the keys of the object obj
. To get a value by key, you need to writeobj[key];
3.3 Exceptions
JavaScript supports working with exceptions, but since there is no normal typing, all exceptions have exactly one type - Error
.
To work with exceptions, there is an operator try-catch-finally
that works similar to the operator from Java.
Example:
try {
throw new Error("JavaScript support exceptions");
}
catch(e) {
console.log(e);
}
GO TO FULL VERSION