Intro to Programming

Introduction to Programming and Languages

Before diving deeper into JavaScript, it's helpful to understand some fundamental concepts about how programming languages work.


High-Level vs. Machine-Level Language

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.

Compilation vs. Interpretation

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 as an Interpreted Language

JavaScript is traditionally known as an interpreted language. This nature allows it to be very flexible in how it's executed.

1. Execution in Browsers

2. Execution Outside Browsers (Node.js)


Execution Modes in JavaScript

Because it's an interpreted language, JavaScript supports two main modes of execution.

Script Mode

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.

Script Mode Example (save as `example.js`):

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 (REPL)

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:

  1. Open your terminal.
  2. Type node and press Enter.
  3. You can now type JavaScript commands directly.

Summary


Exercise

?

What is the main difference between a compiler and an interpreter?