404 Not Found

404 Not Found


nginx

JavaScript Syntax

Syntax is the rules of the language — mastering JS syntax rules ensures your code is correctly understood by the browser.

Statements and Semicolons

JS code consists of statements, each performing an action. A semicolon ; marks the end of a statement.

Although JS has automatic semicolon insertion (ASI) and most code runs fine without semicolons, it's strongly recommended to add them manually. Why? Because ASI occasionally misinterprets your intent, causing hard-to-debug bugs. Building the habit of adding semicolons saves far more debugging time than the effort of typing them.

Code Blocks

Multiple statements wrapped in curly braces {} form a code block, commonly seen in function bodies, conditionals, and loops:

HTML
<script>
if (score > 60) {
  result = "Pass";
  color = "green";
}
</script>

Code blocks make multiple statements execute as a unit. Although braces can be omitted for single statements, never skip them — braces make your intent clearer and prevent bugs when you add more statements later.

Comments

Comments are written for humans; the browser ignores them entirely. Good comments explain "why," not "what" (the code itself should convey what it does).

Case Sensitivity

JS is strictly case-sensitive: myVar, myvar, and MYVAR are three completely different variables. Beginners often stumble here — the logic looks correct, but errors occur because of wrong casing.

Keywords and Reserved Words

JS reserves certain words as keywords (like var, let, const, function, if, else, etc.) and you cannot use them as variable names. The full list of reserved words is long; just remember the common ones — your editor's syntax highlighting will help identify them.

