We can place the <script> tags, containing our JavaScript, anywhere
within our web page, but it is normally recommended that we should keep it within
the <head> tags.
The script tag takes two important attributes
−
Language − This
attribute specifies what scripting language you are using. Typically, its value will be javascript.
Type − This
attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".
JavaScript segment will look like
<script language ="javascript" type="text/javascript" >
Javascript
</script>
JavaScript is a
case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent capitalization of letters.
Comments in JavaScript
JavaScript supports
both C-style and C++-style comments, Thus −
- Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
- Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
Example
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("HelloWorld!")
</script>
</body>
</html>
<body>
<script language="javascript" type="text/javascript">
document.write("HelloWorld!")
</script>
</body>
</html>
Javascript can be used in both head and body sections.
JavaScript Variable
Variables are declared
with the var keyword as follows.
<script type="text/javascript">
<!--
var money; var name;
//-->
</script>
JavaScript Variable Scope
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.
Example
<body onload = checkscope();>
<script type = "text/javascript">
var myVar = "global"; // Declare a global variable
<script type = "text/javascript">
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>
</body>
</html>
}
</script>
</body>
</html>
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().
The document.write() method should only be used for testing.
No comments:
Post a Comment