Programming in JavaScript
Standard Library and Imports¶
JavaScript has a built-in standard library available in all environments. In Node.js, modules can be imported using require() or import. Some examples:
import fs from 'fs';for reading and writing filesimport path from 'path';for working with file pathsimport readline from 'readline';for reading user input in the terminal
Comments¶
// single line comment
/* multi
line
comment */Data Types and Variables¶
Each variable is a container for a value. JavaScript is dynamically typed, so the type is inferred from the value. Variables are declared using let, const, or var.
let variableName = value;— declares a block-scoped variable that can be reassignedconst variableName = value;— declares a block-scoped variable that cannot be reassignednumber: stores integers and decimalsstring: stores textboolean: stores eithertrueorfalsenull: represents an intentional absence of valueundefined: a variable that has been declared but not assigned a valueobject: stores collections of key-value pairsarray: stores ordered lists of values (a special kind of object)
User Input and Output¶
In a browser, console.log() prints to the developer console. In Node.js, the readline module is needed for user input.
console.log("Hello, World!"); // printing to the console
// Reading user input in Node.js
import readline from 'readline';
const rl = readline.createInterface({ input: process.stdin });
rl.question("What is your name? ", (name) => {
console.log("Hello " + name);
rl.close();
});Operators¶
Operators are used to manipulate variables in different ways.
Arithmetic (mainly used for numbers):
+ // Addition
- // Subtraction
* // Multiplication
/ // Division
% // Modulus (gives the remainder)
** // Exponentiation
++ // Increment (adds 1 to variable)
-- // Decrement (subtracts 1 from variable)Assignment Operators (Shorthand version of doing an operation and then assigning it to the variable):
+=
-=
*=
/=
%=
**=Comparison Operators (Compares two statements and returns a boolean):
=== // strict equality (checks value AND type)
!== // strict inequality
>
<
>=
<=Logical Operators (Can also compare two statements and returns a boolean):
&& // and
|| // or
! // notStrings¶
To use strings, no imports are needed as they are built into JavaScript.
let a = "Hello";
let b = " World";
// String concatenation (adding two strings together will create a new string that contains both strings)
let c = a + b;
// Returns the length of the string
let length = c.length;
// Accessing a character of the string using an index
let firstChar = c[0];
// Template literals (another way to build strings using backticks, expressions go inside ${})
let d = `${a}${b}`;
// Escape characters (special characters that can be added to a string)
\' // Single quote
\" // Double quote
\\ // Backslash
\n // New line
\t // Tab
// Common string methods
c.toUpperCase(); // returns the string in all caps
c.toLowerCase(); // returns the string in all lowercase
c.includes("Hello"); // returns true if the string contains the given substring
c.slice(0, 5); // returns a portion of the string (start index, end index)
c.replace("Hello", "Hi"); // replaces the first occurrence of a substring with another
c.trim(); // removes whitespace from both ends of the stringStatements and Loops¶
// If statement
let a = 5;
let b = 3;
if (a > b) {
console.log("a is greater");
}
else if (b > a) {
console.log("b is greater");
}
else {
console.log("a is equal to b");
}
// While loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// For...of loop (loops over the elements of an array)
let fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
// Break & continue statements
// when placed inside a loop and break is reached, the loop will stop and move to the next line of code after the loop
break;
// when placed inside a loop and continue is reached, the loop will skip the remaining lines of code after the continue statement and the loop will run its next iteration
continue;