Introduction

Before learning to write in a spoken language, you must first learn the rules of grammar. Here are a few examples of rules you might find in the English language:

  • A sentence starts with a capital letter
  • A sentence ends in a period
  • A new paragraph is indented
  • Spoken dialogue is placed inside double quotation marks.

Similarly, all programming languages must adhere to specific rules in order to function. This set of rules that determine the correct structure of programming languages is known as syntax. Many programming languages consist largely of similar concepts with variations in syntax.

In this tutorial, we’ll go over many of the rules and conventions of JavaScript syntax and code structure.

Functionality and Readability

Functionality and readability are two important reasons to focus on syntax as you begin to work with JavaScript.

There are some syntax rules that are mandatory for JavaScript functionality. If they are not followed, the console will throw an error and the script will cease execution.

Consider a syntax error in the “Hello, World!” program:

// Example of a broken JavaScript program
console.log("Hello, World!"

This code sample is missing the closing parenthesis, and instead of printing the expected “Hello, World!” to the console, the following error will appear:

Uncaught SyntaxError: missing ) after argument list

The missing ) must be added before the script will continue to run. This is an example of how a mistake in JavaScript syntax can break the script, as correct syntax must be followed in order for code to run.

Some aspects of JavaScript syntax and formatting are based on different schools of thought. That is, there are stylistic rules or choices that are not mandatory and will not result in errors when the code is run. However, there are many common conventions that are sensible to follow, as developers between projects and codebases will be more familiar with the style. Adhering to common conventions leads to improved readability.

Consider the following three examples of variable assignment.

const greeting = 'Hello' // no whitespace between variable & string
const greeting = 'Hello' // excessive whitespace after assignment
const greeting = 'Hello' // single whitespace between variable & string

#javascript #fundamentals

Understanding Syntax and Code Structure
1.35 GEEK