Sage-Code Laboratory
index<--

JavaScript Syntax

JavaScript syntax is derived from C. It uses the same comments and is a curly bracket language. Some symbols and operators are borrowed from C. However it has different keywords and semantic.In this chapter we present a general overview. Let's get started with an example.

Example:

This is an HTML fragment containing JavaScript code:
<script>
   /* a simple JavaScript program
      to demonstrate basic syntax features */
   let greeting = "Hello, World!";
   document.write(greeting); //output
</script>

Notes:

  1. After <script> tag that belongs actually to XHTML you can observe the second and third and forth lines, separated by symbols: /* … */. This is called a "block" comment. It is the same as C comment.You can use block comments to outline a region of code.
  2. Second form of comment is using two symbols: "//". This is called single line comment, and the same symbol can be used to create end of line comments.
  3. In JavaScript a line of code should end with semi-column. ";". However many times this symbol is optional. JavaScript is forgiving, and will infer the end of statement for you.
  4. Can you spot the variable declaration? It is done using "let" keyword followed by operator "=" and a string literal "Hello, Worlds!", that is enclosed in double quotes. The variable is therefore a string in this case. Java do not require explicit type declarations.

Details:

Keywords:

JavaScript may have been started as a small language but now it has 64 keywords, and this is not at all small any longer. Also is more difficult to master than it use to be.

abstractargumentsawait*boolean
breakbytecasecatch
charclass*constcontinue
debuggerdefaultdeletedo
doubleelseenum*eval
export*extends*falsefinal
finallyfloatforfunction
gotoifimplementsimport*
ininstanceofintinterface
let*longnativenew
nullpackageprivateprotected
publicreturnshortstatic
super*switchsynchronizedthis
throwthrowstransienttrue
trytypeofvarvoid
volatilewhilewithyield

Expressions

One expression is an enumeration of identifiers and literal constants separated by operators and separators. An expression can be evaluated in JavaScript console. Larger expressions can be created using smaller expressions that are enclosed in round parenthesis.Expressions can be captured into variables using "=" that is assign operator.

/* Examples of expressions: */
(6+12)/3                  //a numeric expression
a =  (1+1)                //assign result of expression (1+1) to a variable
a >= 2                    //Boolean logic expression (true)
b = a == 2                //Capture Boolean expression (a == 2)
"this was" +"  "+"a test" //string expression

Homework: Open JavaScript console (Shift+Ctrl+J) and create the expressions one by one as they are presented in the example above.I have run this homework using Chrome browser console and I have captured the screen so you can do it to and have the same results:

Responsive Image

Chrome JavaScript Console

Statements

JavaScript is a structured language. That means its syntax is based on statements. A statement represents one or more lines of code.One JavaScript subprogram or script can have one or more statements.Statements are created using keywords, operators, expressions and separators.There are many kind of statements: declarations, assignments, function calls ... etc.

Example:

In the example below we show you a special statement that is called: anonymous block. It start with separator "{" that marks the beginning of the block and it ends with separator:"}" that marks the end of the block. This notation is specific to all curly-based languages.

{
  /* single line statements */
  let a = 10, b = 20;
  console.log(a+b);

  /* nested anonymous block*/
  {
     let c = 30;
     console.log(c);
  }
}

Notes:

Ternary expressions

A ternary expression is an intelligent expression that makes a decision and calculate one result or another depending on condition value. Remember a logical condition can use relation operators or logical operators to create a boolean response.

Syntax:

condition ? first_expression : second_expression;
Notes:

Example:

In next example we create a function: draw(). A function is a block of code that has a named can be executed multiple times. We explain later in details how to make functions in JavaScript.In this example focus on conditional assignment, that use ternary operator "?" to make a ternary expression.

/* function that return random (0,1) */
function draw() {
/* generate a number between 0 and 1*/
   let x = Math.random();
/* conditional assignment */
   let y = x > 0.5 ? 1: 0;
   return String(y);
}
// call draw() function several times
console.log(draw()+draw()+draw()); //010
console.log(draw()+draw()+draw()); //110

Conditional chain

The ternary operator is right-associative, which means it can be chained.Most developers do not use conditional chains and prefer to use nested "if" statements.Therefore we do not insist on chains.Next fragment is not real code but a "design pattern" that look like code (pseudo-code).

function example(…) {
 return condition1 ? expression1:
 condition2 ? expression2:
 condition3 ? expression3:
 default_expression;
}

Notes:

Debugging Code

During development, you run your JavaScript code often to find errors. This process is called debugging. A "bug" in programming is not an insect but an unexpected situation called "error" or "bug". To find them you need to test your code multiple times.

Logical errors: The most common technique to find JavaScript errors is to introduce a "spy". This is a line of code that display a message to console that you can investigate.If the message produce unexpected output, you are about to find an unexpected logical error.

Syntax errors: These errors are produced during runtime. Your code execute until a syntax error is encountered. Then the program is stopping its execution and you can read a usually red message about the error. For these kind of errors you do not need to create a "spy" statement.

Step by step: Sometimes the error is difficult to find. The last resort is to run a script step by step. This require to set a "breakpoint". This is not a script element it is a location (a statement number) that is flagged by the IDE with a red dot. When your script reach that specific point, it will suspend.

Inspection:  You can inspect values of variables (in scope) using using special window that can show the objects and the values from memory. After the inspection you can press a button and the script can resume running one step at a time or it can run up to next "breakpoint" depending on the button you use.

Example:

/*spy demo*/
{ let x = 5, y = 10;
  console.log(x,y) //first spy
  x++
  y++
  console.log(x,y) //second spy
  x++
  y++
  /* better output */
  console.log("x = ",x)
  console.log("y = ",y)
}

Chrome debugger: You can debug JavaScript in Chrome.Sometimes your script is preloaded when you visit a web page.If your code is stored as a script file, you can load the script using Chrome browser and debug it by following these steps:

Chrome debug in console.
  1. Hit the F12 key or Ctrl+Shift+I;
  2. Select the Scripts , or Sources tab;
  3. Select "js/test.js" script from the tree;
  4. Add a breakpoints by clicking on the line number;
  5. Click this link to execute: test()
  6. Use F11 to run step by step.
  7. Click Console tab to see the messages.

Responsive Image

Chrome Console Source


Firefox debug in console.
  1. Hit the F12 key or Ctrl+Shift+I;
  2. Select the Debugger tab;
  3. Select "js/test.js" script from the tree;
  4. Add a breakpoints by clicking on the line number;
  5. Click this link to execute: test()
  6. Use F11 to run step by step.
  7. Click Console tab to see the messages.
Responsive Image

Firefox Console Debugger

There are much more to be explained about JavaScript syntax. However, we prefer to stop here and continue with other topics.Bookmark this page and visit later for updates. I will review this page to add more topics about syntax after I do all chapters.


Read next: Variables