0% found this document useful (0 votes)
63 views

Javascript Prefi

The document discusses JavaScript, including what it is, why it is important to study, its capabilities to change HTML content and styles, how to add JavaScript to a webpage, different ways to output JavaScript, JavaScript statements, comments, variables, data types, and more.

Uploaded by

guendelyn omega
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Javascript Prefi

The document discusses JavaScript, including what it is, why it is important to study, its capabilities to change HTML content and styles, how to add JavaScript to a webpage, different ways to output JavaScript, JavaScript statements, comments, variables, data types, and more.

Uploaded by

guendelyn omega
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 66

Javascript

What is Javascript
• JavaScript is a programming language for use
in HTML pages
• Invented in 1995 at Netscape Corporation
(LiveScript) invented by Brendan Eich i
• JavaScript has nothing to do with Java
Why Study JavaScript?
mJavaScript is one of the 3 languages all web
developers must learn:
• 1. HTML to define the content of web pages
• 2. CSS to specify the layout of web pages
• 3. JavaScript to program the behavior of
web pages
Capabilities of JavaScript
• JavaScript Can Change HTML Content
• One of many JavaScript HTML methods
is getElementById().
• This example uses the method to "find" an
HTML element (with id="demo") and changes
the element content (innerHTML) to "Hello
JavaScript":
<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button"
onclick='document.getElementById("demo").innerHTML
= "Hello JavaScript!"'>Click Me!</button>

</body>
</html>
JavaScript Can Change HTML Styles
(CSS)
• Changing the style of an HTML element, is a variant of
changing an HTML attribute:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an
HTML element.</p>
<button type="button"
onclick="document.getElementById('demo').style.fontSiz
e='35px'">Click Me!</button>
</body>
</html>
JavaScript Can Hide HTML Elements
• Hiding HTML elements can be done by changing the
display style:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="document.getElementById('demo').style.display
='none'">Click Me!</button>
</body>
</html>
JavaScript Can Show HTML Elements
• Showing hidden HTML elements can also be done by
changing the display style:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button"
onclick="document.getElementById('demo').style.display
='block'">Click Me!</button>
</body>
</html>
Where to put a JavaScript in a
Webpage
• The <script> Tag
• In HTML, JavaScript code must be inserted between
<script> and </script> tags.

• <script>
document.getElementById("demo").innerHTML = "My
First JavaScript";
</script>
JavaScript in <head> or <body>
• You can place any number of scripts in an HTML document.
• Scripts can be placed in the <body>, or in the <head> section of an
HTML page, or in both.

• <!DOCTYPE html>
<html><head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";}
</script>
</head>
• <body>
• <h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
• </body>
</html>
JavaScript in <body>
<!DOCTYPE html>
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</body>
</html>
JavaScript Output
• JavaScript can "display" data in different ways:
– Writing into an HTML element, using innerHTML.
– Writing into the HTML output
using document.write().
– Writing into an alert box, using window.alert().
– Writing into the browser console,
using console.log().
Using innerHTML
• To access an HTML element, JavaScript can
use
the document.getElementById(id) method.
• The id attribute defines the HTML element.
The innerHTML property defines the HTML
content:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5
+ 6;
</script>
</body>
</html>
Using document.write()
• For testing purposes, it is convenient to
use document.write():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
• Using document.write() after an HTML document
is fully loaded, will delete all existing HTML:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="document.write(5 + 6)">Try
it</button>
</body>
</html>
Using window.alert()
• You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using console.log()
• For debugging purposes, you can use
the console.log() method to display data.
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JS Statements
• In HTML, JavaScript statements are "instructions" to be
"executed" by the web browser.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>In HTML, JavaScript statements are executed by the
browser.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello
Dolly.";
</script>
</body>
</html>
JavaScript Programs
• Most JavaScript programs contain many
JavaScript statements.
• The statements are executed, one by one, in
the same order as they are written.
• In this example x, y, and z are given values,
and finally z is displayed:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript code (or just JavaScript) is a sequence of
JavaScript statements.</p>
<p id="demo"></p>
<script>
var x, y, z;
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
Semicolons
Semicolons separate JavaScript statements.
• Add a semicolon at the end of each executable
statement:
• var a, b, c;
a = 5;
b = 6;
c = a + b;
• When separated by semicolons, multiple
statements on one line are allowed:
• a = 5; b = 6; c = a + b;
JavaScript White Space

• JavaScript ignores multiple spaces. You can


