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.

Page Bookmarks

Script Tag

Learning JavaScript starts with the syntax. We introduce JavaScript using HTML tag <script>, because JavaScript was design to run in the browser. It's primary function is to make a website dynamic. For this you can use "document" object. Let's start with an example and then we explain it.

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:

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 chains

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:

Keywords:

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

Keyword Description
async Used to declare an asynchronous function, which returns an AsyncFunction object.
await Used to pause the execution of an asynchronous function until the promise is settled.
break Used to break out of a loop or switch statement.
case Used in a switch statement to specify a case matching the condition.
catch Used to catch errors thrown by try block.
class Used to declare a class.
const Used to declare a constant variable.
continue Used to skip one iteration of a loop.
debugger Used to debug code by pausing execution at a debug point.
default Used in a switch statement to specify the default case when no case matches the condition.
delete Used to remove a property from an object.
do Used to start a do-while loop.
else Used to specify what to do if the condition in an if statement is false.
export Used to export functions, variables or classes from a module.
extends Used to create a subclass (derived class).
false A boolean keyword that represents a false value.
finally Used to execute code regardless of the result of the try block.
for Used to start a for loop.
function Used to declare a function.
if Used to specify a test condition to be executed.
import Used to import functions, variables or classes from a module.
in Used to check if a property is in an object.
instanceof Used to check if an object is an instance of a specified object.
let Used to declare a block-scoped variable.
new Used to create an instance of an object.
null A keyword that represents a null value.
return Used to return a value from a function.
switch Used to specify different code blocks to be executed.
this Used to refer to the current object.
throw Used to throw (generate) an error.
true A boolean keyword that represents a true value.
try Used to test a block of code for errors.
typeof Used to return the data type of an operand.
var Used to declare a variable.
void Used to return an undefined value from a function.
while Used to start a while loop.
with Used to specify the default object for a statement block.
yield Used to pause and resume a generator function.

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