# JavaScript Overview

Provided within this overview are brief sections detailing the important aspects of the JavaScript language for use with applications.

Note:

The information provided in this overview topic is intended for users already familiar with the basic principles of programming.

For more in-depth information about the JavaScript programming language, please consult the following (Internet access is required):

- Mozilla JavaScript Guide
- Mozilla JavaScript Language Reference
- "JavaScript: The Definitive Guide" by David Flanagan

## WebHMI and Type Compatibility with C# Applications

For information about WebHMI, see WebHMI: Functional Overview, Compatible Types, and an Example.

For an overview of data type compatibility between WebHMI JavaScript and native C# applications, see WebHMI: Type Compatibility .

### JavaScript Restrictions when Using WebHMI

- JavaScript is only allowed for use within the WebHMI.
- JavaScript is only executed on the Web client. JavaScript is not executed on the Cognex Designer Task.
- JavaScript is not available as a User Script or Script Block.
- C# scripting is not available in the WebHMI.
- $API properties and functions from the WebHMI are not available to WPF HMI, and vice-versa. For example, a user can't change the WPF HMI's page from the WebHMI.

- Existing WPF Forms controls are not available in WebHMI.

## Basic Lexical Structure

The implementation of JavaScript follows version 5 of the open standard approved by the European Computer Manufacturer’s Association, also known as ECMAScript 5 (ECMA5). It utilizes the Unicode 3 (or later) character set (UTF-8), and is similar to C, C++, C# and Java syntax in the following ways:

- The language is case-sensitive, which requires language keywords, variables, function names and other identifiers use a consistent capitalization of letters.
- Identifiers are used to name variables and functions, and must begin with a letter, an underscore (_) or a dollar sign ($). Digits are not allowed at the beginning.
- Compound statements are contained within curly braces ({}).
- White space is ignored, thus allowing cleanly formatted code that is easy to read and understand.

- Semicolons (;) separate statements, and while these are optional at the end of a line, they are highly recommended to explicitly demarcate the end of a statement.

  If statements are on separate lines, they can be omitted. However, JavaScript always interprets line breaks as a semicolon, so never insert a line break between return, break or continue and the expression that follows those keywords.

## Comments

