0% found this document useful (0 votes)
36 views67 pages

Introduction To Javascript

The document provides an introduction to JavaScript, covering why it is important to learn, what JavaScript is used for, where JavaScript code can be placed, and basic JavaScript syntax including variables, operators, and functions. It also discusses how to output JavaScript values to browsers.

Uploaded by

seyoum shimels
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views67 pages

Introduction To Javascript

The document provides an introduction to JavaScript, covering why it is important to learn, what JavaScript is used for, where JavaScript code can be placed, and basic JavaScript syntax including variables, operators, and functions. It also discusses how to output JavaScript values to browsers.

Uploaded by

seyoum shimels
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 67

INTRODUCTION TO JAVASCRIPT

WHY STUDY JAVASCRIPT?

JavaScript 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


JAVASCRIPT
 JavaScript is the programming language of HTML and the Web.
 Programming makes computers do what you want them to do.
 Change HTML Content
 Change HTML Attributes
 Change HTML Styles (CSS)
 Validate Data
 JavaScript and Java are completely different languages, both in concept and
design.
JAVASCRIPT WHERE TO
 JavaScript can be placed in the <body> and the <head> sections
of an HTML page.
 The <script> Tag

 In HTML, JavaScript code must be inserted between <script> and


</script> tags.
Example
 <script>
document.getElementById("demo").innerHTML = "My First
JavaScript";
</script>
JAVASCRIPT IN <HEAD>
 In this example, a JavaScript function is placed in the <head> section of an
HTML page.
 The function is invoked (called) when a button is clicked:
 Example
 <!DOCTYPE html>
<html><head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JAVASCRIPT IN <BODY>
 In this example, a JavaScript function is placed in the <body> section of an
HTML page.
 The function is invoked (called) when a button is clicked:
 Example
 <!DOCTYPE html>
<html>
<body>
<h1>My 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>
 It is a good idea to place scripts at the bottom of the
<body> element.
This can improve page load, because script compilation
can slow down the display.
EXTERNAL JAVASCRIPT
 Scripts can also be placed in external files:
myScript.js
 function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
 External scripts are practical when the same code is used in many different
web pages.
 JavaScript files have the file extension .js.
 To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
 Example
 <!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
EXTERNAL JAVASCRIPT
 You can place an external script reference in <head> or <body>
as you like.
 The script will behave as if it was located exactly where the
<script> tag is located.
 External scripts cannot contain <script> tags.

External JavaScript Advantages


 Placing JavaScripts in external files has some advantages:
 It separates HTML and code

 It makes HTML and JavaScript easier to read and maintain

 Cached JavaScript files can speed up page loads


JAVASCRIPT OUTPUT
 JavaScript does NOT have any built-in print or display functions.
JavaScript Display Possibilities
 JavaScript can "display" data in different ways:
 Writing into an alert box, using window.alert().
 Writing into the HTML output using document.write().
 Writing into an HTML element, using innerHTML.
 Writing into the browser console, using console.log().
USING WINDOW.ALERT()
 You can use an alert box to display data:
 Example

 <!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
USING DOCUMENT.WRITE()
 For testing purposes, it is convenient to use document.write():
 Example

 <!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:
 <button onclick="document.write(5 + 6)">Try it</button>
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:
 Example

 <!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 CONSOLE.LOG()
 In your browser, you can use the console.log() method to display
data.
 Activate the browser console with F12, and select "Console" in
the menu.
 Example

 <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JAVASCRIPT SYNTAX
 JavaScript syntax is the set of rules, how JavaScript programs
are constructed
JavaScript Programs.
 A computer program is a list of "instructions" to be "executed"
by the computer.
 In a programming language, these program instructions are
called statements.
 JavaScript is a programming language.

 JavaScript statements are separated by semicolons.

 Example

 var x = 5;
var y = 6;
var z = x + y;
JAVASCRIPT SYNTAX
JavaScript Statements
 JavaScript statements are composed of:
 Values, Operators, Expressions, Keywords, and Comments.
JavaScript Values
 The JavaScript syntax defines two types of values: Fixed values and
variable values.
 Fixed values are called literals. Variable values are called variables.
