JavaScript Base PDF
Document Details
Uploaded by UnrestrictedOrangeTree1920
Instituto Politécnico de Leiria
Marco Monteiro & Eugénia Bernardino
Tags
Summary
This document is a JavaScript presentation focused on the base concepts of the language. It covers topics such as introduction, syntax, data types, loops, arrays, objects, functions, and best practices.
Full Transcript
JavaScript - base JavaScript Language – syntax and core concepts Criado por Marco Monteiro Revisto por Eugénia Bernardino Summary 1. Introduction and history 2. Basic syntax and semantic 3. Data types 4. Loop and control st...
JavaScript - base JavaScript Language – syntax and core concepts Criado por Marco Monteiro Revisto por Eugénia Bernardino Summary 1. Introduction and history 2. Basic syntax and semantic 3. Data types 4. Loop and control statements 5. Arrays 6. Objects 7. Functions 8. Best practices JavaScript - Base 2 1 – INTRODUCTION AND HISTORY 3 Why JavaScript? JavaScript is the ubiquitous language for the development of web clients (Web Browsers) JavaScript is used directly or indirectly, since alternative languages usually extend or compile to JavaScript. CoffeeScript Dart - from Google TypeScript - from Microsoft JavaScript is also used on the server-side (e.g.: node.js) and other domains (e.g.: OpenOffice; Universal Remote Controllers; Game Engines; Google App Scripts; Internet of Things; Robotics; etc.) WebAssembly (wasm) initiative proposes an alternative to JavaScript on the browser. It is still to early to predict if it will succeed (started in 2015), therefore, at least in the near future, JavaScript will remain a fundamental part of web client development Low-level (bytecode) binary format for in-browser client side programming. Suitable for compilation on the web (other languages will compile to wasm) Support from major browser players: Mozilla, Google, Microsoft and Apple JavaScript - Base 4 History 1995: JavaScript included on Netscape Navigator 2.0 Brendan Eich 1996: Javascript (JScript) added to Internet Explorer 3.0 1996: Netscape submitted JavaScript for standardization to ECMA European Computer Manufacturer’s Association ECMA-262 – Standard for ECMAScript (JavaScript) language 1997: ECMAScript 1st edition 1999: ECMAScript 3rd edition 2009: ECMAScript 5th edition 2015: ECMAScript 6th edition 2016: ECMAScript 7th edition 2017: ECMAScript 8th edition 2018: ECMAScript 9th edition 2019: ECMAScript 10th edition 2020: ECMAScript 11th edition 2021: ECMAScript 12th edition 2022: ECMAScript 13th edition 2023: ECMAScript 14th edition 2024: ECMAScript 15th edition JavaScript - Base 5 JavaScript engines JavaScript engine is a virtual machine that interprets and executes JavaScript Speed of JavaScript execution in the browser is related to the the JavaScript Engine Browser JavaScript Engine Google Chrome & Opera V8 JavaScript Engine * Mozilla Firefox SpiderMonkey Microsoft Internet Explorer & Chakra Microsoft Edge JavaScriptCore (also known as Nitro, Nitro Extreme, Apple Safari (WebKit projects) SquirrelFish or SquirrelFish Extreme) * Also used in Node.JS server JavaScript - Base 6 Language characteristics Syntax based on C language Interpreted language Recent JavaScript Engines perform just-in-time compilation Dynamic language Program code and objects can change at run-time Loosely Typed Data type is checked only at run-time. Variables data type can change at run-time Multi-paradigm Imperative Object Oriented Functional – First-class functions JavaScript - Base 7 2 – BASIC SYNTAX AND SEMANTIC 8 JavaScript Syntax JavaScript is case sensitive Comments: // Single-line comment. */ JavaScript uses Unicode charset Unicode Escape Sequences: "café" === "caf\u00e9" Semicolons ; Semicolons are optional. However, it is recommended that all statements end with a semicolon. Exceptions: for, function, if, switch, try, while JavaScript - Base 9 Names Naming rules for identifiers (variables, functions): May contain letters, digits, $ (dollar) and _ (underscore) Cannot contain spaces or hyphens (-) Cannot start with a digit Naming conventions Don't use the $ (dollar) – usually used by frameworks (e.g. jQuery) Don't use the _ (underscore) as the first or the last character of a name Use camelCase convention maxTemperatureInDayLight Constructor function that must be used with the new prefix should start with a capital letter. var a = new CreateRecord(); Constants should be in all caps const GLOBAL_VAR = 123; JavaScript - Base 10 Variables var or let or const - variable declaration var firstVar; //firstVar has no value let secondVar= 1; //secondVar has a value Declaration doesn't include variable type Variable declaration is optional thirdVar = 123; if (fourthVar === 12) … // Valid, but nonsense (fourthVar is undefined) if (ThirdVar === 123) … // ThirdVar has no value !!! It is recommended that all variables are declared To force variable declaration we can use strict mode "use strict" thirdVar = 123; // ERROR JavaScript support constants after ECMAScript201 5 const PI=3.14; JavaScript - Base 11 Differences between var, let and const A commonly accepted practice is to use: const as much as possible let in the case of loops and reassignment var can be avoided outside of working on legacy code Can Be Can Be Keyword Scope Hoisting Reassigned Redeclared Function var Yes Yes Yes scope let Block scope No Yes No const Block scope No No No JavaScript - Base 12 Scope There are only 2 types of scope: Global variables are those declared outside of a block Local variables are those declared inside of a block Variables declared with the var keyword are always function-scoped, meaning they recognize functions as having a separate scope. This locally-scoped variable is therefore not accessible from the global scope. var a = 1; function f() { a = a+1; // a = 2 - Same variable as global a b = 1; // b is a local variable – first use within function for (var i=0; i a and b are accessible here! }; }; JavaScript - Base 15 3 – DATA TYPES 16 Data types Primitive types String There is no character type. A character (e.g. "a") is represented with a string that has only one character. Number All numbers (including integer numbers) are handled internally has floating-point values. That means that 1 and 1.0 are the same value. Boolean Null Undefined Composite types (objects) Object Array (in JavaScript, arrays are objects) Function (in JavaScript, functions are objects) Date RegExp JavaScript - Base 17 Data types JavaScript has a dynamic type system Variable type is not declared Variable type can change through time Automatic type conversion Types are converted automatically to what the expression expects Inexperience programmers may have unexpected results "9" + 3; // string "93" "9" - 3; // number 6 "true" == true // boolean false | "true" == 1 "1" == true // boolean true | "1" == 1 | 1 == 1 | true Explicit type conversion Number("42.1"); // number 42.1 String(42.1); // string "42.1" Set of functions that force type Boolean(42.1); // boolean true conversion parseInt("42.1"); // number 42 JavaScript - Base 18 Wrapping objects Wrapping objects – wrap primitive types on objects Objects: Number; String and Boolean Provide properties and methods to manipulate primitive types var s = "teste"; var t1 = s.length; // t1 = 5 var t2 = "teste".length; // t2 = 5 var t2 = "teste".length; // similar (internally) to: var t2 = new String("teste").length; // String object wraps a string value JavaScript - Base 19 Strings Literals "Don't mix your quotes" // double quote 'this "string" is valid' // single quote "a" + 'b'; // "ab" Concatenation: operator + "a" + 16; // "a16" 16 + "a"; // "16a" Multiple lines: "one\ "Two\nlines" long\ // A string with 2 lines line" // 1 line string written // in 3 lines of code Escape character: \ 'Don\'t mix your quotes, unless you use escape characters' "In that case you can use \"mixed\" quotes" "c:\\folder1\\folder2" JavaScript - Base 20 Strings Escape sequences: \0 The NULL character (\u0000) \b Backspace (\u0008) \t Horizontal tab (\u0009) \n Newline (\u000A) \v Vertical tab (\u000B) \f Form feed (\u000C) \r Carriage return (\u000D) \" Double quote (\u0022) \' Apostrophe or single quote (\u0027) \\ Backslash (\u005C) \x XX The Latin-1 character specified by the two hexadecimal digits XX \u XXXX The Unicode character specified by the four hexadecimal digits XXXX JavaScript - Base 21 Strings Strings are sequences of characters (zero indexed), but there is no character type in JavaScript Strings are not arrays of characters var str = "abc"; var firstLetter = str; // "a" var secondLetter = str.charAt(1); // "b" // Both expressions return strings with only one character. Strings are immutable var str = "abc"; str = str + "def"; // a new string ("abcdef") is created JavaScript - Base 22 Strings There is no simple way to manipulate (change) individual characters of strings This is not valid: var str = "abcde"; str = "X"; It is necessary to create a new string. A possible solution that uses a new function (replaceAt): function replaceAt(str, idx, newChar) { return str.substr(0, idx) + newChar + str.substr(idx + newChar.length); } var str = "abcde"; str = replaceAt(str, 2, "X"); //str === "abXde" JavaScript - Base 23 String object String object – wrapping object Note: Strings are immutable - when a method manipulates the string, a new instance is created and returned var s = "abc"; s.toUpperCase(); // s = "abc" // Method toUpperCase() returns a new string // but s value is still "abc" var s = s.toUpperCase(); // s = "ABC" -> s is a new instance JavaScript - Base 24 String object Some properties and methods: (not a complete list) length* String size (total number of characters) - *it is a property toUpperCase/toLowerCase Converts to uppercase / lowercase letters trim Removes whitespace from both ends of a string charAt/charCodeAt Returns the character/character code (unicode) at a specific index fromCharCode Converts the character code (unicode) to a string indexOf/lastIndexOf Returns the position of the first/last occurrence of a substring Returns the position of the first occurrence of a substring (can use search regular expressions) slice/substring Return a substring between two specified positions (indices) Return a substring with a specified number of characters and substr beginning at a specified start position Search the string for a match using a regular expression. Return all match the matches (array of strings) Searches a string for a specified value, or a regular expression, and replace returns a new string where the specified values are replaced JavaScript - Base split Splits a string into an array of strings (requires a separator) 25 String object Examples: var s = "hello, world"; // Start with some text. s.charAt(0) // => "h": the first character. s.charAt(s.length-1) // => "d": the last character. s.substring(1,4) // => "ell": the 2nd, 3rd and 4th // characters. s.slice(1,4) // => "ell": same thing s.slice(-3) // => "rld": last 3 characters s.indexOf("l") // => 2: position of first letter l. s.lastIndexOf("l") // => 10: position of last letter l. s.split(", ") // => ["hello", "world"] split into // substrings s.replace("h", "H") // => "Hello, world": // replaces all instances of h for H s.toUpperCase() // => "HELLO, WORLD" JavaScript - Base 26 Numbers Literals 12 -.01243 0xff 6.02e23 // 6.02 × 1023 0xCAFE911 1.4738223E-32 // 1.4738223 × 10−32 3.14 Infinity // 1.79769313486231570e+308.333333333333333333 -Infinity // -1.797693134862316E+308 All numbers (including integer numbers) are handled internally has floating-point values. That means that 1 and 1.0 are the same value. Arithmetic operations may, on certain conditions, produce results without absolute precision 0.1 + 0.2 === 0.30000000000000004 JavaScript - Base 27 Numbers NaN or Number.NaN Property that represents a value that is not a number isNaN() or Number.isNaN() Function that determines whether a value is a number or not. isNaN(NaN); // true isNaN(""); // false isNaN(undefined); // true //empty string is converted to 0 isNaN({}); // true isNaN(" "); // false isNaN(true); // false //space is converted to 0 // true is converted to 1 isNaN(new Date()); // false isNaN(null); // false isNaN(new Date().toString()); // true // null is converted to 0 isNaN("str"); // true isNaN(37); // false isNaN("37"); // false isNaN("2.8"); // false // "2.8" is converted to 2.8 JavaScript - Base 28 Numbers Convert strings to numbers - global functions Returns a number from a string. May return NaN or parseFloat() ignore irrelevant text. Returns a number (integer part only) from a string. May parseInt() return NaN or ignore irrelevant text. var n1 = parseFloat("12.324"); // n1 = 12.324 var n1 = parseFloat("12.324 xpto"); // n1 = 12.324 var n1 = parseFloat("xpto"); // n1 = NaN var n1 = parseInt(" 12"); // n1 = 12 var n1 = parseInt("12.324 xpto"); // n1 = 12 var n1 = parseInt("xpto"); // n1 = NaN var n1 = parseInt("xpto 12"); // n1 = NaN JavaScript - Base 29 Number object Some properties and methods: (not a complete list) Number object – wrapping object Some properties (static properties) and methods NaN Static property with NaN value (equivalent to global NaN). MAX_VALUE MIN_VALUE Static property with the biggest/smallest (positive) number NEGATIVE_INFINITY POSITIVE_INFINITY Static property with the value of infinity (positive/negative) toString() Converts a number to a string - e.g. 12.toString() toFixed() Returns a number with X digits after decimal point toPrecision() Returns a number with a specified length (total digits) var n= Number.MAX_VALUE; // n= 1.7976931348623157e+308 var n= 136.84226.toFixed(2); // n= 136.84 var n= 136.84226.toPrecision(4); // n= 136.8 JavaScript - Base 30 Numbers - arithmetic Arithmetic in Javascript Using operators, like: + - * / % Using the Math object. Examples: Math.pow(2,53) // => 9007199254740992: 2 to the power 53 Math.round(1.6) // => 2: round to the nearest integer Math.ceil(1.6) // => 2: round up to an integer Math.floor(1.6) // => 1: round down to an integer Math.abs(-5) // => 5: absolute value Math.max(x,y,z) // Return the largest argument Math.min(x,y,z) // Return the smallest argument Math.random() // Pseudo-random number x where 0 "object" typeof(undefined) = "undefined" JavaScript - Base 36 Operators Most operator are similar to C / Java List with some operators (not all of them): Arithmetic operators + - * / % -- ++ addition subtraction multiplication division remainder decrement increment Assignment operators = += -= *= /= %= assignment addition subtraction multiplication division remainder assignment assignment assignment assignment assignment String operators + += concatenation addition concatenation JavaScript - Base 37 Operators Comparison operators == != === !== > >= < >>> AND OR XOR NOT left shift right shift zero-filled right shift Conditional (ternary) operator condition ? val1 : val2 Examples: var s = (age >= 18) ? "adult" : "minor"; function odd(n){ return (n%2)!==0 ? true : false; } JavaScript - Base 39 Operators typeof() Returns a string indicating the type of the operand Examples: typeof(13) //"number" typeof("13") //"string" typeof(new Date()) //"object" in operator (relational) Returns true if the specified property is in the specified object var trees = ["redwood", "bay"]; var mycar = { make: "Honda", 0 in trees; // true model: "Accord", 2 in trees; // false year: 1998 }; "bay" in trees; // false "make" in mycar // true // checks index, not value "model" in mycar // true "length" in trees; // true "Honda" in mycar // false // length is an Array property JavaScript - Base 40 Automatic conversions JavaScript - Base 41 4 – LOOP AND CONTROL STATEMENTS 42 if Loop and control statements (instructions) syntax is based on C language family (C; Java; C#; C++; etc.) Syntax: Examples: if (condition) if (a === b) if (n === 1) { statement1/block1 statement1; // code block #1 } [else if (a === b) { else if (n === 2) { statement2/block1] // code block #2 // code block #1 } } else if (n === 3) { // code block #3 if (a === b) { } // code block #1 else { } else { // if all else fails // code block #4 // code block #4 } } JavaScript - Base 43 while & do.. while while Syntax: Examples: while (i current value (item/element) // index -> current index // array -> full array (always the same); JavaScript - Base 58 Array operations Some properties and methods: (not a complete list) isArray Returns true if an object is an array, false if it is not indexOf Returns the first (or the last) index at which a given element can be lastIndexOf found in the array, or -1 if it is not present pop Removes the last element from an array push Adds one or more elements to the end of an array shift Removes the first element from an array unshift Adds one or more elements to the beginning of an array reverse Reverses an array in place. First element becomes last and vice-versa sort Sorts the elements of an array in place. concat Concatenates several arrays into a new array. slice Returns a partial/complete shallow copy of the array splice Changes an array by removing or adding elements to it join Converts an array to a string by joining all elements into a string. toString toLocaleString Returns a string representing the specified array and its elements JavaScript - Base 59 Array operations length – property with the total number of elements var arr =["A", "B", "C"]; console.log(arr.length); // 3 push - add an element to the end var arr =["A", "B", "C"]; arr.push("New"); console.log(arr); // ["A", "B", "C", "New"] unshift- add an element to the begin var arr =["A", "B", "C"]; arr.unshift("New"); console.log(arr); // ["New", "A", "B", "C"] JavaScript - Base 60 Array operations pop – removes an element from the end var arr =["A", "B", "C"]; arr.pop(); console.log(arr); // ["A", "B"] shift – removes an element from the begin var arr =["A", "B", "C"]; arr.shift(); console.log(arr); // ["B", "C"] indexOf – finds the index of an element var arr =["A", "B", "C"]; var idxA = arr.indexOf("B"); // idxA = 1 var idxB = arr.indexOf("b"); // idxB = -1 JavaScript - Base 61 Array operations slice – copy an array (complete or partial) slice(from_Index, to_Index) var arr = ["A", "B", "C", "D", "E", "F", "G"]; var arrFullCopy = arr.slice(); //A complete shallow copy var arr2 = arr.slice(3,5); //["D", "E"] splice - removes one or more elements at a determined position (index) splice(from_index, deleteCount) var arr = ["A", "B", "C", "D", "E", "F", "G"]; arr.splice(2,1) // ["A", "B", "D", "E", "F", "G"] arr.splice(2,3) // ["A", "B", "F", "G"] arr.splice(2) // ["A", "B"] JavaScript - Base 62 Array operations Operations that use CallBack functions forEach Execute the provided function once for each array element Creates a new array with the results of calling a provided function on map every element in this array Tests whether all elements in the array pass the test implemented by every the provided function. Returns true if all elements pass the test. Tests whether any element in the array pass the test implemented by some the provided function. Returns true if one of the element pass the test. Creates a new array with all elements that pass the test (boolean test) filter implemented by the provided function. Applies a function against an accumulator and each value of the array reduce (from left-to-right) to reduce it to a single value Applies a function against an accumulator and each value of the array reduceRigth (from right-to-left) to reduce it to a single value sort Sorts the array elements using a compare function JavaScript - Base 63 Array operations Operations that use CallBack functions Examples: function positiveGrade(value) { return value >= 10; } var filtered = [12, 5, 8, 13, 17].filter(positiveGrade); // filtered is [12, 13, 17] [12, 5, 8].every(positiveGrade); // false [12, 15, 10].every(positiveGrade); // true [12, 5, 8].some(positiveGrade); // true [3, 5, 8].some(positiveGrade); // false var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); // roots is [1, 2, 3], numbers is still [1, 4, 9] JavaScript - Base 64 6 – OBJECTS 65 Objects JavaScript uses a simple object-based paradigm There is no concept of classes An object is "just" a collection of properties If a property value is a function, it is known as a method Prototype based Inheritance Objects are created by cloning existing objects Every JavaScript object has an internal link to its prototype Objects can be extended by adding properties to it Object properties are dynamic (just like variables). JavaScript - Base 66 Creating new objects Using object initializers or literals: Individual Property Definition Syntax -> propertyName : propertyValue {} // empty object { property1: value1, property2: value2 } Examples: Property values can be of any type, including array or object var o1 = {}; var o2 = {property1: value1, property2: value2}; var myCar = { color: "red", equipment: ["GPS", "ABS", "Bi-Xenon"], engine: {cylinders: 4, size: 2.2} }; JavaScript - Base 67 Creating new objects Using a constructor function var obj = new ConstructorFunction(...); Constructor Function example: By convention, Constructor Function name use capital initial letter Within Constructor Function code, use this keyword to assign values to the object's properties Call the Constructor Function using the new operator – it returns a new object instance function Car(make, model, year) { this.make = make; this.model = model; this.year = year; }; var newObject = new Car("Ford", "Escort", 1989); JavaScript - Base 68 Creating new objects Using the Object.create method var obj = Object.create(ObjectPrototype); Creates a new object by cloning it from a specified prototype Can choose the prototype for the object you want to create, without having to define a constructor function. var animal = { type: "Invertebrates", displayType : function(){ console.log(this.type); } } var animal1 = Object.create(animal); // Clone animal1.displayType(); // Invertebrates JavaScript - Base 69 Using objects Access object properties (and methods) Dot Notation obj.property obj.method() obj[property] obj[method]() Bracket Notation obj["property"] obj["method"]() Examples: var obj = SomeObject(); obj.property1 = "Value"; obj[property2] = 1234; obj["property3"] = null; obj.method1(); obj[method2](); obj["method3"](); JavaScript - Base 70 Bracket notation Using bracket notation, object property names: Can include space and other special characters Can be a number Examples: var obj = SomeObject(); obj["property name with spaces"] = 123; obj = 312; Recommendation for property names Use only names that are accessible using both notations (dot or brackets) Don't use space or special characters Don't use numbers for property names JavaScript - Base 71 Objects and arrays Arrays are objects var a = ["A", "B"]; //typeof(a)== "object" Also, some authors consider JavaScript objects as associative arrays. Why? Each property is associated with a string value that can be used to access it. Arrays indices are similar to object properties that use the brackets notation Despite similarities, objects and arrays are not the same Arrays are objects, but objects are not arrays Objects don't support related array properties and methods (e.g. length; indexOf; push; etc.). Why? Because array object is linked to a specific object prototype. Arrays cannot use dot notation to access its elements. Why? Because numeric properties names are only supported by the brackets notation JavaScript - Base 72 Methods Method definition Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. It is possible to define method using an anonymous function this – object reference Can be used within a method to refer to the current object function f1() { // Using an anonymous function this.p2 = this.p1 * 2; var obj = { } p1: 1, var obj = { p2: 2, p1: 1, method1: function() { p2: 2, this.p2 = this.p1 * 2; method1: f1 } }; }; JavaScript - Base 73 7 – FUNCTIONS 74 Functions JavaScript functions are also objects JavaScript has first-class functions. It is possible to: Assign functions to variables, properties or store them in collections Use functions as arguments to other functions Use functions as return values of other functions Create new functions at run-time JavaScript supports some Functional Programming paradigm concepts However, it is not a pure functional language More about functions on "Advanced JavaScript" presentation JavaScript - Base 75 Function definition Declaration example: function square(number) { return number * number; } Calling a function: var res = square(3); Assigning a function to a variable: var s = square; // square is the name of the function Calling a function assigned to a variable: var varWithFunction = square; var res = varWithFunction(3); // res == 9 JavaScript - Base 76 Anonymous functions Anonymous function is a function with no name Assigning a anonymous function to a variable: var s = function (number) { return number * number; } Calling a anonymous function assigned to a variable: var s = function (number) { return number * number; } var res = s(3); // res == 9 JavaScript - Base 77 Anonymous functions Calling an anonymous function inplace Add the curved brackets () after the anonymous function definition (function() { // Some code console.log("Executing something"); })(); var res = function (number) { return number * number; }(3); // res == 9 JavaScript - Base 78 Function parameters Declaration example: function f1(p1, p2, p3) { // code } Calling a function with parameters Parameter order in the declaration defines which parameter value is passed to the function f1 ("A", "B", "C"); Primitive type parameters are passed by value string, number, boolean, null, undefined Non-primitive type parameters are passed by reference object, array, functions JavaScript - Base 79 Function return value return statement function f1() { // code example: return "some_value"; // this code is not executed } Return statement defines the value that the function returns When return is executed function exits immediately No further code is executed If no return statement is executed, then function returns the value undefined JavaScript - Base 80 Function parameters Parameters mismatch Defined parameters < calling parameters Extra calling parameters are ignored (can be accessed through the arguments object) function f1(p1, p2, p3) { // Values within function f1 // code p1 = "A" } p2 = "B" p3 = "C" f1 ("A", "B", "C", "D"); // forth parameter "D" is ignored JavaScript - Base 81 Function parameters Parameters mismatch Defined parameters > calling parameters Extra defined parameters are assigned the "value" of undefined function f1(p1, p2, p3) { // Values within function f1 // code p1 = "A" } p2 = "B" p3 = undefined f1 ("A", "B"); JavaScript - Base 82 Function parameters Object arguments Array-like object with all the arguments passed to the function Allows to access all parameters, even if they are not declared // Values within function f1 p1 = "A" function f1(p1, p2, p3) { p2 = "B" // code p3 = "C" } arguments.length = 4 arguments = "A" f1 ("A", "B", "C", "D"); arguments = "B" arguments = "C" arguments = "D" JavaScript - Base 83 Function parameters Object arguments. Example: function myConcat(separator) { var result = "", i; // iterate through arguments for (let i = 1; i < arguments.length; i++) { result += arguments[i] + separator; } return result; } myConcat(", ", "a", "b", "c"); // "a, b, c, " myConcat("-", "a", "b", "c", "d"); // "a-b-c-d-" JavaScript - Base 84 8 – BEST PRACTICES 85 Strict mode Strict mode eliminates some JavaScript silent errors by changing them to throw errors. Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript. JavaScript - Base 86 Strict mode Strict mode can be applied to an entire script or to individual functions. Entire script Put the statement "use strict"; "use strict"; // remaining code before any other language... statement on the script file Individual function function functionName() { Put the statement "use strict"; "use strict"; on the function body, before any // remaining code other language statement in the... } function JavaScript - Base 87 Strict mode With strict mode, some restrictions on code are enforced Example of code restriction: all variables must be declared In normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable. "use strict"; a = 1; // Error – a is not defined Previous rule prevent user from mistyping variable names "use strict"; var firstCar = "Opel Corsa"; if (firstcar == "Opel Corsa) // Error – firstcar is not defined executeSomething(); Check bibliography: "MSDN – Strict Mode (JavaScript)" for more restrictions on code JavaScript - Base 88 Best practices Apply strict mode whenever is possible Some external libraries may not work with strict mode. Use strict on your functions only – do not use "use strict" globally. Follow a coding style convention. E.g. Google JavaScript Style Guide Use JSLint (or equivalent) linter - code quality tool. A linter is a tool that checks source code style and syntax. Finds language syntax errors Finds code sections that do not follow coding style conventions Some code editors integrate JSLint (or equivalent) For instance, with SublimeText it is possible to install packages that run JSLint (or equivalent) on background (during code editing) JavaScript - Base 89 Coding style conventions Some conventions: (not a complete list) Based on Conventions defined by "Google JavaScript Style Guide" and Douglas Crockford in the book "JavaScript: The good Parts" Use camelCase for variables, properties, function and method names var age; var fullSize; function addItemToList(item) {…} Use capital initial letter for constructor functions function SalaAula(edificio, numero){…} var sala = new SalaAula('A','1.3'); Use FULLCASE for constant values const PI = 3.14; const DEFAULT_PHOTO = 'no_photo.png'; JavaScript - Base 90 Coding style conventions Some conventions: (not a complete list) Always use semicolons ( ; ) to terminate instructions Always declare variables (with const, let or var keyword) Always declare variables at the beginning of each function On logical expressions prefer strict comparators ( === !==) over regular comparators ( == !=) Prefer single quote over double quote for string literals var str = 'some string'; var str = "some string"; To delete object properties, assign its value to null instead of using the delete operator someObject.somePropery = null; delete someObject.somePropery; JavaScript - Base 91 Coding style conventions Some conventions: (not a complete list) Use this only on constructor functions and methods Never use an array as a map/hash/associative array. If map/hash/associative array is required, use an object instead Use only numeric indices on arrays Use for-in loops only for iterating over keys in object/map/hash Iterate through arrays with a "classical" for loop Avoid multi-line string literals. Use string concatenation instead. var str = 'a very ' + var str = 'a very \ 'long ' + long \ 'string'; string'; Use array and object literals instead of Array and Object constructors JavaScript - Base 92 Coding style conventions Some conventions: (not a complete list) Code Format Conventions Always start curly braces on the same line as whatever they're opening. There should be a space before the start curly braces if (…) { while (…) { for (…) { function f(…) { … … … … } else { } } } … } Always use blocks (curly braces) on structured statements: if, while, do..while, for, for..in Apply this rule even if the block includes only one instruction JavaScript - Base 93 Coding style conventions Some conventions: (not a complete list) Code Format Conventions Single-line array and object initializers are allowed when they fit on a line: var arr = [1, 2, 3]; // No space after [ or before ]. var obj = {a: 1, b: 2, c: 3}; // No space after { or before }. Multiline array initializers and object initializers are indented 2 spaces, with the braces on their own line, just like blocks. var inset = { var arr = [ top: 10, 'first value', right: 20, 'second value', bottom: 15, 'third value', left: 12 'forth value' }; ]; JavaScript - Base 94 Coding style conventions Some conventions: (not a complete list) Code Format Conventions Most important rule: Be Consistent Use JSLint or alternative linter, to help complying with all coding style conventions JavaScript - Base 95 BIBLIOGRAPHY 96 Bibliography Douglas Crockford, "JavaScript: The Good Parts", O'Reilly, 2008 Mozilla Foundation, "MDN – JavaScript", https://developer.mozilla.org/en-US/docs/Web/JavaScript Google, "Google JavaScript Style Guide", http://google.github.io/styleguide/javascriptguide.xml ECMA International, "ECMAScript Language Specification", 5.1 Edition, 2011 http://www.ecma-international.org/ecma-262/5.1/index.html Microsoft, "MSDN - Strict Mode (JavaScript) ", https://msdn.microsoft.com/en-us/library/br230269(v=vs.94).aspx WebAssembly Community Group https://www.w3.org/community/webassembly/ JavaScript - Base 97