JavaScript - Syntax




JavaScript - Syntax

JavaScript syntax refers a set of rules which define how the language is written and interpreted by the browser. Here are some basic rules for JavaScript syntax −

JavaScript syntax refers to a set of rules that determine how the language will be written (by the programmer) and interpreted (by the browser).

JavaScript syntax is the set of rules, how JavaScript programs are constructed -

var x, y, z;       // How to declare variables
x = 6; y = 7;      // How to assign values
z = x + y;         // How to compute values

You will learn what each of these statements means in upcoming chapters.

What is an JavaScript Syntax ?

The JavaScript syntax is loosely based on the Java syntax. Java is a full blown programming environment and JavaScript could be seen as a sub-set of the Java syntax. Having said this, that is where the similarities end Java and JavaScript are two totally different things. By learning JavaScript you will become familiar with terms such as variables, functions, statements, operators, data types, objects etc. It would take much more than a short tutorial to cover the complete JavaScript syntax. However, this tutorial covers the syntax basics that will enable you to code JavaScript in a proficient manner. For now, I'll give you a quick intro by showing you an example and explanation.

Like any other programming language, JavaScript has a set of specific rules for writing code. These rules are called JavaScript syntax. Writing JavaScript code neatly and syntactically correct makes your code bug-free and easy to read. In this JavaScript syntax tutorial, you'll find the rules for writing JavaScript code. You will learn correct capitalization of function names, variables, and other identifiers. You'll also find examples which will show you how JavaScript code should be written.

JavaScript Syntax

This is a collection of specific rules on how programs in JavaScript are constructed. You should follow these rules to maintain your code neat and bug-free. JavaScript statements may include any of these things, operators, values, keywords, expressions, and comments.

Syntax and Case Sensitivity

By definition, a computer program is like a list of instructions for the computer to execute. We refer to these instructions for the computer as statements. However, JavaScript gives commands to the web browser instead of the computer itself. JavaScript statements don't need to be placed in parentheses or braces. They are, however, separated by semicolons -

Example

var a = 7;
var b = 7;
var c = a + b;

JavaScript Syntax

14

In JavaScript, identifiers are used to name variables, keywords, functions, and labels. Their naming rules are not much different from any other programming language. To begin with, the first character of an identifier has to be either a letter, a dollar sign ($), or an underscore (_). So, for example, A, _, or $ in JavaScript are all identifiers. The following characters can be digits, letters, underscores, or dollar signs.

Each JavaScript identifier is case sensitive: for example, Name and name, are not the same variable in JavaScript -

Example

Name = "Riya";
name = "Riya"; // Now we have two separate string variables

JavaScript is Case Sensitive

Riya

Whenever case sensitivity is relevant, it's important to have a clear standard of writing names that consist of more than one word. Throughout the history of programming, there have been three most popular methods to achieve that: hyphens (first-name), underscores (first_name), and camel case (FirstName).

Camel case is the default identifier writing method in JavaScript and many other programming languages. Keep in mind though that in JavaScript the identifier name usually begins with a lowercase letter (firstName)

Types of Literals

Literals define fixed values used in JavaScript. There are a few types of literals we use, and they have their own rules to be followed. Number literals, according to JavaScript syntax, can be written with or without the decimal point. This is shown in the example below -

12.50
125

JavaScript Numbers

12.5

125

Another type of a literal is a string. It defines a piece of text within quotes. String values can be written in single or double quotes -

Example

var name1 = "value1";
var name2 = 'value2';

JavaScript Syntax Rules

JavaScript is a simple language, but you do need to be careful to use its syntax—the rules that define how you use the language—correctly. The rest of this book covers many aspects of JavaScript syntax, but there are a few basic rules you should understand to avoid errors.

Case Sensitivity

