Javascript 2
Javascript 2
Web Programming
JAVASCRIPT
BY:
Nimra BARI
(M.S Computer Science)
2
JavaScript Comments
Comments are used to make code more readable.
Multi-line Comments:
Multi-line comments start with /* and end with
*/
3
JavaScript Variables
Variable is a memory location which store value.
variable is "container" for storing information:
JavaScript uses the var keyword to define variables, and an
equal sign to assign values to variables/identifiers.
var x;
var x = 10;
Document.write(x);
<h1 id="demo"></h1>
<script>
var x = 55;
var y = 10;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
4
JavaScript Data Types
JavaScript can use the dynamic type of data.
JavaScript variables can hold numbers like 100, and
text values like “Engineer".
JavaScript can handle many types of data, but for now,
just think of numbers and strings.
Strings are written inside double or single quotes.
Numbers are written without quotes.
Arithmetic Operators
var x = 5;
var y = 2;
var z = x + y;
6
Assignment Operators
x=5;
Y = 10;
x+ = y => x=5+10
7
String Operators
txt1 = “Muhammad";
txt2 = “Rehan";
result = txt1 + " " + txt2;
The + operator can also be used to concatenate strings.
JavaScript Comparison and Logical Operators
8
JavaScript Arrays
<script>
var cars = ["Suzuki","4seater","Red"];
document.getElementById("demo").innerHTML
=cars[2] ;
</script>
JavaScript Objects:
JavaScript objects are written with curly braces.
9
<p id="demo"></p>
<script>
var car = {
name: "Flat",
model : "500",
color : "white"
};
document.getElementById("demo").innerHTML =
car.name + " " + car.model + " " + car.color
;
</script>
10
JavaScript Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box:
window.alert(“hello I’m alert");
Confirm Box:
window.confirm(“Are u sure want to delete ?");
<h1 id="demo1"></h1>
<button type="button" onclick=“firstFunction()">Try it</button> <br><br>
<script>
function firstFunction(){
var x;
if (confirm("Are u sure to delete ?") == true)
{
x="you deleted the record";
}
else
{
x= "you canceled the operation";
}
document.getElementById('demo1').innerHTML = x;
}
</script>
11
Prompt Box
window.prompt(“I am prompt","defaultText");
<h1 id="demo1"></h1>
<button type="button" onclick=" firstFunction()">Try it</button>
<script>
function firstFunction()
{
var name = prompt("Please enter your name","Iltaf Hussain");
if (name != null)
{
document.getElementById('demo1').innerHTML=
"Dear " + name + "! calm down and do practice ";
}
}
</script>
NOTE: \n is used for new line in a pop up box
12
13
14