JavaScript I Language Basics
Chesapeake Node.js User Group (CNUG) https://www.meetup.com/chesapeake-region-nodejs-developers-group
START BUILDING: CALLFORCODE.ORG
Agenda Introduction to JavaScript Language History Language Features Strict Directive Data Types Basic Syntax Variables Constants Operators JavaScript Object Notation (JSON) Arrays Execution Control Functions Adding modules
JavaScript Language History Developed by Brendan Eich at Netscape (1995) Turned over to the: European Computer Manufacturers Association (ECMA) Current Language Specification is ECMA-262: v8.11.3 (ECMAScript 2017) Long Term Support (LTS) v10.7.0 (ECMAScript 2017) Current Initially developed for Front-End (Web Browser) Use: Enabled Dynamic HTML (DHTML) for Browser Runtimes Over a dozen Front-End frameworks (Angular, Dojo, React) Expanded to Back-end (Server): Node.js 2009 (Express - 2010, LoopBack - 2013) npm (Package Manager) 2010
JavaScript - Language Features JavaScript variables are loosely typed. Scalars (Strings, Numbers) JSON (JavaScript Object Notation) Data Function definitions Automatic Type Conversions Strings Numbers Supports Recursion Has Object Oriented (OO) Features Sloppy vs Better Programming modes use default ; versus use strict ; directives
JavaScript - Strict Directive Directive is scoped Global (e.g. first line of program) Function (e.g. first line in a function) Variables must be declared before use Deleting ( delete ) a variable/object is not allowed Octal literals and escapes are not allowed Writing to a read/get only property is not allowed The with statement is not allowed.
JavaScript Data Types There are 7 Data Types Contain Data String Number (Integer, Floating Point, (-)Infinity, NaN) Boolean (true, false) Do Not Contain Data Null (Unknown variable or value) Undefined (Variable defined but never assigned) Object Oriented Object (Variable contains an Object instance) Symbol (Unique identifier for an Object)
JavaScript Basic Syntax Commands delimited by a semi-colon ( ; ) Comments Within a line begin with two forward slashes ( // ) Multi-line begin with /* and end with */ Code Blocks Code Blocks may be defined to control the scope of code executed in a Function, Conditional, or Looping statement. Code Blocks are begun and terminated by braces { }
JavaScript Variables (1) Variable Names Alphabetic (Upper and Lower case; A Z; a - z) Numeric (0 9); First character may NOT be numeric! Dollar Sign ( $ ) and Underscore ( _ ) Variables ARE NOT typed A named variable may contain any of the 7 Data Types The Data Type inside a variable can change over time Variables DO NOT have to be declared prior to use use strict ; - Directive requires declarations ( var )
JavaScript Variables (2) Declare variables var variablename; let variablename; const variablename; var declaration (Largest Scope) Hoists declared variable Variable considered declared at start of program / function Variable scope is therefore entire program or function Regardless of where the variable is actually declared! Variable may be redeclared without error Variable declared more than once
JavaScript Variables (3) let declaration (Limited Scope) Variables are not hoisted Variable scope is restricted Code block (braces) containing declaration Function containing declaration Variable may not be redeclared within the same scope Variable may be redeclared within a smaller scope New declaration replaces previous within declared scope const declaration (Constants) Create constant when declared; changes not allowed Variable scope is restricted (similar to let ) Variable may not be redeclared
JavaScript Variables (4) Variables may contain a single Scalar value String Number Boolean Null or Undefined (Declared but never assigned a value) Variables may contain multiple named Scalars Data JavaScript Object Notation (JSON) syntax Key : Value pairs Referenced by variablename.keyname Variables may contain Function definitions Method
JavaScript Data Strings Strings must be enclosed in quotes Three kinds of quotes o Double ( ), Single ( ), & Grave / Backtick (`) Only strings in Backticks may span lines Expressions within backticks are evaluated Numbers Integers Floats (with decimal point) Scientific (following by e9; where 9 is the Base 10 exponent) Binary (0b ), Hexadecimal (0x ) Boolean Set equal to true of false (no capitals, no quotes; not strings)
JavaScript String Escape Characters Escape Characters Within a String, the escape character indicates that the following character is to be interpreted as data. The JavaScript escape character is a backslash ( \ ) Escape Sequences \\ \n \ \ \t Backslash End of Line character(s) Quote single Quote double Tab - horizontal
JavaScript Binary Operators Assignment = (set left side equal to right side) Equality == (equality), === (strict equality; no type conversion)!= (inequality), > (greater than), >= (greater than or equal to) < (less than), <= (less than or equal to) Arithmetic + (addition if numbers or concatenation if a string) - (subtraction), * (multiplication), / (division) ** (exponentiation) Logical && (and), (or)
JavaScript Unary Operators Conversion + (convert text to number) Increment / Decrement ++ (increment) -- (decrement) Negation - (negate sign of number) Logical (Binary Operators) && (and) (or)
JavaScript JavaScript Object Notation (JSON) - 1 Variables may contain more than a single value. Multiple values are stored in Key/Value pairs. JSON is a subset of JavaScript syntax. Two syntaxes for referencing a variable Key variablename [keyname] variablename.keyname Object expressions use braces ( {, } ) Array expressions use brackets ( [, ] ) Keys and Values are separated by a colon ( : )
JavaScript JavaScript Object Notation (JSON) - 2 Key/Value pairs are separated by a comma (, ) Keys may be: Strings (Surrounded by quotes) Numbers Variable that contains a String or Number Values may be: Any JavaScript Data Type A JavaScript Function
JavaScript JavaScript Object Notation (JSON) - 3 Sample JSON in JavaScript avariable = { key1 : value1, key2 : value2 } address = { } housenumber : 5, streetname: My Street, city : My City, state : CA, zipcode : 12345
JavaScript Arrays (1) Arrays are variables containing specific JSON data Variable containing a Key of length The length value = largest numeric key + 1 Array element Keys are all numeric Object with a Symbol.iterator method (OO topic) Possible to break/mangle arrays Recommendation: Use only standard Array syntax Array Declarations array1 = [ ] ; weekdays = [ Monday, Tuesday ] ; array1 = new Array (); (Using OO Array class)
JavaScript Arrays (2) Array References Normal JavaScript variable rules apply Array elements numbered beginning with zero weekends = [ Saturday, Sunday ] ; numberofelements = weekends.length; (= 2) firstday = weekends [0]; (= [ Saturday ) lastday = weekends [weekends.length - 1]; Array Processing Special For Of loop to iterate through array elements
JavaScript Execution Control Statements Conditional if Statement (Standard syntax) if Statement (Ternary syntax) switch Statement Looping do while Statement for Statement while Statement
JavaScript Execution Control (1) Conditional Execution ( If Standard syntax) if (expression) { } else { } The expression to be evaluated is within the parentheses The else statement is optional The commands to be executed within the if and else sections are bounded by braces ( {, } ) Individual commands within the braces are terminated by a semi-colon (standard JavaScript syntax)
JavaScript Execution Control (2) Conditional Execution ( If Ternary Syntax) (expression)? truecode; : falsecode; The code to be executed however the expression is evaluated may either by a value or an expression The true and false sections are separated by a colon Each true and false expression is terminated by a semi-colon This syntax does not add any additional language capability, it is only provided as a shortened syntax
JavaScript Execution Control (3) Conditional Execution ( Switch syntax) switch (expression) { case expression1: break; } case expression2: break; default:
JavaScript Execution Control (4) Conditional Execution ( Switch continued) switch expression is compared to each case expression. If the expressions are equal, the case is executed. If a case does not have a break statement, then execution continues falling through to the next sequential case The default statement is executed if none of the other case statements apply or if no break statement was encountered.
JavaScript Execution Control (5) Loops ( Do While syntax) do { } while ( expression ); The Do While loop iterates through the loop and evaluates the expression AFTER executing the code. Individual commands within the braces are terminated by a semi-colon (standard JavaScript syntax)
JavaScript Execution Control (6) Loops ( For syntax - standard) for (initcmd, conditionalexpression, incrementcmd) { } while ( expression ) Similar to the C language for loop. Condition is evaluate BEFORE executing the loop. All of the three expressions are optional. The commas separating them, however, are not optional.
JavaScript Execution Control (7) Loops ( For syntax For In syntax) for (let avalue in avariable) { anewvariable = avariable [avalue] ; } The for in syntax loops through the JSON Key/Value pairs within a variable or object. Recommended for iterating an Object s properties. The order in which the Key/Value pairs are returned should not be relied upon.
JavaScript Execution Control (8) Loops ( For syntax For Of syntax) for (let avalue of anarray) { currentarrayelement = avalue; } for of syntax loops through the elements of an Array. Recommended syntax for processing Arrays. Only Key/Value pairs with numeric keys are selected. Syntax will also iterate through variables containing a String. Each iteration returns a character in the String.
JavaScript Execution Control (9) Loops ( While syntax) while ( expression ) { } The While loop evaluates the expression BEFORE iterating through the code. In all other respects, identical to the Do While loop. Individual commands within the braces are terminated by a semi-colon (standard JavaScript syntax).
JavaScript Execution Control (10) Loop Execution Control Commands JavaScript provides two control commands that affect the processing of loop iterations: continue break (immediate end current loop iteration) (immediate exit loop) Loop Labels A loop command may be preceded by a label: alabel: loopcommand The continue and break commands may be immediately followed by a label indicating the scope of the command Useful for control within nested loops.
JavaScript Functions (1) JavaScript Functions Separate mini programs defined within a program Function itself returns a value. No parameters values are returned. Function behavior Scope of variables Global variables defined in program visible in Function Variables defined inside Function only visible in Function Name collisions (Program & Function) use Function variable All arguments are Call by Content Arguments may only be used to pass Inbound data Number of parameters passed not enforced
JavaScript Functions (2) JavaScript function syntax Function declaration ( function ) Function name (surrounded by spaces) Function arguments (surrounded by parentheses) Arguments separated by commas Function body (surrounded by braces) Arguments separated by commas Returning from a Function return expression; (JavaScript statement) If the return statement is omitted or the value supplied is null, then undefined is returned
JavaScript Functions (3) Sample Function function returnsum (number1, number2) { return number1 + number2; } Function Expressions Functions are considered a special type of value Special value represents an action rather than data Function declaration may be assigned to a variable Variable can then be used as a named Function Can pass a Function as a parameter (to another function)
JavaScript Output to the Console The JavaScript console Object A JavaScript built-in Object A single instance of the object Similar to an OO Singleton pattern Object encapsulates a console (e.g. stdout) Object methods console.log( A String ); - Write message to stdout console.trace( A String ); - Trace message to stderr console.warn( A String ); - Warning message to stderr console.error( A String ); - Error message to stderr
JavaScript Sample Code ( Hello World ) // ============================== // Always use "Strict" mode for new code. // ============================== "use strict"; // ==================== // Declare Global Variables. // ==================== var hellomessage = "Hello, World. It's Me (JavaScript in Node.js)!"; // ============= // Define functions. // ============= function repeatmessage (count, message) { var idx; for (idx=0; idx < count; idx++) { console.log(message); } } // ================= // Main body of program. // ================= repeatmessage(3, hellomessage);
JavaScript Sample Code ( Web Service ) // ============================== // Always use "Strict" mode for new code. // ============================== "use strict"; // ================ // Load HTTP module. // ================ const http = require("http"); const hostname = 127.0.0.1 ; const port = 8000; // =================== // Create an HTTP Server. // =================== const server = http.createserver((req, res) => { res.statuscode = 200; res.setheader( Content-Type, text/plain ); res.end( Hello World. It s me, JavaScript, running in Node.js!\n ); }); server.listen(port, hostname, () => { console.log(`server running at http://${hostname}:${port}/`); });
JavaScript What has not (yet) been covered JavaScript Objects JavaScript has a number of built-in Objects Like an OO Singleton Class instance They extend the language JavaScript Classes JavaScript Modules Modules extend the JavaScript language They are like packages or libraries in other languages These will be covered in a future presentation I/O Capability (Supplied by external Frameworks)
JavaScript References ECMA Standard (ECMA-262) https://www.ecmainternational.org/publications/standards/ecma-262.htm W3 Schools Tutorial https://www.w3schools.com/js/default.asp Modern JavaScript Tutorial https://javascript.info/
Questions?