Lesson · JavaScript Basics

Run your first JavaScript

JavaScript can run in more than one environment, so knowing where a snippet runs matters.

What you will learn

  • Run a Node.js script
  • Recognize browser-only APIs
  • Read console output

Choose an environment

Node.js runs JavaScript outside a browser and is useful for small terminal programs. A browser runs JavaScript alongside a web page and provides APIs such as document. Those environments share the language but not every built-in feature, so an example should say which environment it expects.

Save and run a file

Save source code in a plain text file with a .js extension. With Node.js installed, run node hello.js from the folder containing the file. The terminal command is separate from the JavaScript inside the file, just as a Python command starts its own interpreter.

Use the console as evidence

console.log writes a value to the environment's developer console or terminal output. It is useful while learning, but it is not a page heading or an alert shown to every visitor. Read exactly what appears, then compare it with the value the code was intended to produce.

Keep examples portable

A snippet using console.log and basic values can run in both Node and a browser console. Code that refers to document needs a browser page. If Node reports that document is undefined, the code likely expects a browser rather than a different JavaScript syntax.

Load browser scripts at the right time

When JavaScript needs page elements, use a script element with defer or place the script after the relevant markup so the document has been parsed first. A selector can return null when the requested element is absent. Check that possibility when code supports multiple pages instead of assuming every page contains the same controls.

Javascript example
console.log('Hello, JavaScript!');
Expected output
Hello, JavaScript!

Practice exercise

Create a JavaScript file that logs a greeting and the name of a topic you want to learn.

Show a hint

Use two console.log calls or one template literal.

Show one possible solution

For example, console.log('Hello!'); console.log('Today I will learn arrays.'); prints the two messages on separate lines.

Quick check

Which API is available in a browser page but not guaranteed in Node.js?

Frequently asked questions

Is JavaScript the same as Java?
<p>No. They are different programming languages with different histories and runtimes. Similar names do not mean that their syntax, libraries, or execution model are interchangeable.</p>