JavaScript Literals
 The most important rules for writing fixed values are:
 Numbers are written with or without decimals:
 10.50
1001
 Strings are text, written within double or single quotes:
 "John Doe"
'John Doe'
JAVASCRIPT SYNTAX
JavaScript Variables
 In a programming language, variables are used to store data values.
 JavaScript uses the var keyword to declare variables.
 An equal sign is used to assign values to variables.
 In this example, x is defined as a variable. Then, x is assigned (given) the
value 6:
 var x;
x = 6;
JavaScript Operators
 JavaScript uses an assignment operator ( = ) to assign values to variables:
 var x = 5;
var y = 6;
 JavaScript uses arithmetic operators ( + - * / ) to compute values:
 (5 + 6) * 10
JAVASCRIPT SYNTAX
JavaScript Expressions
 An expression is a combination of values, variables, and operators, which
computes to a value.
 The computation is called an evaluation.
 For example, 5 * 10 evaluates to 50:
 5 * 10
 Expressions can also contain variable values:
 x * 10
 The values can be of various types, such as numbers and strings.
 For example, "John" + " " + "Doe", evaluates to "John Doe":
JavaScript Keywords
 JavaScript keywords are used to identify actions to be performed.
 The var keyword tells the browser to create a new variable:
 var x = 5 + 6;
var y = x * 10;
JAVASCRIPT SYNTAX
JavaScript Comments
 Not all JavaScript statements are "executed".

 Code after double slashes // or between /* and */ is treated as a


comment.
 Comments are ignored, and will not be executed:

 var x = 5; // I will be executed

// var x = 6; I will NOT be executed


JavaScript Character Set
 JavaScript uses the Unicode character set.

 Unicode covers (almost) all the characters, punctuations, and


symbols in the world.
JAVASCRIPT SYNTAX
JavaScript Identifiers
 Identifiers are names.

 In JavaScript, identifiers are used to name variables (and


keywords, and functions, and labels).
 The rules for legal names are much the same in most
programming languages.
 In JavaScript, the first character must be a letter, an underscore
(_), or a dollar sign ($).
 Subsequent characters may be letters, digits, underscores, or
dollar signs.
 Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from
numbers.
JAVASCRIPT SYNTAX
JavaScript is Case Sensitive
 All JavaScript identifiers are case sensitive.

 The variables lastName and lastname, are two different


variables.
 lastName = "Doe";
lastname = "Peterson";
 JavaScript does not interpret VAR or Var as the keyword var.
JAVASCRIPT SYNTAX
JavaScript and Camel Case
 Historically, programmers have used three ways of joining
multiple words into one variable name:
 Hyphens:

 first-name, last-name, master-card, inter-city.

 Underscore:

 first_name, last_name, master_card, inter_city.

 Camel Case:

 FirstName, LastName, MasterCard, InterCity.

 In programming languages, especially in JavaScript, camel case


often starts with a lowercase letter:
 firstName, lastName, masterCard, interCity.

 Hyphens are not allowed in JavaScript. It is reserved for


subtractions.
JAVASCRIPT STATEMENTS
 In HTML, JavaScript statements are "instructions" to be "executed" by the
web browser.
 This statement tells the browser to write "Hello Dolly." inside an HTML
element with id="demo":
 Example
 document.getElementById("demo").innerHTML = "Hello Dolly.";
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:
 Example
 var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
Example
<!DOCTYPE html>
<html>
<body>
<p>JavaScript code (or just JavaScript) is a list of JavaScript
statements.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
JAVASCRIPT STATEMENTS
Semicolons ;
 Semicolons separate JavaScript statements.
 Add a semicolon at the end of each executable statement:
 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";
 A good practice is to put spaces around operators ( = + - * / ):
 var x = y + z;
JAVASCRIPT STATEMENTS
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:
 Example

 document.getElementById("demo").innerHTML =
"Hello Dolly.";
JAVASCRIPT STATEMENTS
JavaScript Code Blocks
 JavaScript statements can be grouped together in code blocks,
inside curly brackets {...}.
 The purpose of code blocks is to define statements to be
executed together.
 One place you will find statements grouped together in blocks,
