What is JavaScript?
JavaScript is a general-purpose programming language widely used to make web pages respond to users. It also runs outside browsers, including in server applications and development tools. A program expresses calculations and decisions using values, functions, and objects; its execution environment supplies ways to interact with the outside world.
Think of a shopping list application. JavaScript can calculate which items remain to buy. A browser supplies the document and click events needed to display and change that list. A server runtime supplies facilities to read a saved list from disk. The calculation can remain the same while the surrounding capabilities change. This distinction between the language and its host helps explain why browser-specific code cannot simply run unchanged on a server. MDN’s introduction describes this relationship.
JavaScript’s core language is standardized as ECMAScript. JavaScript and Java are separate languages, despite their names. Familiarity with Java’s variables, loops, and methods helps you begin, but JavaScript makes different choices about types, functions, and inheritance.
This article assumes you can read variables, conditionals, and function calls. By the end, you should be able to trace a small JavaScript program, explain how its functions share information, and distinguish asynchronous waiting from parallel computation.
What are JavaScript characteristics?
Values have types; variables can hold different types
JavaScript uses dynamic typing: a variable can hold a number now and a string later. You still need to reason about the type of each value. Primitive values include strings, numbers, booleans, undefined, null, big integers, and symbols. Objects include arrays and functions.
Some operators convert types implicitly. For example, 2 + 3 produces the number 5, while '2' + 3 produces the string '23'. A form field containing digits therefore needs an intentional conversion before arithmetic. Conversion and validation are separate decisions: converting an empty string with Number('') produces zero, which might violate your input rules.
For equality checks, === avoids converting operands to matching types: '2' === 2 is false. Objects compare by identity, so two separately created objects are unequal even when their properties match. Special numeric cases still matter: NaN === NaN is false. See the strict equality reference for its exact rules.
Functions are values with access to their surrounding scope
A function can be assigned to a variable, passed into another function, or returned as a result. Passing a function lets you supply behavior: a list operation can accept your rule for deciding which items to keep.
JavaScript uses lexical scope, meaning a function’s access to variables depends on where it was defined. A closure retains access to that surrounding scope even after the outer function returns. A configured filter can therefore remember its threshold without putting that threshold in a global variable. MDN’s closure guide explains how these retained environments work.
Objects connect data through references and prototypes
An object groups named properties. Assigning an object to another variable copies a reference to the same object; it does not duplicate the object’s contents. Mutating through either reference affects the shared object. MDN’s object guide covers object creation, properties, inheritance, and identity.
Use const for a binding you will not reassign and let when reassignment is needed. Both are block-scoped. A const binding does not freeze an object: its properties can still change. Object spread, written { ...item }, creates a new object containing copied enumerable own properties, but nested objects remain shared references.
Objects can also inherit behavior through a prototype, another object consulted when a property is missing. JavaScript’s class syntax provides a structured way to define constructors and methods on top of this model. For small records and transformations, ordinary objects and functions often suffice.
Modules separate responsibilities; promises represent eventual results
An ECMAScript module explicitly exports values that other modules import. Each module has its own scope, helping you keep calculations separate from display or storage code. Module loading details depend on the host, as the module guide explains.
A promise represents an eventual result or failure. An async function returns a promise; await suspends that function until the awaited value settles, without blocking the entire execution thread. Other scheduled work can proceed while it waits. An exception inside the function becomes a rejected promise. These semantics are documented in the async function reference.
Waiting does not make expensive calculations parallel. Within one JavaScript execution thread, a long synchronous loop still delays other work. Browser and server runtimes provide scheduling and additional concurrency facilities, but adding async to a function does not move its calculations to another thread.
JavaScript in action - code examples
The following examples use standard JavaScript and run with Node.js, which supplies the runtime and console. Save each standalone example as an .mjs file and run node filename.mjs. The .mjs extension explicitly selects ECMAScript modules.
Transform records with a configured function
We will select unfinished tasks whose estimates fit a time budget. An arrow function such as task => task.done is a compact function expression. filter calls your function for each array element and returns a new array containing the elements for which it returns a truthy value. map returns a new array containing each transformation’s result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const tasks = [
{ title: 'Review patch', minutes: 20, done: false },
{ title: 'Write guide', minutes: 60, done: false },
{ title: 'Update ticket', minutes: 10, done: true }
];
function withinBudget(maxMinutes) {
// The returned function retains access to maxMinutes.
return task => !task.done && task.minutes <= maxMinutes;
}
const canDoNow = withinBudget(30);
const titles = tasks.filter(canDoNow).map(task => task.title);
console.log(titles.join(', ')); // Review patch
Calling withinBudget(30) creates a function whose closure remembers the maxMinutes binding containing 30. The outer function then finishes. When filter later calls canDoNow, the review task passes both conditions, the guide exceeds the budget, and the ticket is already done. map extracts the surviving title; join formats it for display.
The resulting array is new, but its elements would still refer to the original task objects if we stopped after filter. These methods do not automatically copy nested data or prevent side effects inside your callbacks.
Make shared state visible
This standalone example compares an alias with a shallow copy:
1
2
3
4
5
6
7
8
9
10
const task = { title: 'Review patch', done: false };
const alias = task;
alias.done = true;
console.log(task.done); // true
console.log(alias === task); // true
const reopened = { ...task, done: false };
console.log(reopened === task); // false
console.log(task.done, reopened.done); // true false
alias.done = true changes the original object because both names refer to it. The spread expression creates a separate object, then overrides its done property. This record contains only primitive property values, so a shallow copy is sufficient here. If it contained an owner object, spreading the task would retain the same owner reference.
Put behavior in a module and await its result
Now move a calculation behind an explicit export. Create these two files in the same directory. The first uses an async function to model a future data source without making a network request.
1
2
3
4
5
6
7
// tasks.mjs
export async function loadTasks() {
return [
{ title: 'Review patch', done: false },
{ title: 'Update ticket', done: true }
];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// app.mjs
import { loadTasks } from './tasks.mjs';
async function main() {
console.log('Loading');
const tasks = await loadTasks();
const remaining = tasks.filter(task => !task.done).length;
console.log(`Remaining: ${remaining}`);
}
main().catch(error => {
console.error('Could not load tasks:', error.message);
});
console.log('Started');
Run node app.mjs. The output is:
1
2
3
Loading
Started
Remaining: 1
main begins immediately and prints Loading. Even though loadTasks returns an already fulfilled promise, await schedules the continuation for later. Execution outside main prints Started before the continuation counts the unfinished task. The backtick string inserts remaining through ${remaining}. If loading failed, the rejection would propagate through main to its attached catch handler.
This example demonstrates promise scheduling, not real I/O or parallel execution. Replacing the loader with a network call also requires handling that API’s response and failure rules.
What problems can JavaScript solve?
JavaScript is useful when programs coordinate events and transform application data. A browser can apply the filtering function after a user changes a time-budget control. A server can apply the same calculation before returning a response. Keeping the calculation independent of browser or server APIs makes reuse and testing easier.
| Situation | Useful language feature | Practical limit |
|---|---|---|
| Interactive list or form | Functions passed as event handlers | Slow synchronous work can delay the interface |
| Application-specific filtering | Closures and array transformations | Shared object references need care |
| Separating storage from calculations | Explicit module exports and imports | Host APIs still differ |
| Coordinating asynchronous results | Promises and async/await | Failures require deliberate handling |
Dynamic typing makes small transformations concise, but value shapes can become harder to track as an application grows. TypeScript can add static checking while retaining JavaScript’s runtime behavior. For heavily numerical or CPU-intensive workloads, compare other languages, specialized libraries, or worker-based execution against measured requirements.
Conclusion
JavaScript combines dynamically typed values, functions that retain their surrounding scope, and objects connected through references and prototypes. Modules help organize those pieces, while promises let you describe work whose result arrives later.
When reading unfamiliar code, trace the value types, identify which objects are shared, and locate every asynchronous continuation. Those three habits make the language’s compact syntax easier to reason about and help you keep calculations separate from the environment that runs them.