Example: Statements, Semicolons, and Code Blocks

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Syntax - Statements and Code Blocks</title>
  <style>
    body { font-family: Arial, sans-serif; max-width: 500px; margin: 60px auto; }
    #output { min-height: 40px; padding: 16px; background: #f5f5f5; border-radius: 8px; margin-top: 16px; }
    button { padding: 10px 24px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; color: #fff; background: #2196F3; margin-top: 8px; }
    button:hover { background: #1976D2; }
    input { padding: 8px; font-size: 16px; border: 2px solid #ddd; border-radius: 4px; width: 100px; }
  </style>
</head>
<body>
  <h2>Statements and Code Blocks</h2>
  <p>Enter a score to check if it passes:</p>
  <input type="number" id="scoreInput" placeholder="Score" value="75">
  <button id="checkBtn">Check</button>
  <div id="output"></div>
  <script>
    document.getElementById("checkBtn").onclick = function() {
      var score = parseInt(document.getElementById("scoreInput").value);
      var result = "";
      var color = "";
      if (score >= 60) {
        result = "Passed! Score: " + score;
        color = "#4CAF50";
      } else {
        result = "Failed. Score: " + score;
        color = "#f44336";
      }
      var outputEl = document.getElementById("output");
      outputEl.textContent = result;
      outputEl.style.color = color;
    };
  </script>
</body>
</html>
▶ Try it Yourself

Example: Using Comments

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Syntax - Comments</title>
  <style>
    body { font-family: Arial, sans-serif; max-width: 500px; margin: 60px auto; }
    .code-box { background: #263238; color: #aed581; padding: 20px; border-radius: 8px; font-family: Consolas, monospace; font-size: 14px; line-height: 1.8; white-space: pre; overflow-x: auto; }
    .comment { color: #78909c; }
    button { margin-top: 16px; padding: 10px 24px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; color: #fff; background: #4CAF50; }
    #result { margin-top: 12px; font-size: 18px; }
  </style>
</head>
<body>
  <h2>JS Comments</h2>
  <div class="code-box"><span class="comment">// Single-line comment: calculate the area of a circle</span>
var r = 5;
var area = 3.14 * r * r;
<span class="comment">/* Multi-line comment:
   round to two decimal places */</span>
area = area.toFixed(2);</div>
  <button id="runBtn">Run this code</button>
  <p id="result"></p>
  <script>
    document.getElementById("runBtn").onclick = function() {
      var r = 5;
      var area = 3.14 * r * r;
      area = area.toFixed(2);
      document.getElementById("result").textContent = "Area of circle with radius 5 = " + area;
      document.getElementById("result").style.color = "#4CAF50";
    };
  </script>
</body>
</html>
▶ Try it Yourself

Example: Case Sensitivity Demo

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Syntax - Case Sensitivity</title>
  <style>
    body { font-family: Arial, sans-serif; max-width: 500px; margin: 60px auto; text-align: center; }
    .card { display: inline-block; padding: 20px; border: 2px solid #ddd; border-radius: 12px; margin: 8px; min-width: 120px; }
    .card h3 { margin: 0 0 8px; }
    .card p { margin: 0; font-family: Consolas, monospace; font-size: 18px; }
    #myVar { border-color: #4CAF50; }
    #myvar { border-color: #FF9800; }
    #MYVAR { border-color: #9C27B0; }
    button { margin-top: 20px; padding: 10px 24px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; color: #fff; background: #e91e63; }
  </style>
</head>
<body>
  <h2>JS Case Sensitivity</h2>
  <p>These three variable names are all different:</p>
  <div class="card" id="myVar"><h3>myVar</h3><p>---</p></div>
  <div class="card" id="myvar"><h3>myvar</h3><p>---</p></div>
  <div class="card" id="MYVAR"><h3>MYVAR</h3><p>---</p></div>
  <br>
  <button id="showBtn">Assign and Display</button>
  <script>
    document.getElementById("showBtn").onclick = function() {
      var myVar = "Green";
      var myvar = "Orange";
      var MYVAR = "Purple";
      document.querySelector("#myVar p").textContent = myVar;
      document.querySelector("#myvar p").textContent = myvar;
      document.querySelector("#MYVAR p").textContent = MYVAR;
    };
  </script>
</body>
</html>
▶ Try it Yourself

Example: Naming Rules in Practice

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Syntax - Naming Rules</title>
  <style>
    body { font-family: Arial, sans-serif; max-width: 550px; margin: 60px auto; }
    .rule { padding: 12px 16px; border-left: 4px solid #2196F3; background: #e3f2fd; margin: 8px 0; border-radius: 0 8px 8px 0; }
    .bad { border-left-color: #f44336; background: #ffebee; }
    .good { border-left-color: #4CAF50; background: #e8f5e9; }
    code { background: #eceff1; padding: 2px 6px; border-radius: 3px; font-size: 14px; }
  </style>
</head>
<body>
  <h2>Variable Naming Rules</h2>
  <div class="rule">✅ Allowed: letters, digits, underscore <code>_</code>, dollar sign <code>$</code></div>
  <div class="rule">✅ Cannot start with a digit</div>
  <div class="rule">✅ Cannot use keywords (like <code>var</code> <code>let</code> <code>function</code>)</div>
  <div class="rule good">✅ Recommended: camelCase — <code>myFirstName</code> <code>totalScore</code></div>
  <div class="rule bad">❌ Not recommended: <code>my_first_name</code> (underscore style is uncommon in JS)</div>
  <div class="rule bad">❌ Invalid: <code>2ndPlace</code> (starts with digit) <code>my-var</code> (contains hyphen)</div>
  <hr style="margin: 24px 0;">
  <h3>camelCase Examples</h3>
  <div id="demo" style="font-size: 18px; line-height: 2;"></div>
  <script>
    var firstName = "John";
    var lastName = "Doe";
    var ageInYears = 25;
    var isStudent = true;
    var favoriteLanguage = "JavaScript";
    var demoEl = document.getElementById("demo");
    demoEl.innerHTML = "firstName = \"" + firstName + "\"<br>" +
      "lastName = \"" + lastName + "\"<br>" +
      "ageInYears = " + ageInYears + "<br>" +
      "isStudent = " + isStudent + "<br>" +
      "favoriteLanguage = \"" + favoriteLanguage + "\"";
  </script>
</body>
</html>
▶ Try it Yourself

📖 Summary

  1. JS statements end with semicolons — always add them manually; don't rely on automatic semicolon insertion
  2. Code blocks use {} — even for single statements, never omit the braces
  3. Single-line comments use //, multi-line comments use /* */ — comments should explain "why," not "what"
  4. JS is strictly case-sensitive — myVarmyvar is the most common beginner mistake
  5. Variable names cannot start with digits, and cannot use keywords or reserved words
  6. camelCase is the recommended naming convention: firstName, totalScore

❓ FAQ

Q Can omitting semicolons really cause bugs?
A Most of the time no, but edge cases exist. For example, a line break after return causes JS to auto-insert a semicolon, returning undefined instead of your intended value. These bugs are extremely sneaky — you might debug for hours only to find a missing semicolon. Why risk it?
Q Should I add braces to single-line statements?
A Yes. Today it's one line; tomorrow you might add two more. Forgetting to add braces then causes logic errors. Braces cost a few bytes but save hours of debugging.
Q camelCase or snake_case — which is better?
A In the JS world, camelCase (firstName) is the standard. snake_case (first_name) is more common in Python and database fields. When in Rome, do as the Romans do — use camelCase in JS.

📝 Exercises

  1. Basic: Write JS code that declares two variables studentName and studentAge, assigns values to them, and prints them with console.log(). Ensure all statements have semicolons and variable names use camelCase.
  2. Intermediate: Create a page with an input field and a button. When the user enters an age, determine if they're an adult (≥18) using an if/else code block, and display the result on the page.
  3. Challenge: Create a "Naming Checker" page where the user enters a variable name. JS checks if it's valid (no leading digits, no spaces or hyphens, not a keyword) and displays "Valid" or "Invalid" with the reason.
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