JavaScript has grown to become one of the most popular programming languages in the world, powering the interactivity and dynamic behavior of millions of websites. This post will take you on a journey through the world of JavaScript, unraveling what makes it such an indispensable tool for web development.
We’ll start by understanding what exactly JavaScript is, followed by stepping through the building blocks of the language. Then we’ll apply JavaScript to bring web pages to life with dynamic content, event handling and interactive UI. By the end, you’ll have a firm grasp of JavaScript fundamentals opening doors to the vast possibilities it unlocks for client-side scripting.
What is JavaScript?
JavaScript first appeared in 1995 as a way to add programs to web pages in the Netscape browser. The idea was to let web pages and UI react to user actions without needing server communication.
JavaScript gained widespread adoption rapidly and is now supported by all major browsers without plugins. It powers complex web apps like social networks and online video games entirely within the browser.
So in essence, JavaScript allows implementing rich features and logic in web documents just like an application. It can manipulate document structure, styles, and content in response to user events. All this occurs locally in the browser instead of needing page reloads from the server.
Some key capabilities provided by JavaScript include:
- Dynamically modifying HTML and CSS to transform web page appearance
- Responding to user interactions via events
- Animating page transitions and UI behavior
- Sending and receiving data asynchronously using AJAX and promises
- Storing client-side data with cookies and web storage APIs
- Building reactive single page apps using component frameworks like React
- Addingdesktop/mobile app capabilities through runtimes like Electron and Apache Cordova
- Game development using technologies like HTML5 Canvas and WebGL
JavaScript usage was traditionally limited to browsers but runtime environments like Node.js now allow using it for server-side programming as well.
Core Language Components
Now that you have a high-level view of JavaScript and its capabilities in web development, let’s dig deeper into the language itself. We’ll dissect key building blocks that form the nuts and bolts powering any JavaScript program.
Syntax Basics
The most basic JS program would look like:
// Single line comment
/*
Multi-line
comment
*/
// Code statements end with ;
var greeting = "Hello World!";
// String literals use double or single quotes
const name = 'John';
// Console log message to debug
console.log(greeting);
Some syntax basics:
- Case sensitive language with C-like syntax
- Statements terminated with semicolons
- Variables declared using `var`, `let`, or `const`
- Multi-line and single line comments styles
- Code encapsulated in functions and objects
Whitespace is generally ignored though it’s good practice for readability.
Variables
Variables store values that can be used and updated throughout your program.
They are declared using `var
`, `let
` or `const
`:
// Change value later ✅
var age = 32;
// Fixed value ✅
const pi = 3.14;
// Block scoped variable ✅
let score = 10;
- `var` - Function scoped variable that can be updated
- `let` - Block scoped like for loop. Can be updated
- `const` - Block scoped and fixed value
Trying to change a `const` throws an error.
Data Types
JavaScript has dynamic typing so the engine infers types automatically instead of needing explicit declarations.
The main data types available are:
- Number: integers, floats, Infinity, NaN
- String: text data, use single or double quotes
- Boolean: `true`/`false` logical type
- Undefined: variable declared but no value yet
- Null: intentional empty value
- Symbol: unique identifiers
- Object: key-value collection of properties
Additionally JavaScript now has BigInt, Map/Set and Array data structures.
Here are some examples:
// Number
let degrees = 102.5;
// String
let patientName = "Mary";
// Boolean
let isSelected = true;
// undefined
let zipCode; // Value is undefined
// null
let middleName = null;
// Symbol
let id = Symbol('user-id');
// Object
let person = {
name: "Jack",
age: 32
};
// Array
let scores = [90, 85, 96];
Data types can be checked using `typeof`.
Operators
Operators allow you to transform and combine values mathematically or logically.
// Addition
let sum = 45 + 18;
// Logical AND
if (age > 18 && subscribed) {
// Run code
}
// String concatenation
let message = "Welcome " + guest;
Some key operators types are:
- Assignment: `=` Assign value to variable
- Arithmetic: `+`, `-`, `*`, `/`, `%` Math operations
- String Concatenation: `+` Combine strings
- Comparison: `==`, `!=`, `>`, `<` Compare values
- Logical: `!`, `&&`, `||` Boolean logic
- Ternary:`condition ? expr1 : expr2` Conditional assignment
Additionally, ES6 added exponentiation and nullish coalescing operators.
Operators work with most [data types](#data-types) as you would expect.
// Exponentiation
let cubed = 2 ** 3; // 8
// Nullish coalescing
let userAge = age ?? 18;
Conditionals
Conditionals execute different code blocks based on if a condition evaluates to `true` or not:
let discount = 0;
if (items > 2) {
// Apply bulk order discount
discount = 10;
} else if (items > 5) {
// Additional discount for big orders
discount = 20;
} else {
// No discount
}
The comparison after `if` supports all [comparison operators](#operators) like `>`, `===`, `<`, etc.
Multiple conditions can be chained using `else if`. The `else` clause handles the default case when no condition matches.
READ ALSO:
Loops
Loops allow you to repeat a code block a certain number of times:
// Loop 10 times
for (let i = 0; i < 10; i++) {
// Execute code
// i = current loop count
}
let users = [ "John", "Pete", "Mary" ];
// Iterate array
users.forEach(user => {
// Executes for each user
console.log(user);
});
Commonly used loops include:
- for: Execute code fixed number of times
- for...in: Iterate object properties
- for...of: Iterate iterable objects like arrays
- while: Repeat code while condition is `true`
- do...while: Same but check condition after first iteration
Loops let you minimize duplication and repeat code programmatically.
Functions
Functions allow you to encapsulate and reuse code:
// Function declaration
function calculateTotal(price, tax) {
// Calculate order total
let total = price + (price * tax);
return total;
}
// Call function
let orderTotal = calculateTotal(100, 0.05);
Functions have to be declared and defined before they can be executed or *called*.
We *passed* two *parameters* price and tax while calling the function. They are used in the function body for calculations.
The `return` keyword lets functions return a final value once operations are complete.
Scope
Scope determines where variables, functions, and objects are accessible in code.
Any variable declared inside a function using `var` or `let` cannot be accessed from outside that function:
function calculate() {
// Local scoped variable
let total = 100;
}
calculate();
// total cannot be accessed here
console.log(total); // Error
Scopes in JavaScript are:
- Global Scope - Defined outside functions and accessible globally
- Local/Function Scope - Only available within function
- Block Scope - Inside `{ }` brackets like if/loop blocks
Functions can access global scope but not vice-versa. Block scope variables are only accessible within block.