Professional Documents
Culture Documents
JavaScript ES5
JavaScript ES5
Rangarajan| 9952927294
q ECMAScript is the official name for JavaScript.
q Write JS code to
q Get your name – prompt()
q Alert the input– alert()
q Print input in logs – console.log()
q Get confirmation – confirm()
q Points to be learnt
q Usage of prompt, alert & confirm.
q Debugging basics - Blocking & non-blocking.
3
q Statements “do things.” A program is a sequence of statements.
q Expressions produce values. They are function args, the right side of an assignment, etc. Ex : 3 * 7
q Comments:
q Single-line: start with // and are terminated by the end of the line
q Multi-line: start with /* and end with */.
q Semicolons
q Optional, but its recommended including them.
q Else JS can guess wrong about the end of a statement.
4
q Names that play various syntactic roles.
5
q JS has many values: booleans, numbers, strings, arrays, etc. q Declare variables one of integer, float, character, string,
object, array, boolean types and print their values in
q All values have properties - a key (or name) and a value. console.
q You use the dot (.) operator to read a property. q Prompt the user to enter the browser names he knows
q For example, the string 'abc' has the property length:
5times. Each time check it is not empty string and then
store it in the array.
> var str = 'abc';
> str.length 3 q In the object, store the browser name as key and its length
as value.
q The preceding can also be written as:
q Call a function to pass the array & object as parameters
> 'abc'.length 3 and print them in console.
q The dot operator is also used to assign a value to a property: q Points to be learnt
> var obj = {}; // empty object q Declaration & usage of variables.
> obj.foo = 123; // create property `foo`, set it to 123 q Definition & calling of functions.
> obj.foo 123
q Can be used to invoke methods:
> 'hello'.toUpperCase() 'HELLO’
6
q Primitive values are q All nonprimitive values are objects.
q Booleans: true, false
q Plain objects, which can be created by object literals :
q Numbers: 1736, 1.351 { firstName: 'Jane', lastName: 'Doe' }
q Strings: 'abc', "abc"
q Arrays, which can be created by array literals:
q Two “nonvalues”: undefined, null
[ 'apple', 'banana', 'cherry' ], Can be accessed via numeric
q All primitive values encoding the same value are indices.
considered the same (compared by value):
q Regular expressions, which can be created by regular expression
> var prim1 = 123; literals:
> var prim2 = 123; /^a+b+$/
> prim1 === prim2 true
q Identities are compared; every value has its own identity
q Always immutable - Properties can’t be changed, (compared by reference):
added, or removed: > ({} === {}) // two different empty objects false
> var str = 'abc'; > var obj1 = {};
> str.length = 1; // try to change property > var obj2 = obj1;
> str.length // ⇒ no effect 3 > obj1 === obj2 true
> str.foo = 3; // try to create property `foo`
q Mutable by default. Properties can be changed, added or
> str.foo // ⇒ no effect, unknown property
removed.
undefined
> var obj = {};
> obj.foo = 123; // add property `foo`
7
> obj.foo 123
q undefined means “no value.” q The following values are interpreted as false:
q undefined, null
q Uninitialized variables are undefined:
q Boolean: false
> var foo;
q Number: 0, NaN
> foo undefined
q String: ''
q Missing parameters are undefined:
> function f(x) { return x } q All other values (including all objects!) are considered
true.
> f() undefined
q Boolean(), called as a function, converts its parameter
q Reading a nonexistent property: to a boolean.
> var obj = {}; // empty object > Boolean(undefined) false
> obj.foo undefined > Boolean(0) false
q null means “no object.” It is used as a nonvalue whenever an > Boolean(3) true
object is expected. > Boolean({}) true
q undefined and null have no properties. > Boolean([]) true
9
q Binary logical operators: && (And), || (Or) q Try the following in browser console & understand:
q 0 == false , 0 === false
q Prefix logical operator: ! (Not)
q 1 == true , 1===true, 2== true, !2
q JS has two kinds of equality:
q ‘0’ == false, ‘0’? ‘true’:’false’, ''?'true':'false’
q Normal/ lenient (in)equality: == and !=
q ‘0’ == ‘’, ''==false
q Strict (in)equality: === and !==
q undefined==false, undefined==0, undefined==NaN
q Normal equality considers too many values to be equal
which can hide bugs. q undefined==null, null==NaN
q All numbers in JS are floating-point: q Write a simple code snippet that prints the typeof and
instanceof values:
> 1 === 1.0 true
q false
q Special numbers include the following: q “False”
q NaN (“not a number”) q null
> Number('xyz') NaN q undefined
q Infinity q NaN
> 3 / 0 Infinity q {}
> Math.pow(2, 1024) Infinity // number too large q []
q Infinity/-Infinity is larger/smaller than other numbers q 121
(except NaN).
q “121”
10
q Finding elements
q document.getElementById(id) Find an element by element id
q document.getElementsByTagName(name) Find elements by tag name
q document.getElementsByClassName(name) Find elements by class name
q document.querySelectorAll("p.intro") Find elements by CSS Selectors
q document.forms["frm1"], x.elements[i].value Find elements by HTML Object Collections
q Changing values & attributes of elements
q element.innerHTML or element.innerText = new html or text content Change the inner HTML of an output element
q element.value = new value Change the value of an input element
q element.attribute = new value Change the attribute of an HTML element
q element.setAttribute(attribute, value) Change the attribute of an HTML element
q Changing HTML Style
q document.getElementById(id).style.property = new style
q EventListener
q element.addEventListener(event, function);
12
q element.removeEventListener(event, function);
q DOM Navigation
q document.getElementById("id01").firstChild.nodeValue
q document.getElementById("id01").childNodes[0].nodeValue;
q document.getElementById("id01").nodeName
q document.getElementById("id01").nodeType
13
q Addition : number1 + number2 q 12+1
14
q 'abc'.slice(1) // copy a substring 'bc’
q Created via string literals (single or double quotes). q 'abc'.slice(1, 2) 'b’
q The backslash (\) escapes characters & produces a q '\t xyz '.trim() 'xyz' // trim whitespace
few control characters.
q 'mjölnir'.toUpperCase() 'MJÖLNIR’
'Did she say "Hello"?' "Did she say \"Hello\"?"
'That\'s nice!' "That's nice!" q 'abc'.indexOf('b’) 1, 'abc'.indexOf('x') -1
'Line 1\nLine 2' // newline q ”Please locate where 'locate’ occurs!”.lastIndexOf("locate”)
'Backlash: \\’
q "Please locate where 'locate' occurs!".indexOf("locate",15) 21
q Single characters are accessed via square brackets:
q "Please locate where 'locate' occurs!".search("locate") 7
> var str = 'abc'; str[1]
q "Apple, Banana, Kiwi". substring(7,13) Banana
q Strings are immutable.
q "Apple, Banana, Kiwi".substr(7, 6) Banana
q Strings are concatenated via the plus (+) operator,
which converts the other operand to a string if one of q "Please visit Microsoft!".replace("Microsoft", "W3S")
the operands is a string:
q "Please visit Microsoft & Microsoft!".replace("Microsoft",
> var messageCount = 3; "W3S")
> 'You have ' + messageCount + ' messages'
q "Please visit Microsoft & Microsoft!".replace(/Microsoft/g,
q To concatenate strings in multiple steps, use the += "W3Schools");
operator:
q "Please visit Microsoft!".replace("MICROSOFT", "W3S");
> var str = '';
> str += 'Multiple '; q "Please visit Microsoft!".replace(/MICROSOFT/i, "W3S");
q Upon pressing each character for password, calculate the password strength:
(0 to 3 – Poor, 4 & 5- Medium, 6 – Good.)
q 8 to 15 characters.
q Atleast one character.
q Atleast one number.
q Atleast one special character.
q Atleast one upper case letter.
q Atleast one lower case letter.
17
q Once we get the list of errors upon form validation,
q Change the border of the respective elements to red.
q Append a child node to those error elements giving an error message.
q Depending upon the type of account chosen, show and hide the payment details.
q The payment details row should have a number field to get number of months.
q While entering number in the box, calculate subscription fee. (Premium-5$, Enterprise-10$, Platinum-20$)
q Show 4 userId suggestions and upon clicking set it in the disabled textbox.
q It should have first 2 characters from FirstName, MiddleName & LastName followed by number of characters in each.
q It should have first 3 characters from FirstName & LastName followed by number of characters in each.
q It should have last 3 characters from LastName & FirstName followed by number of vowels in each.
q It should have first 2 characters from FirstName & LastName and any randomly generated alphabet followed by
randomly generated 3 digit number.
q After selecting the userId, show “Form validation success!” to the user using a custom popup.
18
q A function that is passed to another function (let’s call this other
function “otherFunction”) as a parameter, and the callback function is
called (or executed) inside the otherFunction.
q A callback function is essentially a pattern (an established solution to a
common problem). So also known as a callback pattern.
q We can pass functions around like variables and return them in
functions and use them in other functions.
q When we pass a callback function as an argument to another function,
we are only passing the function definition.
q We are not executing the function in the parameter.
q In other words, we aren’t passing the function with the trailing pair of
executing parenthesis () like we do when we are executing a function.
q And since the containing function has the callback function in its
parameter as a function definition, it can execute the callback anytime.
q Note that the callback function is not executed immediately.
q It is “called back” (hence the name) at some specified point inside the
containing function’s body.
19
20
The try clause surrounds critical code, and the catch clause is executed if an exception is thrown inside the try clause.
21
getPersons([2, -5, 137]); //[Error: ID must not be negative: -5] [ { id: 2 }, { id: 137 } ]
q Create an array with numbers, characters, strings, objects, arrays, boolean, undefined, null, NaN.
q Iterate through out the array. Throw an error and suitably catch it if you encounter
q 0, false, undefined, null, NaN, negative numbers, -infinity.
q Object with error as one of the keys.
q Array of length less than 5.
q Strings which have ‘error’ as substring.
q Character of lower case or special character.
q Declare function A() which takes null as first argument and a function as another argument.
q Find the length of the two arguments. What will happen? Handle suitably.
q Invoke the callback function which is passed in the second argument to print present date and time.
22
q arr1.concat(arr2, arr3);
q arr.splice(0, 1);
q arr.toString();
q arr.reverse();
q Math.max.apply(null, arr);
q Math.min.apply(null, arr);
q arr. forEach(function(){});
q Number(new Date("2017-09-30")); // returns 1506729600000 q Math.min(0, 150, 30, 20, -8, -200);
q parseFloat("10 20 30"); / parseFloat("10 years"); // returns 10 q Math.LN2 // returns the natural logarithm of 2
24
q parseFloat("years 10"); // returns NaN q Math.LN10 // returns the natural logarithm of 10
q new Date()
q new Date(milliseconds)
q d.getTime();
q d.getFullYear(); d.setFullYear();
q d.getMonth(); d. setMonth();
q d.getDate(); d.setDate();
q d.getHours(); d.setHours(22);
q d.getMinutes(); d.setMinutes(30);
q d.getSeconds(); d.setSeconds(30);
q d.getMilliseconds();
q d.getDay();
25
q Check for duplicate numbers in an array.
q In a continuous numbered array, one number is missing & another is repeated. Find them.
q Bill generation
q Declare an array of objects with name & quantity of few books.
q Declare another object with book name as key & price as value.
q Write a function to find the total cost of all the books.
q Print it like a bill in table format in the html page.
q Sample solution
q Medium : new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
q Strong: new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})")
28
q Quiz application
q It should have textarea for descriptive answers, Radio options, select options.
q Descriptive answers can be evaluated based on pre-defined keywords.
q Once the quiz is submitted, print the report that compares the answers and derive a score.
q Time limit is 60secs. If the user doesn’t submit before the time limit, the test will be automatically submitted.
q Memory game
q Randomly load 10 images on the screen. Each image should be loaded twice.
q Image shouldn’t be visible to the user. Image becomes visible when the user clicks on it.
q At a time a user can see only 2 images. If the 2 images match, those 2 images get removed. Else they’ll be flipped.
q A maximum of 30 attempts can be given to the user.
q The number of images matched will be the final score of the user.
q Chess
q Print a chess board on the screen.
q Place blocks random on the board. Those places can’t be occupied by any coin.
q Get the present position and the coin type (horse/queen/rook/bishop/pawn) from the user.
q Depending upon the present position, coin type and the blocks print all possible position to which the coin can move.
q Facebook
q Implement a facebook like page where user can add, delete & edit comments. Such posts should go to the top.
q There should be a move to top and scroll to bottom which does the relevant purpose. 29
q Get the number of rows and columns and print the multiplication table.
30