JavaScript Basic Code and Syntax

JavaScript is a programming language used to add logic and interactivity to web pages. A useful first program declares a value, performs an operation, and sends the result somewhere visible such as the browser console or the page itself.

Simple JavaScript example:

const name = "plus2net";
let lessons = 10;
lessons += 1;
console.log(name, lessons);

This creates a constant string, a number that can change, updates the number, and prints both values. Modern JavaScript normally uses const for bindings that are not reassigned and let when reassignment is needed.

How JavaScript Code Runs Top ↑

JavaScript can run in a browser when it is included in an HTML page with a <script> element. The type="text/javascript" attribute is not required for normal JavaScript in HTML5.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>JavaScript Example</title>
</head>
<body>
  <p id="message">Waiting...</p>
  <script>
    document.getElementById("message").textContent = "JavaScript is running";
  </script>
</body>
</html>

For larger programs, keep JavaScript in an external .js file. See adding JavaScript to HTML for script placement, external files, defer, async, and modules.

Values and Variables Top ↑

JavaScript works with values such as strings, numbers, Booleans, objects, arrays, null, and undefined. Variables give those values useful names.

const course = "JavaScript";
let score = 85;
const passed = true;
const topics = ["variables", "loops", "functions"];
console.log(course, score, passed, topics.length);

JavaScript is dynamically typed: the type belongs to the value rather than being permanently attached to the variable. Use the typeof operator when you need a basic type check.

Operators and Expressions Top ↑

Expressions combine values and operators to produce another value. Arithmetic, comparison, and logical operators are among the most common.

const price = 120;
const quantity = 3;
const total = price * quantity;
const qualifies = total >= 300 && quantity > 1;
console.log(total, qualifies);

Use strict equality (===) as the normal default when comparing values. See comparison operators and logical operators for the details.

Displaying JavaScript Output Top ↑

For learning and debugging, console.log() is usually the least intrusive output method. To show information to a user, update a DOM element instead of relying on document.write().

const result = 2 + 3;
console.log(result);

const output = document.getElementById("result");
if (output) {
  output.textContent = `Result: ${result}`;
}
Why not document.write()? It is useful mainly for understanding older examples. When called after a page has loaded, it can replace the document and is not a good general-purpose output technique.

Making Decisions with if...else Top ↑

Conditions let a program choose what to do. The following checks a score and runs one of two branches.

const score = 72;

if (score >= 50) {
  console.log("Pass");
} else {
  console.log("Try again");
}

Continue with the full JavaScript if...else tutorial and switch statement.

Repeating Code with Loops Top ↑

Loops repeat a block of code. A for loop is convenient when the start, stop condition, and step are known.

for (let i = 1; i <= 3; i += 1) {
  console.log(`Step ${i}`);
}

See the loops overview, for loop, and while and do...while loops.

Reusing Code with Functions Top ↑

A function groups reusable logic. Parameters receive input and return sends a result back to the caller.

function add(a, b) {
  return a + b;
}

const total = add(4, 6);
console.log(total);

The JavaScript functions tutorial covers parameters, returns, scope, function expressions, arrow functions, callbacks, recursion, and more.

Changing a Web Page with JavaScript Top ↑

Browser JavaScript commonly reads or changes the Document Object Model (DOM). First select an element, then update a property or attach an event listener.

<button id="helloButton" type="button">Say hello</button>
<p id="helloOutput"></p>
const button = document.getElementById("helloButton");
const output = document.getElementById("helloOutput");

button.addEventListener("click", () => {
  output.textContent = "Hello from JavaScript";
});

Errors and Debugging Top ↑

Syntax errors prevent code from being parsed. Runtime errors occur while valid code is executing. Browser developer tools and the console are essential for finding both.

try {
  JSON.parse("not valid JSON");
} catch (error) {
  console.error(error.message);
}

See try...catch and JavaScript error handling for when an exception should be handled rather than allowed to propagate.

Small Complete JavaScript Example Top ↑

This example combines variables, a function, a condition, and a loop.

function labelNumber(value) {
  if (value % 2 === 0) {
    return `${value} is even`;
  }
  return `${value} is odd`;
}

for (let i = 1; i <= 5; i += 1) {
  console.log(labelNumber(i));
}

Common Beginner Mistakes Top ↑

  • Using a variable before understanding its scope or initialization.
  • Using = when a comparison such as === was intended.
  • Forgetting to update a loop condition and creating an infinite loop.
  • Changing page content with innerHTML when plain textContent is sufficient.
  • Putting everything in the global scope instead of using functions or modules.
  • Copying old examples without checking whether the API or syntax is still appropriate.

What to Learn After the Basics Top ↑

A practical path is adding JavaScript to HTML → variables → comparisons → conditions → loops → functions → arrays → DOM and events.

JavaScript Basics




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer