In Javascript, an expression is a line of code that returns a value. A statement is any line of code. Every expression needs a semi-colon at the end. Statements that aren't expressions don't generally require semi-colons, and may cause syntax errors.
For example,
// variable assignments are expressions
let x = 5;
// function declarations are statements
function() {}
if (x === 5) { // `if` blocks are statements
console.log("hello"); // console.log's are expressions
} Curly braces are used to delineate code blocks such as in function definitions, loops, and if blocks. Curly braces can also be used to define JavaScript objects.
// `if/else` block
if (boolean) {
// code block...
} else {
// another code block...
}
// loop
while (condition) {
// code block...
}
// function definition
function foo() {
// code block...
}
// JS object
let obj = { key: "value" };Missing curly braces is a very common mistake! Build good habits early.
Use blocks to delineate code within loops.
for (let i = 0; i < 10; i++) {
// code block
}while (condition) {
// code block
}Skips the current iteration.
let result = [];
for (let i = 1; i < 10; i++) {
if (i % 3 === 0) {
continue;
}
result.push(i);
}
console.log(result); // [1, 2, 4, 5, 7, 8]Exits the loop.
let result = [];
for (let i = 1; i < 10; i++) {
if (i % 3 === 0) {
break;
}
result.push(i);
}
console.log(result); // [1, 2]switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}You'll notice that many of these operators are very similar to Ruby! Give them a try in Node.
This is similar to puts in Ruby.
> console.log('hello')
hello// this is a javascript in-line comment
/*
this is
a javascript
comment block
*/+-*/%
><>=<====!==
NB: Three equals signs? What's that about? There is a double equals operator (==)
in JS as well, but we'll mostly be sticking with ===. The double equals sign
does some type conversion which can lead to confusing results. Learn more about
it in Effective Javascript.
&&: and||: or!: not
String.prototype.toLowerCaseString.prototype.toUpperCaseString.prototype.indexOf+: concatenation
Array.prototype.length
Array.prototype.popArray.prototype.pushArray.prototype.unshiftArray.prototype.shiftArray.prototype.indexOf- Similar to
Array#indexin Ruby, but returns-1when it does not find an item.
- Similar to
[]- Index using bracket notation (similar to Ruby).
Array.prototype.slice([start, [end]])- Makes a copy of an array from the start index up to but not including the end index. Both arguments are optional (the first and last elements are used by default).
Array.includes(ES6+)- Identical to
Array#include?in Ruby
- Identical to
Array.isArray(ES6+):- Class method that accepts one argument and returns a boolean representing whether it is an
Array.
- Class method that accepts one argument and returns a boolean representing whether it is an