add white space to your script to make it more
readable.
• The following lines are equivalent:
var person = "Hege";
var person="Hege";
JavaScript Line Length and Line Breaks
• For best readability, programmers often like to
avoid code lines longer than 80 characters.
• If a JavaScript statement does not fit on one
line, the best place to break it, is after an
operator:
document.getElementById("demo").innerHTML
=
"Hello Dolly!";
JavaScript Comments
• JavaScript comments can be used to explain
JavaScript code, and to make it more
readable.
• JavaScript comments can also be used to
prevent execution, when testing alternative
code.
Single Line Comments
• Single line comments start with //.
• Any text between // and the end of the line
will be ignored by JavaScript (will not be
executed).
• This example uses a single-line comment
before each code line:
// Change heading:
document.getElementById("myH").innerHTML =
"My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML =
"My first paragraph.";
Multi-line Comments
• Multi-line comments start with /* and end with */.
• Any text between /* and */ will be ignored by
JavaScript.
• This example uses a multi-line comment (a comment
block) to explain the code:
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My
First Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";
JS Variables
• JavaScript variables are containers for storing
data values.
• In this example, x, y, and z, are variables:
var x = 5;
var y = 6;
var z = x + y;
• From the example above, you can expect:
• x stores the value 5
• y stores the value 6
• z stores the value 11
Much Like Algebra
• In this example, price1, price2, and total, are variables:
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
• In programming, just like in algebra, we use variables
(like price1) to hold values.
• In programming, just like in algebra, we use variables in
expressions (total = price1 + price2).
• From the example above, you can calculate the total to
be 11.
JavaScript Identifiers
• All JavaScript variables must be identified with unique
names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more
descriptive names (age, sum, totalVolume).
• The general rules for constructing names for variables
(unique identifiers) are:
• Names can contain letters, digits, underscores, and
dollar signs.
• Names must begin with a letter
• Names can also begin with $ and
• Names are case sensitive (y and Y are different
variables)
• Reserved words (like JavaScript keywords) cannot be
used as names
The Assignment Operator

• In JavaScript, the equal sign (=) is an "assignment"


operator, not an "equal to" operator.
• This is different from algebra. The following does not
make sense in algebra:
• x=x+5
• In JavaScript, however, it makes perfect sense: it
assigns the value of x + 5 to x.
• (It calculates the value of x + 5 and puts the result into
x. The value of x is incremented by 5.)
Assignment operators assign values to
JavaScript variables.

var x = 10;
x += 5;
Output: 15
JavaScript Data Types
• JavaScript variables can hold numbers like 100
and text values like "John Doe".
• In programming, text values are called text
strings.
• 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.
• If you put a number in quotes, it will be treated as
a text string.
• var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Declaring JS VARIABLES
<p id="demo"></p>

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML
= carName;
</script>
One Statement, Many Variables

• var person = "John Doe", carName = "Volvo",


price = 200;
You can also add strings, but strings
will be concatenated:
• var x = "John" + " " + "Doe";
Output: John Doe
• If you put a number in quotes, the rest of the
numbers will be treated as strings, and
concatenated.
• var x = 2 + 3 + "5";
Output: 55
• var x = "5" + 2 + 3;
Output523
JavaScript String Operators
• The + operator can also be used to add (concatenate)
strings.
txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;
Output:John Doe
• The += assignment operator can also be used to add
(concatenate) strings:
txt1 = "What a very ";
txt1 += "nice day";
Output: What a very nice day
JavaScript Comparison and Logical
Operators
• Comparison and Logical operators are used to
test for true or false.
• Comparison operators are used in logical
statements to determine equality or
difference between variables or values.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 8):</p>

<p id="demo"></p>

<script>
var x = 5;
document.getElementById("demo").innerHTML = (x == 8);
</script>

</body>
</html>
Logical Operators
• Logical operators are used to determine the
logic between variables or values.
• Given that x = 6 and y = 3, the table below
explains the logical operators:
Conditional (Ternary) Operator
• JavaScript also contains a conditional operator
that assigns a value to a variable based on
some condition.
• Syntax
variablename = (condition) ? value1:value2
• var voteable = (age < 18) ? "Too young":"Old
enough";
Output: Old enough
JavaScript If...Else Statements
• Conditional statements are used to perform different
actions based on different conditions.
Very often when you write code, you want to perform
different actions for different decisions.
• You can use conditional statements in your code to do this.
• In JavaScript we have the following conditional statements:
• Use if to specify a block of code to be executed, if a
specified condition is true
• Use else to specify a block of code to be executed, if the
same condition is false
• Use else if to specify a new condition to test, if the first
condition is false
• Use switch to specify many alternative blocks of code to be
executed
Use the if statement to specify a block of
JavaScript code to be executed if a condition is
true.
• if (hour < 18) {
greeting = "Good day";
}
Output: Good Day
The else Statement
• if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
• Output: Good evening
The else if
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Output: Good evening
JavaScript Switch Statement
• The switch statement is used to perform different
actions based on different conditions.
• Use the switch statement to select one of many blocks
of code to be executed.

switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
code block
}
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
Common Code Blocks
• switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
JS FUNCTIONS
• A JavaScript function is a block of code designed to
perform a particular task.
• A JavaScript function is executed when "something"
invokes it (calls it).

<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML =
myFunction(4, 3);
</script>
JavaScript Function Syntax

• A JavaScript function is defined with


the function keyword, followed by a name,
followed by parentheses ().
• Function names can contain letters, digits,
underscores, and dollar signs (same rules as
variables).
• The parentheses may include parameter names
separated by commas:
(parameter1, parameter2, ...)
• The code to be executed, by the function, is
placed inside curly brackets: {}
• Function parameters are the names listed in the
function definition.
• Function arguments are the real values received
by the function when it is invoked.
• Inside the function, the arguments (the
parameters) behave as local variables.
• Function Invocation
• The code inside the function will execute when
"something" invokes (calls) the function:
• When an event occurs (when a user clicks a
button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Function Return
• When JavaScript reaches a return statement, the
function will stop executing.
• If the function was invoked from a statement,
JavaScript will "return" to execute the code after the
invoking statement.
• Functions often compute a return value. The return
value is "returned" back to the "caller":

<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML =
myFunction(4, 3);
</script>
JavaScript Popup Boxes
• JavaScript has three kind of popup boxes: Alert box,
Confirm box, and Prompt box.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<script>
alert("I am an alert box!");
</script>
</body>
</html>
Confirm Box
• A confirm box is often used if you want the
user to verify or accept something.
• When a confirm box pops up, the user will
have to click either "OK" or "Cancel" to
proceed.
• If the user clicks "OK", the box returns true. If
the user clicks "Cancel", the box returns false.
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!") == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
Prompt Box
• A prompt box is often used if you want the
user to input a value before entering a page.
• When a prompt box pops up, the user will
have to click either "OK" or "Cancel" to
proceed after entering an input value.
• If the user clicks "OK" the box returns the
input value. If the user clicks "Cancel" the box
returns null.
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry
Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
Line Breaks
• To display line breaks inside a popup box, use
a back-slash followed by the character n.
• alert("Hello\nHow are you?");
JavaScript For Loop

• Loops can execute a block of code a number of times.


Loops are handy, if you want to run the same code over
and over again, each time with a different value.
• Often this is the case when working with arrays:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
Different Kinds of Loops
• JavaScript supports different kinds of loops:
• for - loops through a block of code a number
of times
• for/in - loops through the properties of an
object
• while - loops through a block of code while a
specified condition is true
• do/while - also loops through a block of code
while a specified condition is true
The For Loop
• The for loop is often the tool you will use when
you want to create a loop.
• The for loop has the following syntax:
• for (statement 1; statement 2; statement 3) {
code block to be executed
}

• Statement 1 is executed before the loop (the


code block) starts.
• Statement 2 defines the condition for running
the loop (the code block).
• Statement 3 is executed each time after the loop
(the code block) has been executed.
<p id="demo"></p> Output
0
<script> 1
var text = ""; 2
var i; 3
for (i = 0; i < 5; i++) { 4
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML
= text;
</script>
The For/In Loop
• The JavaScript for/in statement loops through the
properties of an object:
<p id="demo"></p> Output
<script> John Doe 25
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
JavaScript While Loop

• The While Loop


• The while loop loops through a block of code
as long as a specified condition is true.
Syntax
while (condition) {
code block to be executed
}
<script> Output:
var text = ""; The number is 0
var i = 0; -9
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML
= text;
</script>
The Do/While Loop
• The do/while loop is a variant of the while loop.
This loop will execute the code block once, before
checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do {
code block to be executed
}
while (condition);
<p id="demo"></p>
<script>
var text = "";
var i = 0;
Do{
text += "<br>The number is " + i;
i++;
while (i < 10) {
}
document.getElementById("demo").innerHTML =
text;
</script>

You might also like