Declare a variable
var x = 10;
Declare a block-scoped variable
let y = 20;
Declare a block-scoped, read-only named constant
const z = 30;
Numeric data type
let num = 42;
Textual data type
let str = 'Hello, world!';
True or false values
let bool = true;
Complex data type, a collection of key-value pairs
let obj = { key: 'value' };
Represents the intentional absence of any object value
let n = null;
Indicates a variable that has not been assigned a value
let u;
Evaluate a condition and execute code if it's true
if (x > y) {
/* ... */
}
Evaluate another condition if the previous one is false
else if (x < y) {
/* ... */
}
Execute code if all previous conditions are false
else {
/* ... */
}
Evaluate an expression against multiple cases
switch (x) {
case 1: /* ... */;
break;
default:
/* ... */;
}
Create a loop with a counter
for (let i = 0; i < 10; i++) {
/* ... */
}
Create a loop that continues as long as the condition is true
while (x < 10) {
/* ... */; x++;
}
Execute code once, then repeat the loop as long as the condition is true
do {
/* ... */; x++;
} while (x < 10);
Declare a function with a given name
function myFunction() {
/* ... */
}
Declare a function and assign it to a variable
var myFunction = function() {
/* ... */
};
Declare a function using the arrow syntax
(param1, param2) => {
/* ... */
}
Declare a function without a name
function() {
/* ... */
}
Pass a function as an argument to another function
function myCallback() {
/* ... */
};
someFunction(myCallback);
Create an array using the array literal syntax
let myArray = [1, 2, 3];
Manipulate arrays using various methods
push, pop, shift, unshift, splice, indexOf
Create an object using the object literal syntax
let myObject = { key: 'value' };
Manipulate objects using various methods
keys, values, create, defineProperty
Handle errors and exceptions using try, catch, and finally blocks
try {
/..
}
catch (error) {
...
} finally {
...
}
Represent a value that may be available now, in the future, or never
new Promise((resolve, reject) => {
/* ... */
}
)
Attach callbacks for when the Promise is fulfilled
promise.then(onFulfilled)
Attach callbacks for when the Promise is rejected
promise.catch(onRejected)
Export values, objects, or functions from a module
export { myFunction, myVariable };
Import values, objects, or functions from a module
import { myFunction, myVariable } from './myModule.js';
Define a class with a constructor and methods
class MyClass { constructor() {
/* ... */
}
myMethod() {
/* ... */
}
}
Create a subclass that inherits from a parent class
class MySubclass extends MyClass {
/* ... */
}
Call the constructor or methods of a parent class
super(); super.myMethod();
Create a string that can include expressions
let str = `Hello, ${name}!`;
Assign array elements to variables
let [a, b] = [1, 2];
Assign object properties to variables
let { a, b } = { a: 1, b: 2 };