You are on page 1of 30

1

Rangarajan| 9952927294
q ECMAScript is the official name for JavaScript.

q A new name became necessary because there is a trademark (held originally


by Sun, now by Oracle).
q For common usage, these rules apply:
q JavaScript means the programming language.
q ECMAScript is the name used by the language specification.
q Therefore, whenever referring to versions of the language, people say
ECMAScript.
q The current version is ECMAScript 7; ECMAScript 8 is currently being
developed.
q JavaScript’s creator - Brendan Eich.

q Borrowed from several programming languages:


q Java (syntax, primitive values versus objects),
q Scheme and AWK (first-class functions),
q Self (prototypal inheritance), and
q Perl &Python (strings, arrays, and regular expressions).

q Enables a programming style that is a mixture of


q functional programming (higher-order functions; built-in map, reduce, etc.)
q object-oriented programming (objects, inheritance).
2
q Interpreted language.
q Create a sample html page with basic html elements.

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.

q Variables & assignment


q Declared before they are used.
Ex: var foo; // declare variable `foo`.
q You can declare a variable and assign a value at the same time:
Ex: var foo = 6;
q You can also assign a value to an existing variable:
Ex: foo = 4; // change variable `foo`
q Compound assignment operators such as += and -=.
x += 1 & x = x + 1; are same.

4
q Names that play various syntactic roles.

q For ex, the name of a variable is an identifier.

q Identifiers are case sensitive.

q First character can be any Unicode letter, a


dollar sign ($), or an underscore (_).
q Subsequent characters can be any Unicode
digit.
q The following are all legal identifiers:
q arg0
q _tmp
q $elem

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

q Functions normally allows us to indicate a missing value via


either undefined or null.
q We can do the same via an explicit check:
if (x === undefined || x === null) { ... }
q We can also exploit the fact that both undefined and null are
considered false: 8
if (!x) { ... }
q typeof, used for primitive values.
q instanceof, used for objects.
q typeof value.
q value instanceof Constr.
> typeof true 'boolean' > var b = new Bar(); // object created by
> typeof 'abc' 'string' constructor Bar
> typeof {} 'object' > b instanceof Bar true
> typeof [] 'object’ > {} instanceof Object true
q typeof null returning 'object' is a bug that can’t be > [] instanceof Array true
fixed, because it would break existing code. It does > [] instanceof Object true
not mean that null is an object.
> undefined instanceof Object false
> null instanceof Object false

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 Using strict equality is recommended. q !0, !NaN, !null, !undefined, !false,!’’

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 Adding and Deleting Elements


q document.createElement(element) Create an HTML element
q document.removeChild(element) Remove an HTML element
q document.appendChild(element) Add an HTML element
q document.replaceChild(element) Replace an HTML element
q document.write(text) Write into the HTML output stream 11
q Finding HTML Objects
q document.anchors Returns all <a> elements that have a name attribute
q document.body Returns the <body> element
q document.cookie Returns the document's cookie
q document.forms Returns all <form> elements
q document.head Returns the <head> element
q document.images Returns all <img> elements
q document.links Returns all <area> and <a> elements that have a href attribute
q document.scripts Returns all <script> elements
q document.title Returns the <title> element
q Events
q onclick, ondblclick, onkeypress, onkeyup, onkeydown
q onload
q onchange, oninput
q onmouseover, onmouseout, onmousedown, onmouseup

q Adding Events Handlers


q document.getElementById(id).onclick = function(){code}

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

q Subtraction : number1 - number2 q “12”+1

q Multiplication : number1 * number2 q “12”+”1”

q Division : number1 / number2 q “12”-1

q Remainder : number1 % number2 q “12”-”1”

q Increment : ++variable, variable++ q “12”%2

q Decrement : --variable, variable-- q “12”%”two”

q Negate : -value q 3/0

q To number : +value q +”10”

q Math obj provides more arithmetic operations. q +”Ten”

q JS also has operators for bitwise operations q -45

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");

> str += 'pieces '; q "HELLO WORLD".charAt(0); charCodeAt(0);