Almost everything in JavaScript is case sensitive, you cannot use lowercase and capital letters interchangeably. Here are a few general rules, JavaScript keywords, such as for and if, are always lowercase. Built-in objects such as Math and Date are capitalized. DOM object names are usually lowercase, but their methods are often a combination of capitals and lowercase. Usually capitals are used for all but the first word, as in toLowerCase and getElementById. When in doubt, follow the exact case used in this book or another JavaScript reference. If you use the wrong case, the browser will usually display an error message.

Variable, Object, and Function Names

When you define your own variables, objects, or functions, you can choose their names. Names can include uppercase letters, lowercase letters, numbers, and the underscore (_) character. Names must begin with a letter or underscore. You can choose whether to use capitals or lowercase in your variable names, but remember that JavaScript is case sensitive: score, Score, and SCORE would be considered three different variables. Be sure to use the same name each time you refer to a variable.

Reserved Words

One more rule for variable names—they must not be reserved words. These include the words that make up the JavaScript language, such as if and for, DOM object names such as window and document, and built-in object names such as Math and Date. A complete list of reserved words is included in Appendix D, "JavaScript Quick Reference.

Spacing

Blank space (known as whitespace by programmers) is ignored by JavaScript. You can include spaces and tabs within a line, or blank lines, without causing an error. Blank space often makes the script more readable.

Understanding the JavaScript Syntax

<script>   
document.write("Basic Print method in JavaScript");   
</script>

JavaScript syntax refers to the set of rules that determines how JavaScript programs are constructed -

// Variable declaration
var c, d, e;

// Assign value to the variable
c = 8; 

// Computer value of variables
d = c;
e = c/d;

JavaScript Comments

Comments refer to the text or code in a program that is ignored at the time of executing the program. Comments are used to provide additional information in the code, such as the description of code. And it is considered as good practice to add comments to your code. Similar to other programming languages like C, C++, etc., JavaScript also defines two types of comments. Single line Comments, and Multiline Comments, friends Let's take an example and understand how we can add these in our JavaScript code.

<html>
<head>
    <title>JavaScript Comment Example</title>
    <script>
    // This is an single line comment and it will not be executed
    /*
        This is a multiline comment and everything written 
        inside this block will not be executed. 
    */
    var x = 20;
    var y = 3*x;
    </script>
</head>
<body>
    <!-- Some HTML code - This is HTML comment -->
</body>
</html>

JavaScript Statements

If expressions are single units of JavaScript that the engine can evaluate, statements can contain one or more different expressions, and are executed by the engine to perform an operation. programs are composed by multiple statements. Statements can span over multiple lines. Just like with expressions, JavaScript has a whole different set of statements:

  • Expression statements

  • Declaration statements

  • Control flow statements

  • Loop statements

  • Miscellaneous statements

Expression statements

An expression on its own is also a statement -

2
0.02
'something'
true
false
this //the current scope
undefined
i //where i is a variable or a constant
1 / 2
i++
i -= 2
i * 2
'A ' + 'string'
[] //array literal
{} //object literal
[1,2,3]
{a: 1, b: 2}
{a: {b: 1}}
a && b
a || b
!a
object.property //reference a property (or method) of an object
object[property]
object['property']
new object()
new a(1)
new MyRectangle('name', 2, {a: 4})
function() {}
function(a, b) { return a * b }
(a, b) => a * b
a => a * 2
() => { return 2 }
a.x(2)
window.resize()

Declaration statements

With a declaration statement you assign a value to a variable name.

var i = 0
let j = 1
const k = 2

//declare an object value
const car = {
  color: blue
}

Control flow statements

Statements can be grouped, using a block -

{
  //this is a block
  const a = 1;
  const b = 2;
}

Using this syntax, you can have multiple statements whenever JavaScript expects a single statement. Be aware that any of the conditional control flow statements check an expression and depending on it they execute a statement, or a block -

if (condition === true) {
  //execute this block
} else {
  //execute this block
}

Loop statements

Loops work similarly to the if example above. Some loops check an expression, and repeat a statement execution it until that expression evaluates to true. Some other loops iterate over a list and execute a statement (or block) for each element of the list, until the list finishes.