are in JavaScript functions:
 Example

 function myFunction() {
document.getElementById("demo").innerHTML = "Hello
Dolly.";
document.getElementById("myDIV").innerHTML = "How
are you?";
}
JAVASCRIPT STATEMENTS
JavaScript Keywords
 JavaScript statements often start with a keyword to identify the
JavaScript action to be performed.
 Here is a list of some of the keywords you will learn about in
this tutorial:
Keyword Description

break Terminates a switch or a loop

continue Jumps out of a loop and starts at the top

debugger Stops the execution of JavaScript, and calls (if available) the debugging function

do ... while Executes a block of statements, and repeats the block, while a condition is true

for Marks a block of statements to be executed, as long as a condition is true

function Declares a function

if ... else Marks a block of statements to be executed, depending on a condition

return Exits a function

switch Marks a block of statements to be executed, depending on different cases

try ... catch Implements error handling to a block of statements

var Declares a variable


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).
 Example

 var x = 5; // Declare x, give it the value of 5


var y = x + 2; // Declare y, give it the value of x + 2
JAVASCRIPT COMMENTS
 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:
*/
 Using comments to prevent execution of code, is suitable for
code testing.
 Adding // in front of a code line changes the code lines from an
executable line to a comment.
JAVASCRIPT COMMENTS
 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:
*/
 Using comments to prevent execution of code, is suitable for
code testing.
 Adding // in front of a code line changes the code lines from an
executable line to a comment.
JAVASCRIPT VARIABLES

 JavaScript variables are containers for storing data


values.
 In this example, x, y, and z, are variables:

 Example

 var x = 5;
var y = 6;
var z = x + y;
 All JavaScript variables must be identified with unique
names.
 These unique names are called identifiers.
JAVASCRIPT 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 _ (but we will not use it in
this tutorial)
 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.)
 The "equal to" operator is written like == in JavaScript.
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 quotes around a number, it will be treated as a text
string.
 Example

 var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
DECLARING (CREATING) JAVASCRIPT
VARIABLES
 Creating a variable in JavaScript is called "declaring" a
variable.
 You declare a JavaScript variable with the var keyword:

var carName;
 After the declaration, the variable has no value. (Technically
it has the value of undefined)
 To assign a value to the variable, use the equal sign:

carName = "Volvo";
 You can also assign a value to the variable when you declare
it:
 var carName = "Volvo";

 var person = "John Doe", carName = "Volvo", price = 200;


EXAMPLE
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>Create a variable, assign a value to it, and display it:</p>
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
</body>
</html>
VALUE = UNDEFINED

 In computer programs, variables are often declared


without a value. The value can be something that has to
be calculated, or something that will be provided later,
like user input.
 A variable declared without a value will have the value
undefined.
 The variable carName will have the value undefined
after the execution of this statement:
 Example

 var carName;
RE-DECLARING JAVASCRIPT VARIABLES

 If you re-declare a JavaScript variable, it will not lose its


value.
 The variable carName will still have the value "Volvo"
after the execution of these statements:
 Example

 var carName = "Volvo";


var carName;
JAVASCRIPT ARITHMETIC
 As with algebra, you can do arithmetic with JavaScript
variables, using operators like = and +:
 Example

var x = 5 + 2 + 3;
 You can also add strings, but strings will be concatenated
(added end-to-end):
 Example

var x = "John" + " " + "Doe";


JAVASCRIPT ARITHMETIC
OPERATORS

 Arithmetic operators are used to perform arithmetic on


numbers (literals or variables).
JAVASCRIPT ASSIGNMENT
OPERATORS
 Assignment operators assign values to JavaScript
variables.
JAVASCRIPT COMPARISON AND LOGICAL
OPERATORS
OPERATORS AND OPERANDS
 The numbers (in an arithmetic operation) are called
operands.
 The operation (to be performed between the two operands) is
defined by an operator.
 Operand Operator Operand 100 + 50
JAVASCRIPT DATA TYPES
 JavaScript variables can hold many data types: numbers,
strings, arrays, objects and more:

 JavaScript evaluates expressions from left to right. Different


sequences can produce different results:
 var x = 16 + 4 + "Volvo";

 var x = "Volvo" + 16 + 4;
