Web Kokua Banner Image

Javascript Language

JavaScript, often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.

Web browsers have a dedicated JavaScript engine that executes the client code. These engines are also utilized in some servers and a variety of apps. The most popular runtime system for non-browser usage is Node.js.

JavaScript is a high-level, often just-in-time compiled language that conforms to the ECMAScript standard. It has dynamic typing, prototype-based object-orientation, and first-class functions. It is multi-paradigm, supporting event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM).

The ECMAScript standard does not include any input/output (I/O), such as networking, storage, or graphics facilities. In practice, the web browser or other runtime system provides JavaScript APIs for I/O.

Although Java and JavaScript are similar in name and syntax, the two languages are distinct and differ greatly in design.

Variables

In Javascript there are basically three ways to declare a variable:

var

Declares variables with function or global scope and allows re-declaration and updates within the same scope.

var name1; var name1 = value1; var name1 = value1, name2 = value2; var name1, name2 = value2; var name1 = value1, name2, /* ..., */ nameN = valueN;

let

Declares variables with block scope, allowing updates but not re-declaration within the same block.

let name1; let name1 = value1; let name1 = value1, name2 = value2; let name1, name2 = value2; let name1 = value1, name2, /* ..., */ nameN = valueN;

const

Declares block-scoped variables that cannot be reassigned after their initial assignment.

const name1 = value1; const name1 = value1, name2 = value2; const name1 = value1, name2 = value2, /* ..., */ nameN = valueN;

Block Scope

Scope, with regards to variables, has to do with where the variables are visible or useable to the code. Global scope means that it is visible and useable anywhere within the code. Block scope is contained to the block where the declaration exists. Blocks are enclosed between braces {...}


Control Flow

All computer programming languages have a set of different statements that define the flow of a program. In many of them, the syntax is the same.

If Then Else

if (condition) { statement1; } else { statement2; } if (condition1) { statement1; } else if (condition2) { statement2; } else if (conditionN) { statementN; } else { statementLast; }

Switch

