javascript
- Details
- Last Updated: Monday, 27 September 2021 07:32
- Published: Tuesday, 26 May 2020 00:27
- Hits: 2573
javascript (JS):
Now that you learned DOM basics, javascript is easier to learn as DOM and javascript kind of go together.
This is one of the best tutorials on javascript on digitalocean website: https://www.digitalocean.com/community/tutorial_series/how-to-code-in-javascript
javascript or JS is one of the core languages besides HTML and CSS that go into your website. Supoort for javascript is built into the browser, so that no extra plugin is required to run javascript. Javascript runs locally on your computer, by browser downloading the script from specified location and then running locally. Javascript makes web pages interactive, and so has become very popular (as HTML, CSS just provide static webpages and were never designed for dynamic interaction).
console: In DOM section, we saw how to open console in firefox, and write javascript cmds on it. This is also called "javascript console".This console is like javascript shell, where we can try any javascript cmd in real time.
console.log() => To o/p anyhting on this console, we can use console cmd below. This console cmd is useful during debug of javascript to dump out values.
>> console.log("Hello") => This will print "Hello" on javascript console
>> console.log(4+5); => This will print "9" on console.
alert(): This is another function used to print values in a pop up box. This is also used to dump out values.
>> alert("hello") => brings a pop up box with "hello" written on it.
Adding JS into HTML doc:
JS is added into HTML doc by adding tag <script> ... </script>. Just as in CSS, they can be inserted inline or as a separate file. Generally JS is put into the <HEAD> section, signalling the browser to run the JavaScript script before loading in the rest of the page. However, if your script needs to run at a certain point within a page’s layout, then it has to put at a point, where it is to be called, generally in <BODY> section. Putting JS in HEAD section is preferred, as it keeps JS separate from main HTML content, but it's not always possible.
1. Inline: Here, JS code is put directly within <script> tags. In ex below, JS function alert( ) is called in <head> section, so a popup with msg "Hello" shows up on browser, even before the erest of the page loads. This is because <body> section hasn't even run yet, as alert ( ) is in <head> section.
<head>
<script>
alert("Hello")
</script>
</head>
2. separate file: Here, JS code is put in a separate file, so that it's cleaner. In ex below, test.js is a separate JS file having JS function alert("Hello");
<head>
<script> src="/test.js" </script>
</head>
Syntax: Just like any other programming languages, JS also has variables, reserved keywords (if, else, etc) and special characters (for doing arithmetic, signalling end of cmd, etc).
1. Whitespace: Whitespace in JavaScript consists of spaces, tabs, and newlines. Whitespace is used to separate out tokens. Extra whitespace is ignored. Some tokens may be recognized even without whitespace, however, it's preferred to put whitespace.
2. semicolon: JS consists of multiple statements. Each statement is terminated by a newline or a semicolon( ; ). semicolon is mandatory when there are multiple statements on a single line. It's possible to write entire JS program in a single line by using semicolons and spaces, but that would be unreadable. Indentation (or using multiple spaces) is good way to make your pgm readable.
ex: alert("Me"); var a="ASD";
3. comments: JS comments are written in same style as in C language. single lines comments are written using //, and multiline comments within /* this is multi line comment */
4. variables / identifiers: The name of a variable, function, or property is known as an identifier in JavaScript. Identifiers consist of letters and numbers, but they cannot include any symbol outside of $
and _
, and cannot begin with a number. They are case sensitive. They are declared using "var", "let" or "const". Initially JS only allowed keyword "var" to declare variables, but now 2 additional keywords "let" and "const" used. That is why in lot of legacy JS code, only "var" is seen. However it's recommended to use "let" and "const" instead of var. "let" is used for variables that can be reassigned as in loops, etc, while "const" is used everywhere else, where var are fixed and never modified or reassigned. The scope of variables may be local or global (i.e if variables may or may no be accessible outside the function or block where they are defined). The scope of "let" is block level, while scope of "const" is global level. See digitalocean link for more details.
var myname = "Tom". Here myname is an identifier which stores var "Tom" which is of string type.
let tr=23;
const Me="Ajay";
let ToVar; => We can also define a var, but not initialize it to any value. Then we can assign it later as ToVar=1;
Data Types: variables can be of different data types. In JS, just as in other scripting languages, we don't define data type beforehand. Variables can be accessed directly by their identifier (no need of appending it with any special var). These are the primitive data types in JS:
I. number: Both integers and floating point numbers can be declared. Scientific notation is also supported.
let t = 16; // t is a number.
var t = 14.23 //t is floating number
console.log(t) => prints value of var t. ooks for a var named t and if found prints it's value. It knows t is a var, since it's not a number, not a string (since not enclosed within quotes) and not a boolean.
var t; //here t is undefined, so is assigned null value
Arithmetic operators: as+, -, *, /, +=, ++, etc can be applied on number data type.
ex: 10 +20 => returns 30
ex: let a=4.2; let b=2.1; let c=a / b; => here c is assigned 4.2/2.1=2
ex: let x=a++; ++ and -- are increment and decrement operators. Used in for loops
II. string: A string is a sequence of one or more characters (letters, numbers, symbols). There are 3 ways to write a string: single quotes ( ' ... '), double quotes ( " ..." ) and backtick ( `.... ` ).There's no difference b/w single or double quotes. backtick quotes is the newest method and is also called template literal. It allow substitution of variables inside the quotes. "+" is a concatenation operator for strings (i.e it joins 2 strings).
ex: let t = "Mother Teresa"; // t is a string
let T='teresa' + t; //this concatenates 2 strings and assigns it to T. So T = "teresa Mother Teresa"
backtick: Above we had to use + to concatenate string, since anything inside single or double quotes is interpreted as string, so we could not have used our variable inside quotes. However, backtick allows us to do that by using ${}.
ex: let T=`teresa ${t}` => here t is seen as a var, and it's value is substituted.
NOTE: when having single or double quotes as part of string, we can use \' or \" to treat it as part of string, or use backtick to store that string (since then single or double quotes won't be recognized as end of string). Also, \n is recognized as newline in a string, or even string on different lines is recognized as same string with newlines in between (string continues as long as ending quotes are not found)
string manipulation: There are many methods available to manipulate strings. Note that string is treated as an array of characters starting with index 0.
const originalString = "How are you?"; => Here index [0]=H, [1]=o, [2]=w, [3]="space" or "blank", [4]=a and so on ....
var char5 = originalString[5] => this returns index 5 of above array of char, which is char "r".
originalString.charAt(5) => returns index 5, which is r"
"My name".indexOf("n") => return index number of char "n", which is 3
//slice of string
"How are you?".slice(8, 11); => returns "you"
originalString.sliceof(8) => returns everything starting from index 8 to end of string, so this returns "you
// Split string by whitespace character
const splitString = originalString.split(" "); => this splits string by whitespace, so var splitString is now an array [ 'How', 'are', 'you' ]
console.log(splitString); => we can now access various elements of array too, via splitString[0], etc
There are various other methods to convert cases, finding length, trim, replace, etc. These can be found in digitalocean link at top.
III. Boolean: The Boolean data type can be one of two values, either true or false.
let t = true; // t is a Boolean
let myBool = 5 > 8; // var myBool is assigned a value "false"
IV. array: An array can hold multiple values within a single variable. square brackets used to hold elements of array. They can store any data type as number, string or objects, and single array can have mixed dat types. Arrays can contain arrays within it. Arrays are similar to string, since strings are array of characters.
ex: let fish = ["shark", "cuttlefish", "clownfish", "eel", 7, ["meen", 9], null, 0]; => declares an array of string, number, etc.
ex: fish; => this will print the contents of entire array named fish. We can access items in an array via index, i.e fish[0] refers to 1st element of array, etc.
Array methods: We can use many methods to access various elements of array, or remove/add elements, modify elements, etc.
There are 3 kinds of array methods available:
1. mutator methods: these modify the array itself (i.e adding, removing elements, etc).
Array methods are properly written out as Array.prototype.method()
, as Array.prototype
refers to the Array
object itself.
isArray(): returns True if var is an array. ex: Array.isArray(fish) => returns boolean true
pop(): removes the last element from the end of an array.. ex: fish.pop() => removes last element 0 from fish array.
similarly other methods as push(), shift, unshift, sort, etc. Because of these methods, it's very easy to work with arrays.
2. accessor methods: these return new value or representation. methods such as concat, slice, indexOf, etc
ex: let newfish = fish.slice(2,4); => create new array with elements from index 2 to index 3. newfish = ["clownfish", "eel"]; NOTE: last index has to be one more than the index you want. So, in this case, we did (c,4), even though we wanted (2,3).
3. iteration methods: These are used to operate on every item in an array, one at a time. These methods are closely associated with loops.
To access all elements of array, we can use for loop below (discussed later).
for (let i = 0; i < fish.length; i++) { //here length is a property of array, not a method
console.log(i, fish[i]);
}
Other way using method:. This prints each element of array (same as above), but using a method forEach. Here forEach method calls a function, which we'll learn later
fish.forEach(individualFish => {
console.log(individualFish);
})
Similarly many other methods available, as find, reduce, etc
V. objects: The JavaScript object data type can contain many values as name:value pairs. These pairs provide a useful way to store and access data, and can be of any data type. The object literal syntax is made up of name:value pairs separated by colons with curly braces on either side { }
. The name value pairs are called the property of the object. We can also have methods or functions as part of object. As a data type, object is stored in variable.
2 ways to construct an object:
1. Using object literal: This is preferred method. This uses curly braces { ... }
ex: below ex creates an object var named "sammy", which contains values as indicated. We can have functions too. The whole statement can also be on same line, however that makes it unreadable.
let sammy = {
firstName: "Sammy",
lastName: "Shark",
color: "blue",
greet: function() {
return `Hi, my name is ${this.firstName}!`; //this keyword inside an object refers to current object, in this case to "sammy"
},
location: "Ocean"
};
We can print object data by just typing anme of object.
ex: sammy; => prints all data
{firstName: "Sammy", lastName: "Shark", etc ....}
We can also create empty object.
ex: const sammy = { }; //cretaes empty object named "sammy"
2. Using object constructor: This is one other way to create object, by using "new" keyword
ex: const sammy = new Object();
Properties and methods:
Objects can have properties and methods as discussed above.
There are two ways to access an object’s properties.
- Dot notation: using a dor (.): ex: sammy.firstName => returns "Sammy". Dot notation is more widely used, but has it's limitations.
- Bracket notation: using square brackets [ ] : ex: sammy["lastName"] => "Shark". Bracket notation is used if an object’s property contains any sort of special character.
Objects's methods can be accessed the same way as we access any function, here it's just attached to the object variable.
ex: sammy.greet() => returns "Hi, my name is Sammy"
Modifying or adding to objects properties and methods is easy to do via assignment operator (=). We can use either dot notation or bracket notation.
ex: sammy.firstName = "Akbar" => this changes the value for key=firstName
We can methods by just attaching a new function to object.
ex:
sammy.hello = {
return `Hi, my location is ${this.location}!`;
},
Removing object's properties is done via delete cmd:
ex: delete sammy.firstName => this removes key value pair from object "sammy"
We can loop thru object's properties via "for ... in" loop. NOTE: this is different than "for ...of" loop that is used for arrays. "for ...in" loop is specifically meant for iterating over the properties of an object.
// Get keys and values of sammy properties
for (let my_key in sammy) { //my_key is a var
console.log(my_key.toUpperCase() + ':', sammy[my_key]); //
}
Built in objects: There are many built in objects and associated methods in Javascript.
1. date: The Date
object is a built-in object in JavaScript that stores the date and time. there are many methods associated with it.
ex: // Set variable to current date and time
const now = new Date();
now; // prints current date and time. returns => Wed Oct 18 2017 12:41:34 GMT+0000 (UTC)
now.getTime();// getTime is a method of Date object. Gets the current timestamp,
Finding data type: To find the type of any var, we can use function typeof:
ex: typeof originalString => this return string, since it's defined as string above (by enclosing it in double quotes)
ex: console.log(t) => l
let t; // t is undefined
ex: var myNum= 1 => this assigns it to number type
ex: var a = "my world" => this assigns it to string type
Converting data type:
When using operators, JS coerces data into particular type if needed. This is implicit conversion.
ex: "3" - "2" => even though 3 and 2 are strings here, JS comverts them to number since operator "minus" works on numbers, Returns result as 1
We should always explicitly convert data type to remove ambiguity by using below methods
String(49) => converts number 49 to string "49" and returns "49"
(1776).toString() => converts number 1776 to string "1776"
let str="17";
Number(str) => converts string "17" to Number 17.
Boolean(0) => converts number to boolean, returns false
Boolean("man") => returns boolean true, as any non zero number or string is treated as true
Conditional Statements:
1. if-else: same as if else in other languages. "else" and "else if" are optional.
if (condition a) {
// code that will execute if condition a is true
} else if (condition b) {
// code that will execute if condition b is true
} else if (condition c) {
// code that will execute if condition c is true
} else {
// code that will execute if all above conditions are false
}
ternary operator: similar to ? : in C lang, it's an alternative form of if else.
ex:
let age = 20;
const oldEnough = (age >= 21) ? "enter." : "not enter.";
2. switch: same as switch case in other languages.
switch (expression) {
case x:
// execute case x code block
break;
case y:
// execute case y code block
break;
default:
// execute default code block
}
Loop statements:
1. while, do while: runs loop based on condition. if-else and switch stmt run only once, while runs in a loop as long as the condition is true.
A. while loop: If we put "true" inside while condition (i.e while (true) { ... }), then loop runs infinitely. If we put "false", then loop never runs.
while (fish < popLimit) {
fish++;
console.log("There's room for " + (popLimit - fish) + " more fish.");
}
B. do while loop: this loop will always execute once, even if the condition is never true.
do {
// execute code
} while (condition);
2. for loop: 3 types of for loop: for, for .. of, for ... in
A. for loop: uses 3 optional expr that control execution of loop. All 3 expr are optional and for loop will still run. However the loop may become infinite, if there are no epr to control the loop's var value, so a break stmt inside the loop might be needed. for loops can be used to modify or read values of arrays.
ex:
for (let i = 0; i < 4; i++) {
// Print each iteration to the console
console.log(i);
}
B. for .. in loop: used to iterate over the properties of an object. See in object section above.o
C. for .. of loop: This is used to iterate over iterable objects like arrays and strings, The for ... of statement is a newer feature as of ECMAScript 6. ECMAScript (or ES) is a scripting-language specification created to standardize JavaScript. We looked at the iterator method above to access all elements of an array, which used regular for loop. Here, we use the for ... of loop.
ex: This prints all elements of array.
let sharks = [ "great white", "tiger", "hammerhead" ];
for (let shark_name of sharks) {
console.log(shark_name);
}
A string can be iterated through in the same way as an array (as a string is eventually an array of char).
ex: This prints each char of string
let sharkString = "sharks";
for (let shark of sharkString) {
console.log(shark);
}
Functions:
Functions are same as in other pgm languages. Function can have optional args.
3 types of function syntax allowed:
1. Regular function defn: Here we define functions the regular way
ex: Here we first define function "greet" with 3 args. Args are optional. If no args, then just do "function greet( ) { ... }".
function greet(name, a, b) {
console.log(`Hello, ${name}!`);
return a+b; //return is optional.
}
greet("Sammy", 5, 6); // Invoke greet function with "Sammy", 5, 6 as arguments. Since function returns a value, so 5+6=11 is returned. This value is returned at the point in pgm, that this function is called. It prints 11 on screen, even though we didn't print out the value explicitly by using console.log. This return value can be used immediately or stored in a variable.
2. Function expression: Here, we assign function to a var.
ex:
const sum = function add(x, y) { //function is named add, but the function itself is stored in var "sum"
return x + y;
}
sum(20, 5); //Here we invoke function via the var (function name not needed)
Anonymous functions: Since function name is not really needed for anything when using the var to store the func, we can omit func name altogether. These are called anonymous functions.
ex: here function name "add" is omitted, although parenthesis and args still needed.
const sum = function(x, y) {
return x + y;
}
sum(100, 3);
3. Arrow functions: This is a newer, more concise method of defining a function known as arrow function expressions as of ECMAScript 6. Arrow functions are represented by "=>".
Arrow functions are always anonymous functions and a type of function expression.
ex: Here we omit the word "function" and instead use arrow "=>" after the args. If there are no args, empty parenthesis needed. However, if there is only 1 arg, then parenthesis is not required.
const multiply = (x, y) => {
return x * y;
}
multiply(30, 4);
NOTE: if the function consist of a return
statement only, arrow functions allow the syntax to be reduced even further. If the function is only a single line return
, both the curly brackets and the return
statement can be omitted, as seen in the example below.
ex:
const square = x => x * x; //NOTE: no parenthesis or curly braces needed. No "return" keyword needed either.
square(10);
Events:
Events are are actions that take place in the browser that can be initiated by either the user or the browser itself. We learned a little bit about events in DOM. They are an integral part of javascript, as we can code responses to events in browser, that can make the page look responsive.
Most common events are:
1. mouse events: They refer to events that involve clicking buttons on the mouse or hovering and moving the mouse pointer.
ex: click: Fires when the mouse is pressed and released on an element
2. form events: actions that pertain to forms, such as input
elements being selected or unselected, and forms being submitted.
ex: submit: Fires when a form is submitted (i.e submit button is clicked on form element)
3. keyboard events: used for handling keyboard actions, such as pressing a key, lifting a key, and holding down a key.
ex: ketpress: Fires continuously while a key is pressed
Event handlers: Whenever an event is fired (by user clicking mouse, etc), a JS function can be made to run. This function is called event handler. Button, form, etc are elements of an html page. These elements have properties or attributes such as submit, click, etc (i.e button has onclick attribute). We can assign events to these elements.
There are three ways to assign events to elements:
- Inline event handlers
- Event handler properties
- Event listeners
1. Inline event handlers: Here we set event handler on attribute of an element. Then we assign an attribute value which is the JS function that we want to call. It's called inline as we add handlers to every element that we want to respond to events. This is very cumbersome/inefficient, and so should not be used at all.
ex: In below ex, we assign value of "onclick" (NOT onClick, i.e all small letters) attribute of button element to "changeText()" JS function. In js/test.js, we define this function to change text of p element in html.
<button onclick="changeText()">Click me</button>
<script> src="/js/test.js" </script>
js/test.js => Below file has function defined to modify the text content of the paragraph
const changeText = () => {
const p = document.querySelector('p');
p.textContent = "I changed because of an inline event handler.";
}
Forms: With forms too, we can have inline event handlers. We have attribute onsubmit of a form, on which we can apply event handler.
ex: <form action ="script/action_page.php" onsubmit="ValidateForm()" .. > => Here unless the value returned by function "ValidateForm" is true, the action "script/action_page.php" won't be taken.
2. Event handler properties: Very similar to an inline handler, except we’re setting the property of an element in JavaScript instead of the attribute in the HTML. In the above ex, we set attribute "onclick" to JS func in HTML itself, but here we set property "onclick" to JS func reference in JS code. This also should not be used, as we have better 3rd way of handling events.
ex:
<button>Click me</button> => NOTE: we didn't assign any value to onclick attribute.
<script> src="/js/test.js" </script>
js/test.js => Now we access above element "button" in JS itself (just like we access any other element of HTML in JS), and assign JS function pointer to it's property "onclick". NOTE: onclick is a property of button element here, instead of an attribute.
const changeText = () => {
const p = document.querySelector('p');
p.textContent = "I changed because of an event handler property.";
}
// Add event handler as a property of the button element.
const button = document.querySelector('button');
button.onclick = changeText; => NOTE: when passing a function reference to the onclick
property, we do not include parentheses, as we are not invoking the function in that moment, but only passing a reference to it.
3. Event Listeners: An event listener watches for an event on an element. Instead of assigning the event directly to a property on the element (as in example above), we use the addEventListener()
method to listen for the event. addEventListener()
takes two mandatory parameters — the event it is to be listening for, and the listener callback function.
Event listeners are the newest and preferred way to handle events. They have the advantage that multiple listeners can be added to same event and element, while with the "event handler property" method above, last property set on an element overwrites all previous properties. Furthermore, you can use addEventListener()
on the document
and window
object too.
ex:
<button>Click me</button> => NOTE: we didn't assign any value to onclick attribute.
<script> src="/js/test.js" </script>
js/test.js => Here, we define 2 functions, and add 2
const changeText = () => {
const p = document.querySelector('p');
p.textContent = "I changed because of an event listener.";
}
const alertText = () => {
alert("Am I here?");
}
//Here we access addEventListener() method of element "button". We listen for "click" event on button, and then call appr function.
const button = document.querySelector('button');
button.addEventListener('click', changeText);
button.addEventListener('click', alertText);
// An anonymous function can also be added on an event listener. Anonymous functions are functions that are not named. Often, anonymous functions are used instead of a function reference on an event listener.
button.addEventListener('click', () => { //NOTE: no separate func called, but func body defined here itself.
p.textContent = "Will I change?";
});
NOTE: With the first two methods, a click event was referred to as onclick
, but with event listeners it is referred to as click
. Every event listener drops the on
from the word.
Event Objects: We talked about various events earlier. These events can be accessed via objects. The Event
object consists of properties and methods that all events can access. In addition to the generic Event
object, each type of event has its own extensions, such as KeyboardEvent
and MouseEvent
.
The Event
object is passed through a listener function as a parameter. It is usually written as event
or e
. We can access the code
property of the keydown
event to replicate the keyboard controls of a PC game.
ex: Access the code property of "keydown" event. "keydown" event is captured in "event" object. We then access the "code" property of that event.
document.addEventListener('keydown', event => {
console.log('code: ' + event.code); //This returns the key pressed, as "KeyA", "KeyB", etc
});