JavaScript I Language Basics

Similar documents
CSC Web Programming. Introduction to JavaScript

CGS 3066: Spring 2015 JavaScript Reference

Working with JavaScript

Typescript on LLVM Language Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

HTML5 and CSS3 More JavaScript Page 1

Client-Side Web Technologies. JavaScript Part I

Chapter 2 Working with Data Types and Operators

Lexical Considerations

1 Lexical Considerations

Visual C# Instructor s Manual Table of Contents

Expr Language Reference

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Lexical Considerations

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

Language Reference Manual simplicity

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

UNIT- 3 Introduction to C++

Basics of Java Programming

COMS 469: Interactive Media II

3 The Building Blocks: Data Types, Literals, and Variables

CS313D: ADVANCED PROGRAMMING LANGUAGE

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Java Notes. 10th ICSE. Saravanan Ganesh

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

Web Site Design and Development JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

Decaf Language Reference Manual

egrapher Language Reference Manual

Introduction to Programming Using Java (98-388)

Language Reference Manual

XQ: An XML Query Language Language Reference Manual

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

JME Language Reference Manual

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104)

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Lecture 3. More About C

Language Fundamentals Summary

Fundamental of Programming (C)

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Decaf Language Reference

This tutorial will help you understand JSON and its use within various programming languages such as PHP, PERL, Python, Ruby, Java, etc.

DEPARTMENT OF MATHS, MJ COLLEGE

Fundamental of C programming. - Ompal Singh

The C++ Language. Arizona State University 1

CHAD Language Reference Manual

Language Reference Manual

CA4003 Compiler Construction Assignment Language Definition

Index COPYRIGHTED MATERIAL

Java+- Language Reference Manual

Sprite an animation manipulation language Language Reference Manual

Information Science 1

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 2: Functions and Control Structures

CHIL CSS HTML Integrated Language

C-LANGUAGE CURRICULAM

JavaScript: The Basics

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

In addition to the primary macro syntax, the system also supports several special macro types:

Data Types and Variables in C language

JavaScript Basics. The Big Picture

PHP by Pearson Education, Inc. All Rights Reserved.

4 Programming Fundamentals. Introduction to Programming 1 1

GOLD Language Reference Manual

Chapter 2. Lexical Elements & Operators

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

d-file Language Reference Manual

Cellular Automata Language (CAL) Language Reference Manual

Programming for the Web with PHP

Sketchpad Graphics Language Reference Manual. Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321

JavaScript Lecture 1

C - Basic Introduction

corgi Language Reference Manual COMS W4115

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Operators. Java operators are classified into three categories:

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript

Review of the C Programming Language for Principles of Operating Systems

TED Language Reference Manual

XC Specification. 1 Lexical Conventions. 1.1 Tokens. The specification given in this document describes version 1.0 of XC.

INTRODUCTION 1 AND REVIEW

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Variables, Constants, and Data Types

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

VLC : Language Reference Manual

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Language Reference Manual

The SPL Programming Language Reference Manual

Transcription:

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?