Before diving deeper into JavaScript, it's helpful to understand some fundamental concepts about how programming languages work.
Programming languages can be broadly categorized into two types: high-level and machine-level.
| High-Level Language | Machine-Level Language |
|---|---|
| Human-readable (e.g., JavaScript, Python). | Binary code (0s and 1s) understood by the CPU. |
| Easy for humans to read, write, and debug. | Not human-readable; intended for machine execution. |
| Requires translation to be executed. | No conversion required; the machine understands it directly. |
The translation from a high-level language to machine code can happen in two primary ways: compilation or interpretation.
| Compilation | Interpretation |
|---|---|
| Converts the entire program into machine code at once. | Converts and executes the program one instruction at a time. |
| The software used is called a Compiler. | The software used is called an Interpreter. |
| Translates the whole program first, then executes the result. | Translates and executes line-by-line. |
| Faster execution due to pre-compilation. | Slower execution because of the line-by-line translation. |
| Examples: C, C++, Java | Examples: Python, JavaScript |
JavaScript is traditionally known as an interpreted language. This nature allows it to be very flexible in how it's executed.
.js files locally from your terminal, you need to have Node.js installed.Because it's an interpreted language, JavaScript supports two main modes of execution.
Script mode involves writing your code in a file (with a .js extension) and executing the entire program at once. This is how most real-world applications are built.
console.log("Hello, World!"); // Prints: Hello, World!
console.log(2 + 2); // Prints: 4
console.log(2 * 2); // Prints: 4
To run this file, you would open your terminal and type:
node example.js
Interactive mode, also known as a REPL (Read-Eval-Print Loop), allows for line-by-line execution of JavaScript commands in real-time. It's great for testing and debugging small code snippets.
To access it:
node and press Enter.What is the main difference between a compiler and an interpreter?