JavaScript
Lesson 2
Javascript Placement
Cont
• There is a flexibility given to include JavaScript code anywhere in an HTML
document.
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in <head>...</head> section.
JavaScript in <head>...</head> Section
NB
• The function works when you call it using its name.
• <body> ………. <script> sayHello() </script> ……. </body>
• Or you call it inside another object like button and so on
• <button onclick =“sayHello() "> Click on me </button>
JavaScript in <body>...</body> Section
JavaScript in External File
• The script tag provides a mechanism to allow you to store JavaScript in an
external file and then include it into your HTML files.
• Here is an example to show how you can include an external JavaScript file in
your HTML code using script tag and its src attribute.
Cont
Cont
• To use JavaScript from an external file source, you need to write all your
JavaScript source code in a simple text file with the extension ".js" and then
include that file as shown above.
JAVASCRIPT – VARIABLES
JavaScript Datatypes
• JavaScript allows you to work with three primitive data types:
• • Numbers, e.g., 123, 120.50 etc.
• • Strings of text, e.g. "This text string" etc.
• • Boolean, e.g. true or false.
Cont
• Variables can be thought of as named containers.
• Before you use a variable in a JavaScript program, you must declare it.
Cont
• You can also declare multiple variables with the same var keyword as follows:
Cont
• Storing a value in a variable is called variable initialization.
• For instance, you might create a variable named money and assign the value
2000.50 to it later. For another variable, you can assign a value at the time of
initialization as follows.
Cont
JavaScript Variable Scope
• The scope of a variable is the region of your program in which it is defined.
JavaScript
• variables have only two scopes.
• • Global Variables: A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
• • Local Variables: A local variable will be visible only within a function
where it is defined. Function parameters are always local to that function.
JavaScript Variable Names
• No Keywords
• Not start with Numeral (0-9)
• Case sensitive
JavaScript Reserved Words
• A list of all the reserved words in JavaScript are given in the following table.
They cannot be used as JavaScript variables, functions, methods, loop labels,
or any object names.