JavaScript Syntax – The Basics You Need to Know
To start writing JavaScript effectively, it's important to understand how the language is structured. This section will walk you through the fundamentals of JavaScript syntax, including variables, data types, spacing, and more.
Where Do You Write JavaScript Code?
As mentioned earlier, JavaScript code can be:
-
Written inside an HTML file using the
<script>
tag -
Placed in a separate file with a
.js
extension and linked using thesrc
attribute
Character Set
JavaScript uses the Unicode character set, which supports almost all characters from every language, as well as symbols, punctuation marks, and emojis. This makes it versatile and globally usable.
Case Sensitivity
JavaScript is case-sensitive, meaning:
-
name
is different fromName
-
myFunction
is different fromMyFunction
Be consistent with how you name variables and functions to avoid unexpected errors.
Variables
Variables store data like numbers, text, or boolean values. You can declare a variable using:
-
var
(older, but still used) -
let
(preferred for block-scoped variables) -
const
(for values that shouldn’t change)
Example:
Semicolons
Semicolons (;
) are used to separate statements in JavaScript. While they are optional, it's a good practice to include them for better readability and to prevent certain parsing errors.
Whitespaces
JavaScript ignores extra spaces and tabs. These two lines do the same thing:
Use spacing to keep your code clean and readable—it won’t affect how the code runs.
Comments
Comments help explain your code. JavaScript ignores them when running the script.
-
Single-line comment starts with
//
-
Multi-line comment is wrapped in
/* */
Example:
Strings
A string is a piece of text. You can wrap it in single or double quotes.
Numbers
JavaScript handles whole numbers (integers), decimals (floats), and even hexadecimal values. Just don’t wrap numbers in quotes.
Booleans
Booleans represent true or false values.
They’re commonly used in conditionals like if
statements.
Keywords (Reserved Words)
JavaScript has reserved words that you cannot use as variable names or function names. These are part of the language's syntax.
Common Reserved Keywords:
Control Flow | Functions & Objects | Values/Operators |
---|---|---|
if | function | true , false |
else | return | null |
for | class | new , typeof |
while | this | void , delete |
switch | try , catch | in , instanceof |