2. Why we need JavaScript
• HTML to define the content of web pages
• CSS to specify the layout of web pages
• JavaScript to program the behavior of web pages
3. JavaScript is nice because
• Adds interactivity (event handling)
• Manipulates page contents dynamically
• Does real time validations
• No reloads – All is executed on browser
• Makes asynchronous server calls
• Performs calculations on the spot
• Controls Browser, Window, Keyboard, Mouse, Cookies..
• Can accept third party libraries
4. Where to place JavaScript
<html>
<body>
…
<script language="javascript" type="text/javascript">
…
</script>
</body>
</html>
<script type="text/javascript" src="filename.js" ></script>
5. Variables
• No declaration of types
• Name cannot start with numbers
• JavaScript is case sensitive
• myVariable is a different variable to myvariable
The semicolon at the end of the line is not
mandatory
var myVariable;
myVariable = 'Bob';
var myVariable = 'Bob';
myVariable = 'Steve';
6. Data Types
Variable Example
String var myVariable = 'Bob';
Number var myVariable = 10;
Boolean var myVariable = true;
Array
var myVariable = [1,'Bob','Steve',10];
Refer to each member of the array like this:
myVariable[0], myVariable[1], etc.
Object
var myVariable = document.querySelector('h1');
All of the above examples too.
9. Conditionals
Operator Name Example
=== Strict equality 5 === 2 + 4
!== Strict-non-equality 5 !== 2 + 3
< Less than 10 < 6
> Greater than 10 > 20
<= Less than or equal to 3 <= 2
>= Greater than or equal to 5 >= 4
10. Conditionals
var iceCream = 'chocolate';
if (iceCream === 'chocolate')
{
alert('Yay, I love chocolate ice cream!');
}
else
{
alert('Awwww, but chocolate is my favorite...');
}
11. Loops
• For
• While
• Do.. While
for (i = 0; i < 10; i++) {
text += "The number is " + I;
}
while (i < 10) {
text += "The number is " + i;
i++;
}
do {
text += "The number is " + i;
i++;
}
while (i < 10);
12. Functions
• Code reusal
• No parameter type
• No return type
• Can pass any type in invocation
function multiply(num1,num2) {
var result = num1 * num2;
return result;
}
var x = multiply(4,7);
x = multiply(20,20);
x = multiply(0.5,3);
13. Functions
• Special functions
• alert(“Hi”);
• confirm(“Are you gonna eat that?”);
• prompt(“Enter your age [male only]:”);
• getElementById(“elementId”);
• String functions
• split()
• Array functions
• find()
14. Events
• “things” that happen to HTML elements
• JavaScript react to these events
• User or browser actions
• Button clicked (onclick)
• Key pressed (onkeydown)
• Mouse over some element (onmouseover)
• Page loaded (onload)
• Event handlers are JavaScript functions