15
> str += 'are concatenated.'; q "a,b,c,d,e”.split(“,”);
16
q Create a form for SignUp. It should have
q Text fields for First Name, Middle Name, Last Name, Email-id, address, zip code with placeholders.
q Password field for password.
q Select field for Country(India, USA, UK, etc) grouped by continents.
q Radio button for Gender(Male/Female), selecting the type of account – free, premium, enterprise, platinum.
q Check box for ”Subscribe to newsletter” & Submit button.

q When Submit button is pressed, Validate the following:


q First name, Last name, Email, Password, Gender & Country should not be empty. Email-id should be valid.
q Zip code and mobile number should be number.

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.

q Rewrite task 2 using loops.

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 Print detailed logs in the catch and finally blocks.

q Try the following and observe the error thrown:


q var num = 1; num.toPrecision(500); // A number cannot have 500 significant digits
q var x; x = y + 1; // y cannot be referenced (used)
q eval("alert('Hello)"); // Missing ' will produce an error
q var num = 1; num.toUpperCase(); // You cannot convert a number to upper case
q decodeURI("%%%"); // You cannot URI decode percent signs

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.sort(); //for strings

q arr.reverse();

q arr.sort(function(a, b){return a - b});

q arr.sort(function(a, b){return b - a});

q Math.max.apply(null, arr);

q Math.min.apply(null, arr);

q arr. forEach(function(){});

q arr. map(function(){return val});

q arr. filter(function(){return con});

q arr. reduce(function(){return con});

q arr. every(function(){return con});

q arr. find(function(){return con});

q arr. findIndex(function(){return con});

q arr. indexOf(item, start);


23
q arr. lastIndexOf(item);
q var x = 123; x.toString(); q Math.PI;

q var x = 9.656; x.toExponential(4); x.toFixed(2); x.toPrecision(2); q Math.round();

q var x = Number.MAX_VALUE/ Number.POSITIVE_INFINITY; q Math.pow();

q var x = Number.MIN_VALUE/ Number.NEGATIVE_INFINITY; q Math.sqrt();

q Number(true); // returns 1 q Math.abs();

q Number(false); // returns 0 q Math.ceil();

q Number("10"); / Number(" 10"); / Number("10 "); // returns 10 q Math.floor();

q Number("10 20"); // returns NaN q Math.sin(90 * Math.PI / 180);

q Number("John"); // returns NaN q Math.cos(0 * Math.PI / 180);

q Number(new Date("2017-09-30")); // returns 1506729600000 q Math.min(0, 150, 30, 20, -8, -200);

q parseInt("10"); / parseInt("10.33"); // returns 10 q Math.max(0, 150, 30, 20, -8, -200);

q parseInt("10 20 30"); / parseInt("10 years"); // returns 10 q Math.random();

q parseInt("years 10"); // returns NaN q Math.E // returns Euler's number


q parseFloat("10"); // returns 10 q Math.SQRT2 // returns the square root of 2
q parseFloat("10.33"); // returns 10.33 q Math.SQRT1_2 // returns the square root of ½

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(year, month, day, hours,minutes, seconds, milliseconds)

q new Date(milliseconds)

q new Date(date string)

q var d = new Date();

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 Check if the string is a palindrome.

q Check if the input number is a palindrome.

q Implement the following data structures


q Stack
q Queue
q Hash table
q Binary tree

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 Implement the following with meaningful inputs as separate functions


q All the array methods
q All Number methods
q All String methods
q All Math methods 26
q All Date methods
27
q Write regular expressions to validate
q Email address
q Website address
q Password
q Credit card numbers
q AMEX
q Master card
q Visa

q Construct regular expressions to


q Replace all occurrences of a particular substring in a lengthy string.
q Remove all html tags and extract content alone from a html string.

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.

q Find whether a number is


q Perfect
q Happy
q Armstrong
q Strong

q Find GCD & LCM of 2 numbers.

q Find 2nd largest number in an array of numbers.

q Print the Sum of digits of a number.

q Print the count of each character in a String.

30

You might also like