JavaScript for Grown-Ups – Part 2



JSNotes 2 - JavaScript for Grown-Ups – Part 2(Part 1 was the Introduction)Variables and their scopeLocal/Global In classic JavaScript all variables are global except those declared inside a function with the reserved word var Ex: function foo(x, y) { u=2*x; var v=10*y: } u is global; v is local.Local/Global in ES6+ES6 introduced block-level variables with let and const. Let If you say let myIndex = 1; inside a block of code then myIndex will be local to that block. You can still change the value of myIndex, but you can not reference it outside that block.What defines a block? The smallest enclosing set of braces { …}See Ex: if ( a <0 ) { let aa = -1; //the scope of aa is here : } Ex: for(let myIndex =0; myIndex < 10; myIndex++){ //the body of this for loop is the scope of myIndex }We will see later in the course that var declarations are hoisted to the top of the function block, but let declarations are not. (Stay tuned.)Const is intended to be like let, except that with const you may not redefine (change) the value. Well, almost….. Speciically, if the const declaration is for an array or object then you can change the values inside that array or object.What you are declaring here (see examples below) is a reference to a storage location – and that location can not be changed. But what is stored there can be.So many people treat const as an intention, rather than a guarantee of immutability.Ex: const x =3; x=4; //run-time error. NOT allowedEx: const courses = [110,112, 320]; courses[2] = 321; //allowableEx: const course = {prefix: "CS", number:320}; course.number =321; //allowableIf you want more on this look at the comments at There are other subtleties about const or let inside a for loop- which we’ll discuss when we come to closures and more advanced material on functions in JS.Input and output (Reminder from JSNotes 1)Prompt for input: JavaScript has a built in prompt (“my_prompt” ) function which prints my_prompt in a pop-up box and has a place for the user to enter a response. That response is returned to the script as a string. As with any function, you may grab the returned value and store it in a variable: Weather=prompt(“What is today’s weather like?”, “nice”)The second parameter in the prompt is optional and is a default answer.When your prompt is trying to get a numerical value, you must take the string which prompt( ) returns and convert it to an integer or float.You use parseInt( ) or parseFloat( ) to do the conversions. Age=parseInt(prompt(“How old are you?”, 18))For output you will see the following: alert("some message") //some message appears on the screen in a pop-up confirm("some message") //same as above, but user must answer 'yes' or //'no' console.log("some message") //some message appears on the console //see debugging tools writeln(”some message") //some message appears on the web page JavaScript built-in opeartions: JavaScript has the usual arithmetic operations +, -, * and / (with remainder) mod does the usual finding of the remainder – e.g. 5 mod 3 is 2Javascript has built in Boolean operations &&, || and ! for and, or and not NOTE: = is used for assignment and == is the test for equality != is the test for inequality. ALL LOGICAL TEST MUST BE enclosed in parentheses.Use semicolons to separate statements even when it is not required (e.g. on separate lines of code).This is best practises b/c the interpreter will sometime make errors otherwise.Conditionals –In JavaScript any boolean condition must be inside parentheses!Please note and use the following indentations for your code:Note: It is recommended to put { } around even one statement! Prettier will do the formatting for you.if –else if ( condition ) { statement1 } if ( condition ) { statement1; statement2; statementn; } if ( condition ) { statement1; } else { statement2; } if ( condition1 ) { statement1; } else if (condition 2 ) { statement2; } else { statement3; } Loops – Python has for and while loops (test the condition at the start of the body of the loop).JavaScript has both of those and also a do-while loop (test the condition at the end of the body of the loop).An aside:In addition to the usual for loop (which may be used to do something a speciied number of times etc. or to loop thru a string or array), JavaScript has two other for loops both of which may be used to iterate thru objects. Both involve subtleties, and should not be used with arrays.If obj = {Name:"Ada", Field: "Programming" }Then for… in with iterate thru the property names and for…of will iterate thru the values.That is for (x in obj) { ..} will have x take on Name and then Field for (x of obj) {..} will have x take on "Ada" and then "Programming"Documentation on loops may be found at and a tutorial on them at I expect you to not need for-in and for-of loops and I strongly discourage using break and continue. Use a boolean variable to control your loops, as you did in python.The style guides recommend and I want you to use for loops:Do and while loops: while (condition) { statements; } do { statements; }for loop for arrays: for (initialization; termination condition; step) { statements; }for loops for objects:As we learn more about objects, we will learn that an object may inherit from another object. In order to search only within that object, and not all the way up the hierarchy, your for loop will look like: for (xxx in myObject) { if ( myObject.hasOwnProperty(xxx) ) { statements; } } hasOwnProperty is a built-in method, but you may safely ignore this example for now.Space- prettier should also help with this.You should use space to improve readability:Always put a space after a comma or semi-colon Always surround equals, not equals, arithmetic operators with spacesUse spaces just inside the parentheses to set off the condition you are testing for.Examples:for ( j = 0; j < 10; j++ ) is better than for(j=0;j<10;j++)Use blank lines to set off related sections of codeUse // for comments related to one line and use /* */ for multi-line comments, such as when you are starting a section of code.Blocks: { } are used to group statements together The semicolon just before and just after } are optional, but you should use the semi-colon just before the } and skip the one just after. (See examples above). There is a semi-colon before the ‘else’ if you are not using braces, but the correct style is to use braces – even if there is only one statement inside the braces!. You may nest if-else statements. There is a switch statement for multi-way branches. Depending on your style guide, indentation is either always 2 , 3 or4 spaces– I like 3 better, but you may choose.Testing for yes/no answers:When you test an answer (from an input box) for ‘yes’ or ‘no’ it is common to test only if first letter – but you must test both upper and lower case: Cont=prompt(‘Do you wish to continue?’); if ( Cont.charAt(0 )!= ’y’ && Cont.charAt(0 )!= ’Y ’) { document.write(‘So long!’); } else { //more stuff }Warning on tests for equality and inequality in JavaScript:JS has 2 tests for equality, == and === and two tests for inequality != and !==The difference is that in == and != JS will try to coerce types but in === and !== the types must be the same for the test to answer true.JS really has “truthy” and “falsy” values.falsy values are: false, 0, and “” (empty string)null and undefined are equivalent only to themselveseverything else is truthy.This leads to some odd situations. For example, 0 == “” and “0” ==0 are true, but “” == 0 is falsefalse == “0” is true but false ==”false” is falseBottom line: always use === and !==A clear explanation of this is at and at guidelines on nice coding style may be found at Or you can just use prettier. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download