Rust for JavaScript Developers: A Practical Introduction
A hands-on guide to learning Rust, written specifically for developers coming from the JavaScript/TypeScript ecosystem.
Rust for JavaScript Developers: A Practical Introduction
If you're a JavaScript developer curious about Rust, you're in the right place. This guide maps Rust concepts to things you already know.
Variables: let vs let mut
In JavaScript, let creates a mutable variable. In Rust, let creates an immutable variable by default:
let name = "world"; // immutable (like JS const)
let mut count = 0; // mutable (like JS let)
count += 1; // this works
// name = "hello"; // this would NOT compile
No Null, No Undefined
Rust doesn't have null or undefined. Instead, it uses Option<T>:
fn find_user(id: u32) -> Option<String> {
if id == 1 {
Some("Alice".to_string())
} else {
None
}
}
match find_user(1) {
Some(name) => println!("Found: {}", name),
None => println!("User not found"),
}
This is similar to TypeScript's strict null checks, but enforced at the language level.
Error Handling: Result instead of try/catch
use std::fs;
fn read_config() -> Result<String, std::io::Error> {
fs::read_to_string("config.toml")
}
fn main() {
match read_config() {
Ok(content) => println!("Config: {}", content),
Err(e) => eprintln!("Error reading config: {}", e),
}
}
Ownership: The Big Concept
This is where Rust diverges most from JavaScript. Every value has exactly one owner:
let s1 = String::from("hello");
let s2 = s1; // s1 is MOVED to s2
// println!("{}", s1); // ERROR: s1 is no longer valid
println!("{}", s2); // This works
Think of it like transferring a file instead of copying it. This is how Rust avoids garbage collection while preventing memory leaks.
Conclusion
Rust has a steeper learning curve than JavaScript, but the payoff is enormous: zero-cost abstractions, memory safety without GC, and incredibly reliable software.