There are two styles of denoting comments in JavaScript: two forward slashes (//) at the end of a line denote comments, and any characters within /* and */ are also treated as comments (/* JavaScript comments */).

The following illustrates the two styles of denoting comments:

    /* JavaScript comments */
    var x; // Look like Java, C# and
    	 // C++ comments
    /*
    * And they can occupy
    * multiple lines.
    */

Note: Comments can be removed through minification.

## Supported JavaScript Types when Using WebHMI

The following types are supported when writing JavaScript for WebHMI: Functional Overview, Compatible Types, and an Example.

### Primitive Types

- Boolean
- char
- byte
- sbyte
- int16
- uint16
- int32
- uint32
- int64
- uint64
- integer
- single
- double (real)
- String
- DataSet
- Note: No other types can be transferred or interpreted by the WebHMI or JavaScripts.

### Primary Runtime Types

Primary Runtime Types encompass all objects described in the section Developing a Cognex Designer Project. For example, Tags, Tasks, Pages, and Devices are all objects you can use to program with JavaScript using Cognex Designer’s API.

There are some restrictions when using Primary Runtime Types. WebHMI and JavaScript types. For example, if you have $Tag of type CogPMAlignPattern, you cannot access that tag in a WebPage for binding or in a JavaScript script. This $Tag will be accessible, however, in the C# scripts for the WPF HMI, Tasks, and User Scripts.

For binding in a WebPage, ICogImage and ICogRecord will be available to bind to the Display controls’ source property, but cannot be accessed via JavaScript.

### Image Types

For images, only the following types can be displayed on the HMI.

- ICogImage
- CogImage8Grey
- CogImage24
- PlanarColor
- ICogRecord
- CogRecord
- Note:
  - No 3D graphic support is available.
  - Objects derived from these classes will not work.
  - Image tags are not accessible from JavaScripts.

## Variables

Variables are used to define a symbolic name for an object or a value, and allows it to be referred to by its symbolic name. Within JavaScript, there are two types: primitive types and object types. Every variable refers to a primitive value (number, string, true/ false, null or undefined) or an object, which is defined as a non-primitive value.

Variables are declared with the var keyword, as shown in the examples below:

                var aBc, zz32;
    var q = "abc", r = 'f';
    var p = true, q = false;

### Variable Scope

Variables are either scoped globally or functionally. A variable declared outside of any functions has a global scope and is available to all code within the Script module in which they are declared. A variable declared in a function is available only within the body of the function.

## Objects and Arrays

In JavaScript, any non-primitive value is considered to be an object; a property that has a name and a value, which can either be a primitive value or another object. While an object is essentially an unordered collection of named values, an array is an ordered collection of numbered values.

### Object Properties

Within JavaScript, objects are dynamically typed:

- Every object is a dictionary of properties.
- Each property is a name-value pair.
- Properties are added and removed at run time.

Properties are inherited from a prototype object:

- As if each new object is a copy of its prototype.
- The prototype may in turn derive from a prototype of its own.

## Property Syntax

JavaScript uses two types of syntax for defining property access. The following syntax should be followed for properties (with either type, the expression before or after the dot or square bracket is evaluated first):

- Dot notation:

      a.prop = 123;	// Adds a property

      b = a.prop;	// 123

                              delete a.prop;	// Removes the property

      c = a.prop;	// undefined

- Square brackets with a name and/or string:

      a ["break 1"] = 123	// Adds a property

      b = a["break 1"];	// 123

      nm = "break 1";	// Can use a variable

      c = a[nm];		// 123

                              delete a[nm]		// Removes the property

## Object Literal Syntax

To create a new object, use a comma-separated list of name:value pairs, as shown below:

                var myrectangle = {
    	width: 100, height: 50,
    	"return": {a:1, b:2, c:3},
    	getArea: function() {
    	   return this.width * this.height;
    	}
    };

## Arrays

Within JavaScript, arrays are just like regular objects, but use numerical property names, as shown below.

Note: The length property is one plus the highest numbered element.

                var a = []; 	// Empty
    var b = [9.5, "Fred", true];
    var c = b[1];	// "Fred"
    var d = b["1"]// "Fred"
    var e = b[9]	// undefined
    b[3] = 2;	// adds 1 element
    b.newProperty = "hello"

## Built-in JavaScript Classes

The following are examples of built-in JavaScript classes.

- Array: sort, reverse, concat, slice, push, pop, shift, unshift
- Math: abs, min, max, sqrt, ceil, floor, sin, cos, tan, asin, acos, atan
- String: indexOf, match, replace, split, substring, toUpper, toLower, trim
- Date: new Date(), toString, add, subtract

## Numbers

JavaScript represents all numbers using the 64-bit floating-point format defined by the IEEE 754 standard. When a number appears in a JavaScript program, it’s referred to as a numeric literal. The following illustrates how JavaScript represents numbers and numeric literals:

- Base 10: 1, 47, 3.14, -24e-13
- Base 16: 0x7fff

## String Literals

The following are examples of string literals used in JavaScript:

                "Hello I'm Fred"
    'I am "Sam", I am'
    "Hello\t \"World \" \x0D \u000A"
    "Hello \big \world" (EC5)

## Functions

A function is a special kind of object, which has executable code associated with it, and can be invoked to run that code and return a value. Functions, like arrays, behave differently than objects, and have a special language syntax for working with them. Most importantly, they are true values, and programs can treat them like regular objects.

Functions are defined using the function keyword, and arguments and return are optional. The following forms are equivalent:

                function  sum(x, y) {
      return x + y;
    }
    var sum = function (x, y) {
      return x + y;
    }

## Variadic Functions

Within JavaScript, any function can take a variable number of arguments; the arguments keyword is an array of the current function’s arguments. The following demonstrates this:

                function sum() {
      var i, total = 0;
      for (i=0; i < arguments.length; i++) {
        total += (+arguments[i]);
      }
      return total;
    }
    var z = sum(1,2, "3.14");	// 6.14

- Its own arguments and variables.
- Its parent function’s variables.
- As properties of the global object.

## Expressions and Operators

The following are the common expressions and operators used in JavaScript:

- Primary: (x) x.y f(x,y,z) a[x]
- Unary: +x –x !x ++x –x x++ x-- ~x32
- Multiplicative: * / %
- Additive: - + (+ is also used for string concatenation)
- Shift32: << >> (sign extend) >>> (zero extended)
- Relational: < > <= >= (alphabetical for strings)
- Equality: == != === !== (strict equality/inequality)

- Bitwise32

  - AND: &
  - OR: |
  - XOR: ^
  - Conditional AND: &&
  - Conditional OR: ||
  - Conditional if: ?:
- Assign: = *= /= %= += -= &= ^= |= <<= >>= >>>=

## Type Conversion

Values are converted automatically whenever needed (and if possible), and operators are left-associative. When converting, be aware of weak equality statements, such as the following:

                if ("4" == 2 * 2)	// true
    if ("4" === 2 * 2)	// false

“False” values convert to false (undefined, null, 0, -0, NaN, “”), and all other values convert to true (if (“false”) {…} // true).

## typeof Operator

The typeof operator returns a string identifying the type of its operand:

Value | typeof value ==
--- | ---
Null | “null”
Undefined | “undefined”
Any number (NaN) | “number”
A string | “string”
True/False | “boolean”
Any function | “function”
Any object | “object”

## if Statement

Within JavaScript, if statements use the same syntax as C:

                if (x>0) {
      y = Math.Sqrt(x);
    }
    else if (x == 0) {
      y = 0;
    }
    else
      y = undefined;	// braces optional
    			// (but recommended)

## switch Statement

Within JavaScript, switch statements are similar to C, but are also able to use strings, as well:

     switch (name) {
      case "Fred":
        processFredReport();
        break;
      case "Sam":
      case "Samantha":
        processSamReport();
        break;
      case 911:	// also matches "911"
        emergencyAlert();
    		// Fall through (discouraged)
      default:
        return "Unable to process report!";
    }

## Looping

There are several methods to create loops within JavaScript.

- For

                          for (var x = 0; x < 100; x++) {...}

- While

                          while (!inputFile.isAtEnd()) {...}

- Do While

                          do {...} while (foundItem==0);

- For/in

                          for (var propName in myObject) {...}

  Note: The property order is not guaranteed.

- Break

  This is used to exit the enclosing loop:

                          if (foundRecord) break;

- Continue

  This is used to begin the next loop iteration:

                              if (skipThisItem) continue;

## Exceptions

Exceptions are used to indicate that an exceptional condition or error has occurred. A throw signals that an error occurred, while the try/catch/finally statement is used by JavaScript to handle an exception or error.

## Throwing Exceptions

The following demonstrates how to throw an exception within JavaScript:

                if (area <= 0) {
      throw new Error("area must be positive");
      --or--
      throw 'Invalid argument';
      --or--
      throw radius * 3.14;	// not normally used but legal
    }

## Try/Catch/Finally Block

The try clause defines the block of code that contains the exception to be handled, and is followed by either a catch or finally clause. These two are optional, however, the try block must be followed by at least one of them. The following illustrates how to handle an exception or error in JavaScript:

                try {
      sendAllOutput(stream);
    }
    catch(ex) {				// optional (but one is required)
      console.log (ex);
    }
    finally {				// optional (but one is required)
      stream.close();
    }

## Regular Expressions

The following are examples of regular expressions commonly used in JavaScript.

                var x1 = new RegExp("[a-z].*");

                var x2 = /[a-z].*/;

The test method returns true on a match:

    valid = x1.test(input);

The exec method returns multiple results:

                var x3 = /Tool\d*;
    while (r = x3.exec(text))
    {
      console.log("Found" + r[0] +
        "at" + r.index +
        "now at" + x3.lastIndex);
    }

## Strict Mode

Strict mode of ECMAScript5 executes strict code using the “use strict” directive. This implements a restricted subset of the language which fixes a few deficiencies and provides stronger error checking and increased security.

Follow the following guidelines to implement strict mode:

- Begin the script with "use strict";.

- All variables must be declared with var.

  In non-strict mode, assigning an undeclared variable adds it to the global object while strict mode will throw an error and prevents accidentally creating a global variable.

- The with statement is not allowed.

- For function invocations (not methods) this === undefined.

  In non-strict code, this === invokes the global object.

Note: For more information on Strict Mode visit the w3school website topic JavaScript Use Strict (internet access required.)