switch (expression) { case label1: statements1; break; case label2: statements2; break; // ... default: statementsDefault; }

Do While

do { // STATEMENT } while (condition);

While Do

while (condition) { // STATEMENT }

For Next

for (initialization; condition; afterthought) { // STATEMENT } // SCRIPT 1 for (let x=0; x<10; x++) { // STATEMENT } // SCRIPT 2 for (let x=0, y=1; x<10, y<9; x++, y++) { // STATEMENT } // SCRIPT 3 for (let x=0, y=10; x<10, y>0; x++, y--) { // STATEMENT } // SCRIPT 4 for (let x=0; x<10; x=x+2) { // STATEMENT } // SCRIPT 5 for (let x=1; x<10; x=x+2) { // STATEMENT } // SCRIPT 6 for (let x=0; x<100; x=x+10) { // STATEMENT }



For In

for (variable in object) { // STATEMENT } const obj = { a: 1, b: 2, c: 3 }; for (const prop in obj) { rStr += "obj."+ prop +"="+ obj[prop] +"<br/>"; }


For Of

for (variable of object) { // STATEMENT } const arr = [3, 5, 7]; for (const i in arr) { // FOR IN LOOPS OVER INDEXES console.log(i); } for (const i of arr) { // FOR OF LOOPS OVER VALUES console.log(i); } function for_in_02(result_name) { let result = document.getElementById(result_name); let rStr = ""; let arr = [3, 5, 7]; rStr += "Array Length: " + arr.length + "<br/>"; for (let i in arr) { rStr += i + " "; } result.innerHTML = rStr; } function for_of_01(result_name) { let result = document.getElementById(result_name); let rStr = ""; let arr = [3, 5, 7]; rStr += "Array Length: " + arr.length + "<br/>"; for (let i of arr) { rStr += i + " "; } result.innerHTML = rStr; } function for_of_02(result_name) { let result = document.getElementById(result_name); let rStr = ""; let obj = { age: 51, id: 2324, fname: "Duke", lname: "Silver" }; rStr += "Obj Length: " + Object.keys(obj).length + "<br/>"; //var size = Object.keys(myObj).length; for (let [key, val] of Object.entries(obj)) { rStr += "key: "+ key +" val: "+ val +"<br/>"; } result.innerHTML = rStr; }


Data Structures & Types

The latest ECMAScript standard defines eight data types. Seven are known as Primatives and the eighth is the javascript Object.

Primatives
Boolean True or false.
null A special keyword denoting a null value. (Because JavaScript is case-sensitive, null is not the same as Null, NULL, or any other variant.)
undefined A top-level property whose value is not defined.
Number An integer or floating point number. For example: 42 or 3.14159.
BigInt An integer with arbitrary precision. For example: 9007199254740992n.
String A sequence of characters that represent a text value. For example: "Howdy".
Symbol A data type whose instances are unique and immutable.
Non-Primative
Object In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String value or a Symbol value. There are two types of object properties: The data property and the accessor property.

Literals

Literals represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script.

Array Literals
Boolean Literals
Numeric Literals
Object Literals
Regexp Literals
String Literals

Literal Examples

// ARRAY LITERAL const coffees = ["French Roast","Columbian","Kona"]; // EMPTY ELEMENTS coffees[1] = undefined const coffees = ["French Roast",,"Columbian","Kona"]; // THE LENGTH OF THE FOLLOWING ARRAY IS 3. // myList[0] = undefined, myList[1] = "home", myList[2] = undefined, myList[3] = "school" const myList = [, "home", , "school"]; // THE LAST COMMA IS IGNORED // myList[0] = "home", myList[1] = undefined, myList[2] = "school", myList[3] = undefined const myList = ["home", , "school", ,]; // BOOLEAN LITERALS ARE true OR false // INTEGER LITERALS const myint = 0; // DECIMAL BASE 10 const myoct = 015; // OCTAL BASE 8 const myhex = 0x1123; // HEXIDECIMAL BASE 16 const mybin = 0b0011; // BINARY BASE 2 // FLOATING POINT SYNTAX [digits].[digits][(E|e)[(+|-)]digits] // FLOATING POINT LITERALS const myfloat = 3.14159; const myfloat = .123456789; const myfloat = 3.1E+12; const myfloat = .1e-23; // STRING LITERALS var mystring = 'foo'; var mystring = "bar"; var mystring = '1234' var mystring = 'One line\n Another line'; var mystring = "Sentence with an apostrophy. Dirk's computer." // REGULAR EXPRESSION LITERALS const re = /ab+c/;

Object Literals

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Note: Do not use an object literal at the beginning of a statement! This will lead to an error (or not behave as you expect), because the curly brace will be interpreted as the beginning of a block.

The following is an example of an object literal. The first element of the car object defines a property, myCar, and assigns to it a new string, "Saturn"; the second element, the getCar property, is immediately assigned the result of invoking the function (carTypes("Honda")); the third element, the special property, uses an existing variable (sales).

const sales = "Toyota"; function carTypes(name) { return name === "Honda" ? name : `Sorry, we don't sell ${name}.`; } const car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales }; console.log(car.myCar); // Saturn console.log(car.getCar); // Honda console.log(car.special); // Toyota

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

const car = { manyCars: { a: "Saab", b: "Jeep" }, 7: "Mazda" }; console.log(car.manyCars.b); // Jeep console.log(car[7]); // Mazda

Template Literals

Template literals are enclosed by the back-tick (`) (grave accent) character instead of double or single quotes. Template literals provide syntactic sugar for constructing strings. (This is similar to string interpolation features in Perl, Python, and more.)

// Basic literal string creation `In JavaScript '\n' is a line-feed.` // Multiline strings `In JavaScript, template strings can run over multiple lines, but double and single quoted strings cannot.` // String interpolation const name = 'Lev', time = 'today'; `Hello ${name}, how are you ${time}?`

Tagged templates are a compact syntax for specifying a template literal along with a call to a "tag" function for parsing it. A tagged template is just a more succinct and semantic way to invoke a function that processes a string and a set of relevant values. The name of the template tag function precedes the template literal — as in the following example, where the template tag function is named print. The print function will interpolate the arguments and serialize any objects or arrays that may come up, avoiding the pesky [object Object].

const formatArg = (arg) => { if (Array.isArray(arg)) { // Print a bulleted list return arg.map((part) => `- ${part}`).join("\n"); } if (arg.toString === Object.prototype.toString) { // This object will be serialized to "[object Object]". // Let's print something nicer. return JSON.stringify(arg); } return arg; }; const print = (segments, ...args) => { // For any well-formed template literal, there will always be N args and // (N+1) string segments. let message = segments[0]; segments.slice(1).forEach((segment, index) => { message += formatArg(args[index]) + segment; }); console.log(message); }; const todos = [ "Learn JavaScript", "Learn Web APIs", "Set up my website", "Profit!", ]; const progress = { javascript: 20, html: 50, css: 10 }; print`I need to do: ${todos} My current progress is: ${progress} `; // I need to do: // - Learn JavaScript // - Learn Web APIs // - Set up my website // - Profit! // My current progress is: {"javascript":20,"html":50,"css":10}

Since tagged template literals are just sugar of function calls, you can re-write the above as an equivalent function call:

print(["I need to do:\n", "\nMy current progress is: ", "\n"], todos, progress);

This may be reminiscent of the console.log-style interpolation:

console.log("I need to do:\n%o\nMy current progress is: %o\n", todos, progress);

You can see how the tagged template reads more naturally than a traditional "formatter" function, where the variables and the template itself have to be declared separately.


Special Characters

Character Meaning
\0 Null Byte
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab
\v Vertical Tab
\' Apostrophy
\" Double Quote
\XXX The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXX The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXX The Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol.
\u{XXXXX} Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.

Special Characters

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

const quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; console.log(quote);

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

const home = "c:\\temp";

You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.

const str = "this string \ is broken \ across multiple \ lines."; console.log(str); // this string is broken across multiple lines.