JAVASCRIPT HAS DYNAMIC TYPES

 JavaScript has dynamic types. This means that the same


variable can be used as different types:
 Example

 var x; // Now x is undefined


var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
JAVASCRIPT STRINGS

 A string (or a text string) is a series of characters like


"John Doe".
 Strings are written with quotes. You can use single or
double quotes:

 Example
 var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
JAVASCRIPT NUMBERS

 JavaScript has only one type of numbers.


 Numbers can be written with, or without decimals:

 Example
 var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
JAVASCRIPT BOOLEANS
 Booleans can only have two values: true or false.
 Example

 var x = true;
var y = false;
JAVASCRIPT ARRAYS

 JavaScript arrays are written with square brackets.


 Array items are separated by commas.

 The following code declares (creates) an array called


cars, containing three items (car names):
 Example

 var cars = ["Saab", "Volvo", "BMW"];

 Array indexes are zero-based, which means the first item


is [0], second is [1], and so on.
JAVASCRIPT OBJECTS

 JavaScript objects are written with curly braces.


 Object properties are written as name:value pairs,
separated by commas.
 Example

 var person = {firstName:"John", lastName:"Doe",


age:50, eyeColor:"blue"};
 The object (person) in the example above has 4
properties: firstName, lastName, age, and eyeColor.
JAVASCRIPT 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).

function myFunction(p1, p2) {


return p1 * p2; // The function returns the
product of p1 and p2
}
<!DOCTYPE html>
<html>
<body>
<p>This example calls a function which performs a calculation, and
returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
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: {}
JAVASCRIPT FUNCTION SYNTAX
 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 behave as local variables.

function myFunction(p1, p2) {


return p1 * p2; // The function returns the product of
p1 and p2
}

document.getElementById("demo").innerHTML = myFunction(4,
3);
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)

 <input type="button" onClick="compare()"


Value="Compute" />
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":
CONDITIONAL 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
THE IF STATEMENT
 Use the if statement to specify a block of JavaScript code
to be executed if a condition is true.
 Syntax

if (condition) {
block of code to be executed if the condition is true
}
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<p>Display “Not Allowed!" if the age is less than 18</p>
<p id=“ag"></p>
<script>
Var age=14;
if (age < 18) {
document.getElementById(“ag").innerHTML = “Not Allowed!";
}
</script>
</body>
THE ELSE STATEMENT

 Use the else statement to specify a block of code to be


executed if the condition is false.
 Syntax

if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<p>Display “Not Allowed!" if the age is less than 18 else print Allowed</p>
<p id=“ag"></p>
<script>
Var age=14;
if (age < 18) {
document.getElementById(“ag").innerHTML = “Not Allowed!";
}
else{
document.getElementById(“ag").innerHTML = “Allowed!";
}
</script>
</body>
THE ELSE IF STATEMENT
 Use the else if statement to specify a new condition if the
first condition is false.
 Syntax

if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false
and condition2 is true
} else {
block of code to be executed if the condition1 is false
and condition2 is false
}
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<p> Comparing Numbers</p>
<p id=“comp"></p>
<script>
Var x=14;
Var y=14;
if (x > y) {
document.getElementById(“comp").innerHTML =x+ “is gratest";
}
else if (y> x) {
document.getElementById(“comp").innerHTML =y+ “is gratest";
}
else {
document.getElementById(“comp").innerHTML = “both are equal";
}
</script>
</body>
THE 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.
 Syntax
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
 This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
THE BREAK KEYWORD
 When the JavaScript code interpreter reaches
a break keyword, it breaks out of the switch block.
 This will stop the execution of more code and case testing
inside the block.
The default Keyword
 The default keyword specifies the code to run if there is no
case match:
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<input id="myInput" type="text" value="Tutti Frutti">
<button onclick="checkFruit()">Check Fruit</button>
<p id="demo"></p>
<script>
function checkFruit() {
var text;
var fruits = document.getElementById("myInput").value;
switch(fruits) {
case "Banana":
text = "Banana is good!";
break;
case "Orange":
text = "I am not a fan of orange.";
break;
case "Apple":
text = "How you like them apples?";
break;
// add the default keyword here
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>

You might also like